blob: b62b3e10147ca3d6bfec0a9b66e01ff926a20edc [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
Sergey Ulanovc4580e72017-09-13 23:30:11171#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
172 !defined(OS_FUCHSIA)
mmenke9f2ec60c2015-06-01 20:59:47173// Test file used in most FTP tests.
174const char kFtpTestFile[] = "BullRunSpeech.txt";
175#endif
176
[email protected]2bba3252013-04-08 19:50:59177// Tests load timing information in the case a fresh connection was used, with
178// no proxy.
[email protected]cba24642014-08-15 20:49:59179void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25180 int connect_timing_flags) {
181 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19182 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25183
184 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
185 EXPECT_FALSE(load_timing_info.request_start.is_null());
186
187 EXPECT_LE(load_timing_info.request_start,
188 load_timing_info.connect_timing.connect_start);
189 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
190 connect_timing_flags);
191 EXPECT_LE(load_timing_info.connect_timing.connect_end,
192 load_timing_info.send_start);
193 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
194 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
195
[email protected]58e32bb2013-01-21 18:23:25196 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
197 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
198}
199
[email protected]2bba3252013-04-08 19:50:59200// Same as above, but with proxy times.
201void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59202 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59203 int connect_timing_flags) {
204 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19205 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59206
207 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
208 EXPECT_FALSE(load_timing_info.request_start.is_null());
209
210 EXPECT_LE(load_timing_info.request_start,
211 load_timing_info.proxy_resolve_start);
212 EXPECT_LE(load_timing_info.proxy_resolve_start,
213 load_timing_info.proxy_resolve_end);
214 EXPECT_LE(load_timing_info.proxy_resolve_end,
215 load_timing_info.connect_timing.connect_start);
216 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
217 connect_timing_flags);
218 EXPECT_LE(load_timing_info.connect_timing.connect_end,
219 load_timing_info.send_start);
220 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
221 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
222}
223
224// Same as above, but with a reused socket and proxy times.
225void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59226 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59227 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19228 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59229
230 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
231 EXPECT_FALSE(load_timing_info.request_start.is_null());
232
233 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
234
235 EXPECT_LE(load_timing_info.request_start,
236 load_timing_info.proxy_resolve_start);
237 EXPECT_LE(load_timing_info.proxy_resolve_start,
238 load_timing_info.proxy_resolve_end);
239 EXPECT_LE(load_timing_info.proxy_resolve_end,
240 load_timing_info.send_start);
241 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
242 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
243}
244
brettwa1228ebb2016-10-28 03:51:34245#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25246// Tests load timing information in the case of a cache hit, when no cache
247// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17248base::StringPiece TestNetResourceProvider(int key) {
249 return "header";
250}
251
252void FillBuffer(char* buffer, size_t len) {
253 static bool called = false;
254 if (!called) {
255 called = true;
256 int seed = static_cast<int>(Time::Now().ToInternalValue());
257 srand(seed);
258 }
259
260 for (size_t i = 0; i < len; i++) {
261 buffer[i] = static_cast<char>(rand());
262 if (!buffer[i])
263 buffer[i] = 'g';
264 }
265}
xunjielia6888202015-04-14 21:34:25266#endif
[email protected]e3a85452013-11-14 01:46:17267
[email protected]3b23a222013-05-15 21:33:25268void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59269 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25270 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19271 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25272
273 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
274 EXPECT_FALSE(load_timing_info.request_start.is_null());
275
276 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
277 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
278 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
279 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
280
281 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
282 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
283}
284
Sergey Ulanovc4580e72017-09-13 23:30:11285#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
286 !defined(OS_FUCHSIA)
[email protected]3b23a222013-05-15 21:33:25287// Tests load timing in the case that there is no HTTP response. This can be
288// used to test in the case of errors or non-HTTP requests.
289void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59290 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25291 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19292 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25293
294 // Only the request times should be non-null.
295 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
296 EXPECT_FALSE(load_timing_info.request_start.is_null());
297
298 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
299
300 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
301 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
302 EXPECT_TRUE(load_timing_info.send_start.is_null());
303 EXPECT_TRUE(load_timing_info.send_end.is_null());
304 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
305}
xunjielia6888202015-04-14 21:34:25306#endif
[email protected]58e32bb2013-01-21 18:23:25307
mmenkefb18c772015-09-30 22:22:50308// Test power monitor source that can simulate entering suspend mode. Can't use
309// the one in base/ because it insists on bringing its own MessageLoop.
310class TestPowerMonitorSource : public base::PowerMonitorSource {
311 public:
312 TestPowerMonitorSource() {}
313 ~TestPowerMonitorSource() override {}
314
315 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
316
317 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
318
319 bool IsOnBatteryPowerImpl() override { return false; }
320
321 private:
322 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
323};
324
mmenkeed0498b2015-12-08 23:20:42325// Job that allows monitoring of its priority.
326class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
327 public:
328 // The latest priority of the job is always written to |request_priority_|.
329 PriorityMonitoringURLRequestJob(URLRequest* request,
330 NetworkDelegate* network_delegate,
331 RequestPriority* request_priority)
332 : URLRequestTestJob(request, network_delegate),
333 request_priority_(request_priority) {
334 *request_priority_ = DEFAULT_PRIORITY;
335 }
336
337 void SetPriority(RequestPriority priority) override {
338 *request_priority_ = priority;
339 URLRequestTestJob::SetPriority(priority);
340 }
341
342 private:
343 RequestPriority* const request_priority_;
344};
345
[email protected]71c64f62008-11-15 04:36:51346// Do a case-insensitive search through |haystack| for |needle|.
347bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50348 std::string::const_iterator it = std::search(
349 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
350 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51351 return it != haystack.end();
352}
353
danakj8522a25b2016-04-16 00:17:36354std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
355 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28356 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48357 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23358}
359
[email protected]96adadb2010-08-28 01:16:17360// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51361void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17362 // -1 means unknown. 0 means no encryption.
363 EXPECT_GT(ssl_info.security_bits, 0);
364
365 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14366 uint16_t cipher_suite =
367 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29368 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17369}
370
[email protected]79e1fd62013-06-20 06:50:04371void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
372 const GURL& host_url) {
373 std::string sent_value;
374
375 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
376 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
377
378 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
379 EXPECT_EQ("keep-alive", sent_value);
380}
381
[email protected]dc5a5cf2012-09-26 02:49:30382// A network delegate that allows the user to choose a subset of request stages
383// to block in. When blocking, the delegate can do one of the following:
384// * synchronously return a pre-specified error code, or
385// * asynchronously return that value via an automatically called callback,
386// or
387// * block and wait for the user to do a callback.
388// Additionally, the user may also specify a redirect URL -- then each request
389// with the current URL different from the redirect target will be redirected
390// to that target, in the on-before-URL-request stage, independent of whether
391// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12392class BlockingNetworkDelegate : public TestNetworkDelegate {
393 public:
[email protected]dc5a5cf2012-09-26 02:49:30394 // Stages in which the delegate can block.
395 enum Stage {
[email protected]9045b8822012-01-13 20:35:35396 NOT_BLOCKED = 0,
397 ON_BEFORE_URL_REQUEST = 1 << 0,
398 ON_BEFORE_SEND_HEADERS = 1 << 1,
399 ON_HEADERS_RECEIVED = 1 << 2,
400 ON_AUTH_REQUIRED = 1 << 3
401 };
402
[email protected]dc5a5cf2012-09-26 02:49:30403 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59404 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30405 enum BlockMode {
406 SYNCHRONOUS, // No callback, returns specified return values.
407 AUTO_CALLBACK, // |this| posts a task to run the callback using the
408 // specified return codes.
409 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
410 // |auth_retval_| are ignored. In every blocking stage the
411 // message loop is quit.
rdsmithbf8c3c12016-11-18 18:16:24412 USER_NOTIFY, // User is notified by a provided callback of the
413 // blocking, and synchronously returns instructions
414 // for handling it.
[email protected]dc5a5cf2012-09-26 02:49:30415 };
416
rdsmithbf8c3c12016-11-18 18:16:24417 using NotificationCallback =
418 base::Callback<Error(const CompletionCallback&, const URLRequest*)>;
419
420 using NotificationAuthCallback =
421 base::Callback<NetworkDelegate::AuthRequiredResponse(const AuthCallback&,
422 const URLRequest*)>;
423
[email protected]dc5a5cf2012-09-26 02:49:30424 // Creates a delegate which does not block at all.
425 explicit BlockingNetworkDelegate(BlockMode block_mode);
426
427 // For users to trigger a callback returning |response|.
428 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
429 // Only call if |block_mode_| == USER_CALLBACK.
430 void DoCallback(int response);
431 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
432
433 // Setters.
434 void set_retval(int retval) {
435 ASSERT_NE(USER_CALLBACK, block_mode_);
436 ASSERT_NE(ERR_IO_PENDING, retval);
437 ASSERT_NE(OK, retval);
438 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35439 }
440
[email protected]dc5a5cf2012-09-26 02:49:30441 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
442 // |auth_credentials_| will be passed with the response.
443 void set_auth_retval(AuthRequiredResponse auth_retval) {
444 ASSERT_NE(USER_CALLBACK, block_mode_);
445 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
446 auth_retval_ = auth_retval;
447 }
448 void set_auth_credentials(const AuthCredentials& auth_credentials) {
449 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35450 }
451
[email protected]dc5a5cf2012-09-26 02:49:30452 void set_redirect_url(const GURL& url) {
453 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35454 }
455
[email protected]dc5a5cf2012-09-26 02:49:30456 void set_block_on(int block_on) {
457 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35458 }
459
rdsmithbf8c3c12016-11-18 18:16:24460 // Only valid if |block_mode_| == USER_NOTIFY
461 void set_notification_callback(
462 const NotificationCallback& notification_callback) {
463 notification_callback_ = notification_callback;
464 }
465
466 void set_notification_auth_callback(
467 const NotificationAuthCallback& notification_auth_callback) {
468 notification_auth_callback_ = notification_auth_callback;
469 }
470
[email protected]dc5a5cf2012-09-26 02:49:30471 // Allows the user to check in which state did we block.
472 Stage stage_blocked_for_callback() const {
473 EXPECT_EQ(USER_CALLBACK, block_mode_);
474 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35475 }
476
477 private:
[email protected]dc5a5cf2012-09-26 02:49:30478 void RunCallback(int response, const CompletionCallback& callback);
479 void RunAuthCallback(AuthRequiredResponse response,
480 const AuthCallback& callback);
481
[email protected]9045b8822012-01-13 20:35:35482 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20483 int OnBeforeURLRequest(URLRequest* request,
484 const CompletionCallback& callback,
485 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35486
ryansturm2343cb62016-06-15 01:09:00487 int OnBeforeStartTransaction(URLRequest* request,
488 const CompletionCallback& callback,
489 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35490
dchengb03027d2014-10-21 12:00:20491 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35492 URLRequest* request,
493 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32494 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16495 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13496 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35497
dchengb03027d2014-10-21 12:00:20498 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35499 URLRequest* request,
500 const AuthChallengeInfo& auth_info,
501 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13502 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35503
[email protected]dc5a5cf2012-09-26 02:49:30504 // Resets the callbacks and |stage_blocked_for_callback_|.
505 void Reset();
[email protected]9045b8822012-01-13 20:35:35506
[email protected]dc5a5cf2012-09-26 02:49:30507 // Checks whether we should block in |stage|. If yes, returns an error code
508 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
rdsmithbf8c3c12016-11-18 18:16:24509 int MaybeBlockStage(Stage stage,
510 const URLRequest* request,
511 const CompletionCallback& callback);
[email protected]dc5a5cf2012-09-26 02:49:30512
513 // Configuration parameters, can be adjusted by public methods:
514 const BlockMode block_mode_;
515
516 // Values returned on blocking stages when mode is SYNCHRONOUS or
517 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
518 int retval_; // To be returned in non-auth stages.
519 AuthRequiredResponse auth_retval_;
520
[email protected]5f714132014-03-26 10:41:16521 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30522 int block_on_; // Bit mask: in which stages to block.
523
524 // |auth_credentials_| will be copied to |*target_auth_credential_| on
525 // callback.
526 AuthCredentials auth_credentials_;
527 AuthCredentials* target_auth_credentials_;
528
529 // Internal variables, not set by not the user:
530 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
531 // USER_CALLBACK).
532 Stage stage_blocked_for_callback_;
533
534 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35535 CompletionCallback callback_;
536 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30537
rdsmithbf8c3c12016-11-18 18:16:24538 // Callback to request user instructions for blocking.
539 NotificationCallback notification_callback_;
540 NotificationAuthCallback notification_auth_callback_;
541
[email protected]dc5a5cf2012-09-26 02:49:30542 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
543
544 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35545};
546
[email protected]dc5a5cf2012-09-26 02:49:30547BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
548 : block_mode_(block_mode),
549 retval_(OK),
550 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
551 block_on_(0),
552 target_auth_credentials_(NULL),
553 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32554 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30555}
556
557void BlockingNetworkDelegate::DoCallback(int response) {
558 ASSERT_EQ(USER_CALLBACK, block_mode_);
559 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
560 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
561 CompletionCallback callback = callback_;
562 Reset();
563 RunCallback(response, callback);
564}
565
566void BlockingNetworkDelegate::DoAuthCallback(
567 NetworkDelegate::AuthRequiredResponse response) {
568 ASSERT_EQ(USER_CALLBACK, block_mode_);
569 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
570 AuthCallback auth_callback = auth_callback_;
571 Reset();
572 RunAuthCallback(response, auth_callback);
573}
574
575void BlockingNetworkDelegate::RunCallback(int response,
576 const CompletionCallback& callback) {
577 callback.Run(response);
578}
579
580void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
581 const AuthCallback& callback) {
582 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
583 ASSERT_TRUE(target_auth_credentials_ != NULL);
584 *target_auth_credentials_ = auth_credentials_;
585 }
586 callback.Run(response);
587}
588
589int BlockingNetworkDelegate::OnBeforeURLRequest(
590 URLRequest* request,
591 const CompletionCallback& callback,
592 GURL* new_url) {
593 if (redirect_url_ == request->url())
594 return OK; // We've already seen this request and redirected elsewhere.
595
596 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
597
598 if (!redirect_url_.is_empty())
599 *new_url = redirect_url_;
600
rdsmithbf8c3c12016-11-18 18:16:24601 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30602}
603
ryansturm2343cb62016-06-15 01:09:00604int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30605 URLRequest* request,
606 const CompletionCallback& callback,
607 HttpRequestHeaders* headers) {
ryansturm2343cb62016-06-15 01:09:00608 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]dc5a5cf2012-09-26 02:49:30609
rdsmithbf8c3c12016-11-18 18:16:24610 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30611}
612
613int BlockingNetworkDelegate::OnHeadersReceived(
614 URLRequest* request,
615 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32616 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16617 scoped_refptr<HttpResponseHeaders>* override_response_headers,
618 GURL* allowed_unsafe_redirect_url) {
619 TestNetworkDelegate::OnHeadersReceived(request,
620 callback,
621 original_response_headers,
622 override_response_headers,
623 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30624
rdsmithbf8c3c12016-11-18 18:16:24625 return MaybeBlockStage(ON_HEADERS_RECEIVED, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30626}
627
628NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
629 URLRequest* request,
630 const AuthChallengeInfo& auth_info,
631 const AuthCallback& callback,
632 AuthCredentials* credentials) {
633 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
634 credentials);
635 // Check that the user has provided callback for the previous blocked stage.
636 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
637
638 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
639 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
640 }
641
642 target_auth_credentials_ = credentials;
643
644 switch (block_mode_) {
645 case SYNCHRONOUS:
646 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
647 *target_auth_credentials_ = auth_credentials_;
648 return auth_retval_;
649
650 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45651 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30652 FROM_HERE,
653 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
654 weak_factory_.GetWeakPtr(), auth_retval_, callback));
655 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
656
657 case USER_CALLBACK:
658 auth_callback_ = callback;
659 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45660 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17661 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30662 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
rdsmithbf8c3c12016-11-18 18:16:24663
664 case USER_NOTIFY:
665 // If the callback returns ERR_IO_PENDING, the user has accepted
666 // responsibility for running the callback in the future.
667 return notification_auth_callback_.Run(callback, request);
[email protected]dc5a5cf2012-09-26 02:49:30668 }
669 NOTREACHED();
670 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
671}
672
673void BlockingNetworkDelegate::Reset() {
674 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
675 stage_blocked_for_callback_ = NOT_BLOCKED;
676 callback_.Reset();
677 auth_callback_.Reset();
678}
679
680int BlockingNetworkDelegate::MaybeBlockStage(
681 BlockingNetworkDelegate::Stage stage,
rdsmithbf8c3c12016-11-18 18:16:24682 const URLRequest* request,
[email protected]dc5a5cf2012-09-26 02:49:30683 const CompletionCallback& callback) {
684 // Check that the user has provided callback for the previous blocked stage.
685 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
686
687 if ((block_on_ & stage) == 0) {
688 return OK;
689 }
690
691 switch (block_mode_) {
692 case SYNCHRONOUS:
693 EXPECT_NE(OK, retval_);
694 return retval_;
695
696 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45697 base::ThreadTaskRunnerHandle::Get()->PostTask(
698 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
699 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30700 return ERR_IO_PENDING;
701
702 case USER_CALLBACK:
703 callback_ = callback;
704 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45705 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17706 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30707 return ERR_IO_PENDING;
rdsmithbf8c3c12016-11-18 18:16:24708
709 case USER_NOTIFY:
710 // If the callback returns ERR_IO_PENDING, the user has accepted
711 // responsibility for running the callback in the future.
712 return notification_callback_.Run(callback, request);
[email protected]dc5a5cf2012-09-26 02:49:30713 }
714 NOTREACHED();
715 return 0;
716}
717
[email protected]d5a4dd62012-05-23 01:41:04718class TestURLRequestContextWithProxy : public TestURLRequestContext {
719 public:
720 // Does not own |delegate|.
721 TestURLRequestContextWithProxy(const std::string& proxy,
722 NetworkDelegate* delegate)
723 : TestURLRequestContext(true) {
724 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
725 set_network_delegate(delegate);
726 Init();
727 }
dchengb03027d2014-10-21 12:00:20728 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04729};
730
stefanocsbd5be5202016-06-10 03:37:55731// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01732// URI and report to be sent.
733class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55734 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01735 public:
736 MockCertificateReportSender() {}
737 ~MockCertificateReportSender() override {}
738
meacer5d4dc5a2017-04-27 20:37:48739 void Send(const GURL& report_uri,
740 base::StringPiece content_type,
741 base::StringPiece report,
742 const base::Callback<void()>& success_callback,
743 const base::Callback<void(const GURL&, int, int)>& error_callback)
744 override {
estark06e0dac2015-08-07 21:56:01745 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44746 report.CopyToString(&latest_report_);
747 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01748 }
estark06e0dac2015-08-07 21:56:01749 const GURL& latest_report_uri() { return latest_report_uri_; }
750 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44751 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01752
753 private:
754 GURL latest_report_uri_;
755 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44756 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01757};
758
estarkcd39c11f2015-10-19 19:46:36759class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
760 public:
761 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
762};
763
dadrian612337a2016-07-20 22:36:58764// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
765// This is needed because after the certificate failure, the URLRequest will
766// retry the connection, and return a partial SSLInfo with a cached cert status.
767// The partial SSLInfo does not have the OCSP information filled out.
768class OCSPErrorTestDelegate : public TestDelegate {
769 public:
770 void OnSSLCertificateError(URLRequest* request,
771 const SSLInfo& ssl_info,
772 bool fatal) override {
773 ssl_info_ = ssl_info;
774 on_ssl_certificate_error_called_ = true;
775 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
776 }
777
778 bool on_ssl_certificate_error_called() {
779 return on_ssl_certificate_error_called_;
780 }
781
782 SSLInfo ssl_info() { return ssl_info_; }
783
784 private:
785 bool on_ssl_certificate_error_called_ = false;
786 SSLInfo ssl_info_;
787};
788
[email protected]d5a4dd62012-05-23 01:41:04789} // namespace
790
[email protected]a592c0432012-12-01 18:10:29791// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48792class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00793 public:
fdorayf33fede2017-05-11 21:18:10794 URLRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:09795 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25796 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50797 job_factory_impl_ = new URLRequestJobFactoryImpl();
798 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50799 }
bengr1bf8e942014-11-07 01:36:50800
dcheng67be2b1f2014-10-27 21:47:29801 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18802 // URLRequestJobs may post clean-up tasks on destruction.
803 base::RunLoop().RunUntilIdle();
804 }
[email protected]87a09a92011-07-14 15:50:50805
dcheng2339883c2014-12-23 00:23:05806 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50807 SetUpFactory();
808 default_context_.set_job_factory(job_factory_.get());
809 default_context_.Init();
810 PlatformTest::SetUp();
811 }
812
813 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20814 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36815 "data", base::WrapUnique(new DataProtocolHandler));
brettwa1228ebb2016-10-28 03:51:34816#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50817 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19818 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07819 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50820#endif
821 }
822
823 TestNetworkDelegate* default_network_delegate() {
824 return &default_network_delegate_;
825 }
826
827 const TestURLRequestContext& default_context() const {
828 return default_context_;
829 }
830
831
[email protected]3c5ca8c2011-09-29 01:14:51832 // Adds the TestJobInterceptor to the default context.
833 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23834 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20835 job_factory_impl_->SetProtocolHandler("http", nullptr);
836 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36837 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23838 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51839 }
840
Sergey Ulanov2e49f492017-09-14 19:37:51841 // Creates a temp test file and writes |data| to the file. The file will be
842 // deleted after the test completes.
843 void CreateTestFile(const char* data,
844 size_t data_size,
845 base::FilePath* test_file) {
846 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
847 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
848 // now, Mac and Android bots return a path with a symbolic link.
849 base::FilePath absolute_temp_dir =
850 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
851
852 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
853 ASSERT_EQ(static_cast<int>(data_size),
854 base::WriteFile(*test_file, data, data_size));
855 }
856
[email protected]87a09a92011-07-14 15:50:50857 protected:
vishal.b62985ca92015-04-17 08:45:51858 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24859 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50860 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36861 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09862 TestURLRequestContext default_context_;
Sergey Ulanov2e49f492017-09-14 19:37:51863 base::ScopedTempDir temp_dir_;
[email protected]7a0bb4bf2008-11-19 21:41:48864};
865
satoruxddac0442017-05-29 06:06:18866// This NetworkDelegate is picky about what files are accessible. Only
867// whitelisted files are allowed.
868class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
869 public:
870 CookieBlockingNetworkDelegate(){};
871
872 // Adds |directory| to the access white list.
873 void AddToWhitelist(const base::FilePath& directory) {
874 whitelist_.insert(directory);
875 }
876
877 private:
878 // Returns true if |path| matches the white list.
879 bool OnCanAccessFileInternal(const base::FilePath& path) const {
880 for (const auto& directory : whitelist_) {
881 if (directory == path || directory.IsParent(path))
882 return true;
883 }
884 return false;
885 }
886
887 // Returns true only if both |original_path| and |absolute_path| match the
888 // white list.
889 bool OnCanAccessFile(const URLRequest& request,
890 const base::FilePath& original_path,
891 const base::FilePath& absolute_path) const override {
892 return (OnCanAccessFileInternal(original_path) &&
893 OnCanAccessFileInternal(absolute_path));
894 }
895
896 std::set<base::FilePath> whitelist_;
897
898 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
899};
900
[email protected]316c1e5e2012-09-12 15:17:44901TEST_F(URLRequestTest, AboutBlankTest) {
902 TestDelegate d;
903 {
rhalavatib7bd7c792017-04-27 05:25:16904 std::unique_ptr<URLRequest> r(
905 default_context_.CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
906 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44907
[email protected]f7022f32014-08-21 16:32:19908 r->Start();
909 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44910
[email protected]255620da2013-08-19 13:14:29911 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44912
[email protected]f7022f32014-08-21 16:32:19913 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44914 EXPECT_FALSE(d.received_data_before_response());
915 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19916 EXPECT_EQ("", r->GetSocketAddress().host());
917 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04918
919 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19920 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44921 }
922}
923
924TEST_F(URLRequestTest, DataURLImageTest) {
925 TestDelegate d;
926 {
927 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36928 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
929 GURL("data:image/png;base64,"
930 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
931 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
932 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
933 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
934 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
935 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
936 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
937 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
938 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
939 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
940 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
941 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
942 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
943 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
944 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
945 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
946 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
947 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
948 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16949 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44950
[email protected]f7022f32014-08-21 16:32:19951 r->Start();
952 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44953
[email protected]255620da2013-08-19 13:14:29954 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44955
[email protected]f7022f32014-08-21 16:32:19956 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44957 EXPECT_FALSE(d.received_data_before_response());
958 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19959 EXPECT_EQ("", r->GetSocketAddress().host());
960 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04961
962 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19963 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44964 }
965}
966
brettwa1228ebb2016-10-28 03:51:34967#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44968TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51969 const char kTestFileContent[] = "Hello";
970 base::FilePath test_file;
971 ASSERT_NO_FATAL_FAILURE(
972 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04973
Sergey Ulanov2e49f492017-09-14 19:37:51974 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:44975
976 TestDelegate d;
977 {
rhalavatib7bd7c792017-04-27 05:25:16978 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:51979 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44980
[email protected]f7022f32014-08-21 16:32:19981 r->Start();
982 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44983
[email protected]255620da2013-08-19 13:14:29984 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44985
[email protected]f7022f32014-08-21 16:32:19986 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44987 EXPECT_EQ(1, d.response_started_count());
988 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:51989 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
[email protected]f7022f32014-08-21 16:32:19990 EXPECT_EQ("", r->GetSocketAddress().host());
991 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04992
993 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19994 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44995 }
996}
997
[email protected]ba40bb762012-12-17 07:11:04998TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:51999 const char kTestFileContent[] = "Hello";
1000 base::FilePath test_file;
1001 ASSERT_NO_FATAL_FAILURE(
1002 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
1003
1004 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:041005
1006 TestDelegate d;
1007 {
rhalavatib7bd7c792017-04-27 05:25:161008 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511009 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:041010
[email protected]f7022f32014-08-21 16:32:191011 r->Start();
1012 EXPECT_TRUE(r->is_pending());
1013 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:041014 }
[email protected]79e1fd62013-06-20 06:50:041015 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:041016 // destroyed.
[email protected]255620da2013-08-19 13:14:291017 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041018}
1019
[email protected]316c1e5e2012-09-12 15:17:441020TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1021 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361022 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441023 FillBuffer(buffer.get(), buffer_size);
1024
Sergey Ulanov2e49f492017-09-14 19:37:511025 base::FilePath test_file;
1026 ASSERT_NO_FATAL_FAILURE(
1027 CreateTestFile(buffer.get(), buffer_size, &test_file));
1028 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441029
1030 const size_t first_byte_position = 500;
1031 const size_t last_byte_position = buffer_size - first_byte_position;
1032 const size_t content_length = last_byte_position - first_byte_position + 1;
1033 std::string partial_buffer_string(buffer.get() + first_byte_position,
1034 buffer.get() + last_byte_position + 1);
1035
1036 TestDelegate d;
1037 {
rhalavatib7bd7c792017-04-27 05:25:161038 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1039 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441040
1041 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381042 headers.SetHeader(
1043 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591044 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381045 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191046 r->SetExtraRequestHeaders(headers);
1047 r->Start();
1048 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441049
[email protected]255620da2013-08-19 13:14:291050 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191051 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441052 EXPECT_EQ(1, d.response_started_count());
1053 EXPECT_FALSE(d.received_data_before_response());
1054 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1055 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1056 EXPECT_TRUE(partial_buffer_string == d.data_received());
1057 }
[email protected]316c1e5e2012-09-12 15:17:441058}
1059
1060TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1061 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361062 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441063 FillBuffer(buffer.get(), buffer_size);
1064
Sergey Ulanov2e49f492017-09-14 19:37:511065 base::FilePath test_file;
1066 ASSERT_NO_FATAL_FAILURE(
1067 CreateTestFile(buffer.get(), buffer_size, &test_file));
1068 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441069
1070 const size_t first_byte_position = 500;
1071 const size_t last_byte_position = buffer_size - 1;
1072 const size_t content_length = last_byte_position - first_byte_position + 1;
1073 std::string partial_buffer_string(buffer.get() + first_byte_position,
1074 buffer.get() + last_byte_position + 1);
1075
1076 TestDelegate d;
1077 {
rhalavatib7bd7c792017-04-27 05:25:161078 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1079 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441080
1081 HttpRequestHeaders headers;
1082 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591083 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381084 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191085 r->SetExtraRequestHeaders(headers);
1086 r->Start();
1087 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441088
[email protected]255620da2013-08-19 13:14:291089 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191090 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441091 EXPECT_EQ(1, d.response_started_count());
1092 EXPECT_FALSE(d.received_data_before_response());
1093 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1094 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1095 EXPECT_TRUE(partial_buffer_string == d.data_received());
1096 }
[email protected]316c1e5e2012-09-12 15:17:441097}
1098
1099TEST_F(URLRequestTest, FileTestMultipleRanges) {
1100 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361101 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441102 FillBuffer(buffer.get(), buffer_size);
1103
Sergey Ulanov2e49f492017-09-14 19:37:511104 base::FilePath test_file;
1105 ASSERT_NO_FATAL_FAILURE(
1106 CreateTestFile(buffer.get(), buffer_size, &test_file));
1107 GURL temp_url = FilePathToFileURL(test_file);
[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 }
[email protected]316c1e5e2012-09-12 15:17:441123}
1124
[email protected]3ca8b362013-11-11 22:18:071125TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511126 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071127 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511128 ASSERT_NO_FATAL_FAILURE(
1129 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1130
satoruxddac0442017-05-29 06:06:181131 // The directory part of the path returned from CreateTemporaryFileInDir()
1132 // can be slightly different from |absolute_temp_dir| on Windows.
1133 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1134 // Hence the test should use the directory name of |test_file|, rather than
1135 // |absolute_temp_dir|, for whitelisting.
1136 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591137 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071138 {
1139 TestDelegate d;
satoruxddac0442017-05-29 06:06:181140 CookieBlockingNetworkDelegate network_delegate;
1141 network_delegate.AddToWhitelist(real_temp_dir);
[email protected]3ca8b362013-11-11 22:18:071142 default_context_.set_network_delegate(&network_delegate);
rhalavatib7bd7c792017-04-27 05:25:161143 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1144 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191145 r->Start();
[email protected]3ca8b362013-11-11 22:18:071146 base::RunLoop().Run();
satoruxddac0442017-05-29 06:06:181147 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071148 EXPECT_FALSE(d.request_failed());
1149 EXPECT_EQ(test_data, d.data_received());
1150 }
1151
1152 {
1153 TestDelegate d;
satoruxddac0442017-05-29 06:06:181154 CookieBlockingNetworkDelegate network_delegate;
[email protected]3ca8b362013-11-11 22:18:071155 default_context_.set_network_delegate(&network_delegate);
rhalavatib7bd7c792017-04-27 05:25:161156 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1157 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191158 r->Start();
[email protected]3ca8b362013-11-11 22:18:071159 base::RunLoop().Run();
satoruxddac0442017-05-29 06:06:181160 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071161 EXPECT_TRUE(d.request_failed());
1162 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181163 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071164 }
1165}
1166
Kevin Marshalla9f05ec2017-07-14 02:10:051167#if defined(OS_POSIX) && !defined(OS_FUCHSIA) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181168
1169TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511170 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181171 // Get an absolute path since temp_dir can contain a symbolic link.
1172 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511173 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181174
1175 // Create a good directory (will be whitelisted) and a good file.
1176 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1177 ASSERT_TRUE(base::CreateDirectory(good_dir));
1178 base::FilePath good_file;
1179 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1180 std::string good_data("good");
1181 base::WriteFile(good_file, good_data.data(), good_data.size());
1182 // See the comment in AllowFileURLs() for why this is done.
1183 base::FilePath real_good_dir = good_file.DirName();
1184
1185 // Create a bad directory (will not be whitelisted) and a bad file.
1186 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1187 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1188 base::FilePath bad_file;
1189 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1190 std::string bad_data("bad");
1191 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1192
1193 // This symlink will point to the good file. Access to the symlink will be
1194 // allowed as both the symlink and the destination file are in the same
1195 // good directory.
1196 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1197 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1198 GURL good_file_url = FilePathToFileURL(good_symlink);
1199 // This symlink will point to the bad file. Even though the symlink is in
1200 // the good directory, access to the symlink will be rejected since it
1201 // points to the bad file.
1202 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1203 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1204 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1205
1206 CookieBlockingNetworkDelegate network_delegate;
1207 network_delegate.AddToWhitelist(real_good_dir);
1208 {
1209 TestDelegate d;
1210 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371211 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1212 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181213 r->Start();
1214 base::RunLoop().Run();
1215 // good_file_url should be allowed.
1216 EXPECT_FALSE(d.request_failed());
1217 EXPECT_EQ(good_data, d.data_received());
1218 }
1219
1220 {
1221 TestDelegate d;
1222 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371223 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1224 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181225 r->Start();
1226 base::RunLoop().Run();
1227 // bad_file_url should be rejected.
1228 EXPECT_TRUE(d.request_failed());
1229 EXPECT_EQ("", d.data_received());
1230 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1231 }
1232}
1233
1234TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511235 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181236 // Get an absolute path since temp_dir can contain a symbolic link.
1237 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511238 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181239
1240 // Create a good directory (will be whitelisted).
1241 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1242 ASSERT_TRUE(base::CreateDirectory(good_dir));
1243
1244 // Create a bad directory (will not be whitelisted).
1245 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1246 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1247
1248 // This symlink will point to the good directory. Access to the symlink
1249 // will be allowed as the symlink is in the good dir that'll be white
1250 // listed.
1251 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1252 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1253 GURL good_file_url = FilePathToFileURL(good_symlink);
1254 // This symlink will point to the bad directory. Even though the symlink is
1255 // in the good directory, access to the symlink will be rejected since it
1256 // points to the bad directory.
1257 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1258 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1259 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1260
1261 CookieBlockingNetworkDelegate network_delegate;
1262 network_delegate.AddToWhitelist(good_dir);
1263 {
1264 TestDelegate d;
1265 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371266 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1267 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181268 r->Start();
1269 base::RunLoop().Run();
1270 // good_file_url should be allowed.
1271 EXPECT_FALSE(d.request_failed());
1272 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1273 }
1274
1275 {
1276 TestDelegate d;
1277 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371278 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1279 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181280 r->Start();
1281 base::RunLoop().Run();
1282 // bad_file_url should be rejected.
1283 EXPECT_TRUE(d.request_failed());
1284 EXPECT_EQ("", d.data_received());
1285 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1286 }
1287}
1288
Kevin Marshalla9f05ec2017-07-14 02:10:051289#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
[email protected]316c1e5e2012-09-12 15:17:441290
1291TEST_F(URLRequestTest, FileDirCancelTest) {
1292 // Put in mock resource provider.
1293 NetModule::SetResourceProvider(TestNetResourceProvider);
1294
1295 TestDelegate d;
1296 {
[email protected]6cdfd7f2013-02-08 20:40:151297 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441298 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1299 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1300 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1301
danakj8522a25b2016-04-16 00:17:361302 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161303 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1304 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191305 req->Start();
1306 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441307
1308 d.set_cancel_in_received_data_pending(true);
1309
[email protected]255620da2013-08-19 13:14:291310 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441311 }
1312
1313 // Take out mock resource provider.
1314 NetModule::SetResourceProvider(NULL);
1315}
1316
[email protected]5f9581402013-10-30 13:08:321317TEST_F(URLRequestTest, FileDirOutputSanity) {
1318 // Verify the general sanity of the the output of the file:
1319 // directory lister by checking for the output of a known existing
1320 // file.
1321 const char sentinel_name[] = "filedir-sentinel";
1322
1323 base::FilePath path;
1324 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471325 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321326
1327 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161328 std::unique_ptr<URLRequest> req(
1329 default_context_.CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1330 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191331 req->Start();
[email protected]5f9581402013-10-30 13:08:321332 base::RunLoop().Run();
1333
1334 // Generate entry for the sentinel file.
1335 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581336 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491337 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321338 EXPECT_GT(info.size, 0);
1339 std::string sentinel_output = GetDirectoryListingEntry(
1340 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181341 std::string(sentinel_name), false /* is_dir */, info.size,
1342
[email protected]5f9581402013-10-30 13:08:321343 info.last_modified);
1344
1345 ASSERT_LT(0, d.bytes_received());
1346 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501347 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321348 // Check for the entry generated for the "sentinel" file.
1349 const std::string& data = d.data_received();
1350 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1351}
1352
[email protected]316c1e5e2012-09-12 15:17:441353TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1354 // There is an implicit redirect when loading a file path that matches a
1355 // directory and does not end with a slash. Ensure that following such
1356 // redirects does not crash. See http://crbug.com/18686.
1357
[email protected]6cdfd7f2013-02-08 20:40:151358 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441359 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471360 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441361
1362 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161363 std::unique_ptr<URLRequest> req(
1364 default_context_.CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1365 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191366 req->Start();
[email protected]255620da2013-08-19 13:14:291367 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441368
1369 ASSERT_EQ(1, d.received_redirect_count());
1370 ASSERT_LT(0, d.bytes_received());
1371 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501372 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441373}
1374
1375#if defined(OS_WIN)
1376// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1377TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1378 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161379 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
1380 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191381 req->Start();
[email protected]255620da2013-08-19 13:14:291382 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441383
1384 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501385 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441386}
[email protected]5ecf7cb282014-05-11 01:49:551387#endif // defined(OS_WIN)
1388
brettwa1228ebb2016-10-28 03:51:341389#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551390
1391TEST_F(URLRequestTest, InvalidUrlTest) {
1392 TestDelegate d;
1393 {
rhalavatib7bd7c792017-04-27 05:25:161394 std::unique_ptr<URLRequest> r(
1395 default_context_.CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1396 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551397
[email protected]f7022f32014-08-21 16:32:191398 r->Start();
1399 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551400
1401 base::RunLoop().Run();
1402 EXPECT_TRUE(d.request_failed());
1403 }
1404}
1405
jochen0e3b3a62014-09-16 18:31:231406TEST_F(URLRequestTest, InvalidReferrerTest) {
1407 TestURLRequestContext context;
1408 TestNetworkDelegate network_delegate;
1409 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1410 context.set_network_delegate(&network_delegate);
1411 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361412 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161413 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1414 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231415 req->SetReferrer("https://somewhere.com/");
1416
1417 req->Start();
1418 base::RunLoop().Run();
1419 EXPECT_TRUE(d.request_failed());
1420}
1421
[email protected]5ecf7cb282014-05-11 01:49:551422#if defined(OS_WIN)
1423TEST_F(URLRequestTest, ResolveShortcutTest) {
1424 base::FilePath app_path;
1425 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471426 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551427 app_path = app_path.AppendASCII("with-headers.html");
1428
1429 std::wstring lnk_path = app_path.value() + L".lnk";
1430
1431 base::win::ScopedCOMInitializer com_initializer;
1432
1433 // Temporarily create a shortcut for test
1434 {
1435 base::win::ScopedComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161436 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
1437 CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
[email protected]5ecf7cb282014-05-11 01:49:551438 base::win::ScopedComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001439 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
[email protected]5ecf7cb282014-05-11 01:49:551440 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1441 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1442 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1443 }
1444
1445 TestDelegate d;
1446 {
danakj8522a25b2016-04-16 00:17:361447 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161448 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1449 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551450
[email protected]f7022f32014-08-21 16:32:191451 r->Start();
1452 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551453
1454 base::RunLoop().Run();
1455
1456 WIN32_FILE_ATTRIBUTE_DATA data;
1457 GetFileAttributesEx(app_path.value().c_str(),
1458 GetFileExInfoStandard, &data);
1459 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1460 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1461 FILE_ATTRIBUTE_NORMAL, NULL);
1462 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361463 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551464 DWORD read_size;
1465 BOOL result;
1466 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1467 &read_size, NULL);
1468 std::string content(buffer.get(), read_size);
1469 CloseHandle(file);
1470
[email protected]f7022f32014-08-21 16:32:191471 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551472 EXPECT_EQ(1, d.received_redirect_count());
1473 EXPECT_EQ(content, d.data_received());
1474 }
1475
1476 // Clean the shortcut
1477 DeleteFile(lnk_path.c_str());
1478}
1479#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441480
1481// Custom URLRequestJobs for use with interceptor tests
1482class RestartTestJob : public URLRequestTestJob {
1483 public:
1484 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1485 : URLRequestTestJob(request, network_delegate, true) {}
1486 protected:
dchengb03027d2014-10-21 12:00:201487 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441488 private:
dchengb03027d2014-10-21 12:00:201489 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441490};
1491
1492class CancelTestJob : public URLRequestTestJob {
1493 public:
1494 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1495 : URLRequestTestJob(request, network_delegate, true) {}
1496 protected:
dchengb03027d2014-10-21 12:00:201497 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441498 private:
dchengb03027d2014-10-21 12:00:201499 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441500};
1501
1502class CancelThenRestartTestJob : public URLRequestTestJob {
1503 public:
1504 explicit CancelThenRestartTestJob(URLRequest* request,
1505 NetworkDelegate* network_delegate)
1506 : URLRequestTestJob(request, network_delegate, true) {
1507 }
1508 protected:
dchengb03027d2014-10-21 12:00:201509 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441510 request_->Cancel();
1511 this->NotifyRestartRequired();
1512 }
1513 private:
dchengb03027d2014-10-21 12:00:201514 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441515};
1516
bengr1bf8e942014-11-07 01:36:501517// An Interceptor for use with interceptor tests.
1518class MockURLRequestInterceptor : public URLRequestInterceptor {
1519 public:
1520 // Static getters for canned response header and data strings.
1521 static std::string ok_data() {
1522 return URLRequestTestJob::test_data_1();
1523 }
1524
1525 static std::string ok_headers() {
1526 return URLRequestTestJob::test_headers();
1527 }
1528
1529 static std::string redirect_data() {
1530 return std::string();
1531 }
1532
1533 static std::string redirect_headers() {
1534 return URLRequestTestJob::test_redirect_headers();
1535 }
1536
1537 static std::string error_data() {
1538 return std::string("ohhh nooooo mr. bill!");
1539 }
1540
1541 static std::string error_headers() {
1542 return URLRequestTestJob::test_error_headers();
1543 }
1544
1545 MockURLRequestInterceptor()
1546 : intercept_main_request_(false), restart_main_request_(false),
1547 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1548 simulate_main_network_error_(false),
1549 intercept_redirect_(false), cancel_redirect_request_(false),
1550 intercept_final_response_(false), cancel_final_request_(false),
1551 use_url_request_http_job_(false),
1552 did_intercept_main_(false), did_restart_main_(false),
1553 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1554 did_simulate_error_main_(false),
1555 did_intercept_redirect_(false), did_cancel_redirect_(false),
1556 did_intercept_final_(false), did_cancel_final_(false) {
1557 }
1558
1559 ~MockURLRequestInterceptor() override {
1560 }
1561
1562 // URLRequestInterceptor implementation:
1563 URLRequestJob* MaybeInterceptRequest(
1564 URLRequest* request,
1565 NetworkDelegate* network_delegate) const override {
1566 if (restart_main_request_) {
1567 restart_main_request_ = false;
1568 did_restart_main_ = true;
1569 return new RestartTestJob(request, network_delegate);
1570 }
1571 if (cancel_main_request_) {
1572 cancel_main_request_ = false;
1573 did_cancel_main_ = true;
1574 return new CancelTestJob(request, network_delegate);
1575 }
1576 if (cancel_then_restart_main_request_) {
1577 cancel_then_restart_main_request_ = false;
1578 did_cancel_then_restart_main_ = true;
1579 return new CancelThenRestartTestJob(request, network_delegate);
1580 }
1581 if (simulate_main_network_error_) {
1582 simulate_main_network_error_ = false;
1583 did_simulate_error_main_ = true;
1584 if (use_url_request_http_job_) {
1585 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1586 }
1587 // This job will result in error since the requested URL is not one of the
1588 // URLs supported by these tests.
1589 return new URLRequestTestJob(request, network_delegate, true);
1590 }
1591 if (!intercept_main_request_)
1592 return nullptr;
1593 intercept_main_request_ = false;
1594 did_intercept_main_ = true;
1595 URLRequestTestJob* job = new URLRequestTestJob(request,
1596 network_delegate,
1597 main_headers_,
1598 main_data_,
1599 true);
1600 job->set_load_timing_info(main_request_load_timing_info_);
1601 return job;
1602 }
1603
1604 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1605 NetworkDelegate* network_delegate,
1606 const GURL& location) const override {
1607 if (cancel_redirect_request_) {
1608 cancel_redirect_request_ = false;
1609 did_cancel_redirect_ = true;
1610 return new CancelTestJob(request, network_delegate);
1611 }
1612 if (!intercept_redirect_)
1613 return nullptr;
1614 intercept_redirect_ = false;
1615 did_intercept_redirect_ = true;
1616 if (use_url_request_http_job_) {
1617 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1618 }
1619 return new URLRequestTestJob(request,
1620 network_delegate,
1621 redirect_headers_,
1622 redirect_data_,
1623 true);
1624 }
1625
1626 URLRequestJob* MaybeInterceptResponse(
1627 URLRequest* request,
1628 NetworkDelegate* network_delegate) const override {
1629 if (cancel_final_request_) {
1630 cancel_final_request_ = false;
1631 did_cancel_final_ = true;
1632 return new CancelTestJob(request, network_delegate);
1633 }
1634 if (!intercept_final_response_)
1635 return nullptr;
1636 intercept_final_response_ = false;
1637 did_intercept_final_ = true;
1638 if (use_url_request_http_job_) {
1639 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1640 }
1641 return new URLRequestTestJob(request,
1642 network_delegate,
1643 final_headers_,
1644 final_data_,
1645 true);
1646 }
1647
1648 void set_intercept_main_request(bool intercept_main_request) {
1649 intercept_main_request_ = intercept_main_request;
1650 }
1651
1652 void set_main_headers(const std::string& main_headers) {
1653 main_headers_ = main_headers;
1654 }
1655
1656 void set_main_data(const std::string& main_data) {
1657 main_data_ = main_data;
1658 }
1659
1660 void set_main_request_load_timing_info(
1661 const LoadTimingInfo& main_request_load_timing_info) {
1662 main_request_load_timing_info_ = main_request_load_timing_info;
1663 }
1664
1665 void set_restart_main_request(bool restart_main_request) {
1666 restart_main_request_ = restart_main_request;
1667 }
1668
1669 void set_cancel_main_request(bool cancel_main_request) {
1670 cancel_main_request_ = cancel_main_request;
1671 }
1672
1673 void set_cancel_then_restart_main_request(
1674 bool cancel_then_restart_main_request) {
1675 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1676 }
1677
1678 void set_simulate_main_network_error(bool simulate_main_network_error) {
1679 simulate_main_network_error_ = simulate_main_network_error;
1680 }
1681
1682 void set_intercept_redirect(bool intercept_redirect) {
1683 intercept_redirect_ = intercept_redirect;
1684 }
1685
1686 void set_redirect_headers(const std::string& redirect_headers) {
1687 redirect_headers_ = redirect_headers;
1688 }
1689
1690 void set_redirect_data(const std::string& redirect_data) {
1691 redirect_data_ = redirect_data;
1692 }
1693
1694 void set_cancel_redirect_request(bool cancel_redirect_request) {
1695 cancel_redirect_request_ = cancel_redirect_request;
1696 }
1697
1698 void set_intercept_final_response(bool intercept_final_response) {
1699 intercept_final_response_ = intercept_final_response;
1700 }
1701
1702 void set_final_headers(const std::string& final_headers) {
1703 final_headers_ = final_headers;
1704 }
1705
1706 void set_final_data(const std::string& final_data) {
1707 final_data_ = final_data;
1708 }
1709
1710 void set_cancel_final_request(bool cancel_final_request) {
1711 cancel_final_request_ = cancel_final_request;
1712 }
1713
1714 void set_use_url_request_http_job(bool use_url_request_http_job) {
1715 use_url_request_http_job_ = use_url_request_http_job;
1716 }
1717
1718 bool did_intercept_main() const {
1719 return did_intercept_main_;
1720 }
1721
1722 bool did_restart_main() const {
1723 return did_restart_main_;
1724 }
1725
1726 bool did_cancel_main() const {
1727 return did_cancel_main_;
1728 }
1729
1730 bool did_cancel_then_restart_main() const {
1731 return did_cancel_then_restart_main_;
1732 }
1733
1734 bool did_simulate_error_main() const {
1735 return did_simulate_error_main_;
1736 }
1737
1738 bool did_intercept_redirect() const {
1739 return did_intercept_redirect_;
1740 }
1741
1742 bool did_cancel_redirect() const {
1743 return did_cancel_redirect_;
1744 }
1745
1746 bool did_intercept_final() const {
1747 return did_intercept_final_;
1748 }
1749
1750 bool did_cancel_final() const {
1751 return did_cancel_final_;
1752 }
1753
1754 private:
1755 // Indicate whether to intercept the main request, and if so specify the
1756 // response to return and the LoadTimingInfo to use.
1757 mutable bool intercept_main_request_;
1758 mutable std::string main_headers_;
1759 mutable std::string main_data_;
1760 mutable LoadTimingInfo main_request_load_timing_info_;
1761
1762 // These indicate actions that can be taken within MaybeInterceptRequest.
1763 mutable bool restart_main_request_;
1764 mutable bool cancel_main_request_;
1765 mutable bool cancel_then_restart_main_request_;
1766 mutable bool simulate_main_network_error_;
1767
1768 // Indicate whether to intercept redirects, and if so specify the response to
1769 // return.
1770 mutable bool intercept_redirect_;
1771 mutable std::string redirect_headers_;
1772 mutable std::string redirect_data_;
1773
1774 // Cancel the request within MaybeInterceptRedirect.
1775 mutable bool cancel_redirect_request_;
1776
1777 // Indicate whether to intercept the final response, and if so specify the
1778 // response to return.
1779 mutable bool intercept_final_response_;
1780 mutable std::string final_headers_;
1781 mutable std::string final_data_;
1782
1783 // Cancel the final request within MaybeInterceptResponse.
1784 mutable bool cancel_final_request_;
1785
1786 // Instruct the interceptor to use a real URLRequestHTTPJob.
1787 mutable bool use_url_request_http_job_;
1788
1789 // These indicate if the interceptor did something or not.
1790 mutable bool did_intercept_main_;
1791 mutable bool did_restart_main_;
1792 mutable bool did_cancel_main_;
1793 mutable bool did_cancel_then_restart_main_;
1794 mutable bool did_simulate_error_main_;
1795 mutable bool did_intercept_redirect_;
1796 mutable bool did_cancel_redirect_;
1797 mutable bool did_intercept_final_;
1798 mutable bool did_cancel_final_;
1799};
1800
1801// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1802class URLRequestInterceptorTest : public URLRequestTest {
1803 public:
1804 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1805 }
1806
1807 ~URLRequestInterceptorTest() override {
1808 // URLRequestJobs may post clean-up tasks on destruction.
1809 base::RunLoop().RunUntilIdle();
1810 }
1811
1812 void SetUpFactory() override {
1813 interceptor_ = new MockURLRequestInterceptor();
1814 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361815 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501816 }
1817
1818 MockURLRequestInterceptor* interceptor() const {
1819 return interceptor_;
1820 }
1821
1822 private:
1823 MockURLRequestInterceptor* interceptor_;
1824};
1825
1826TEST_F(URLRequestInterceptorTest, Intercept) {
1827 // Intercept the main request and respond with a simple response.
1828 interceptor()->set_intercept_main_request(true);
1829 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1830 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591831 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361832 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161833 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1834 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501835 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1836 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1837 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091838 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041839 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1840 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501841 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191842 req->Start();
[email protected]255620da2013-08-19 13:14:291843 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591844
bengr1bf8e942014-11-07 01:36:501845 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091846 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501847 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1848 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591849
bengr1bf8e942014-11-07 01:36:501850 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501851 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501852 EXPECT_EQ(200, req->response_headers()->response_code());
1853 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1854 EXPECT_EQ(1, d.response_started_count());
1855 EXPECT_EQ(0, d.received_redirect_count());
1856}
[email protected]2bba3252013-04-08 19:50:591857
bengr1bf8e942014-11-07 01:36:501858TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1859 // Intercept the main request and respond with a redirect.
1860 interceptor()->set_intercept_main_request(true);
1861 interceptor()->set_main_headers(
1862 MockURLRequestInterceptor::redirect_headers());
1863 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1864
1865 // Intercept that redirect and respond with a final OK response.
1866 interceptor()->set_intercept_redirect(true);
1867 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1868 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1869
1870 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361871 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161872 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1873 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501874 req->set_method("GET");
1875 req->Start();
1876 base::RunLoop().Run();
1877
1878 // Check that the interceptor got called as expected.
1879 EXPECT_TRUE(interceptor()->did_intercept_main());
1880 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1881
1882 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501883 int status = d.request_status();
1884 EXPECT_EQ(OK, status);
1885 if (status == OK)
bengr1bf8e942014-11-07 01:36:501886 EXPECT_EQ(200, req->response_headers()->response_code());
1887
1888 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1889 EXPECT_EQ(1, d.response_started_count());
1890 EXPECT_EQ(0, d.received_redirect_count());
1891}
1892
1893TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1894 // Intercept the main request to generate a server error response.
1895 interceptor()->set_intercept_main_request(true);
1896 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1897 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1898
1899 // Intercept that error and respond with an OK response.
1900 interceptor()->set_intercept_final_response(true);
1901 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1902 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1903
1904 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361905 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161906 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1907 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501908 req->set_method("GET");
1909 req->Start();
1910 base::RunLoop().Run();
1911
1912 // Check that the interceptor got called as expected.
1913 EXPECT_TRUE(interceptor()->did_intercept_main());
1914 EXPECT_TRUE(interceptor()->did_intercept_final());
1915
1916 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501917 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501918 EXPECT_EQ(200, req->response_headers()->response_code());
1919 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1920 EXPECT_EQ(1, d.response_started_count());
1921 EXPECT_EQ(0, d.received_redirect_count());
1922}
1923
1924TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1925 // Intercept the main request to simulate a network error.
1926 interceptor()->set_simulate_main_network_error(true);
1927
1928 // Intercept that error and respond with an OK response.
1929 interceptor()->set_intercept_final_response(true);
1930 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1931 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1932
1933 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361934 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161935 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1936 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501937 req->set_method("GET");
1938 req->Start();
1939 base::RunLoop().Run();
1940
1941 // Check that the interceptor got called as expected.
1942 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1943 EXPECT_TRUE(interceptor()->did_intercept_final());
1944
1945 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501946 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501947 EXPECT_EQ(200, req->response_headers()->response_code());
1948 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1949 EXPECT_EQ(1, d.response_started_count());
1950 EXPECT_EQ(0, d.received_redirect_count());
1951}
1952
1953TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1954 // Restart the main request.
1955 interceptor()->set_restart_main_request(true);
1956
1957 // then intercept the new main request and respond with an OK response
1958 interceptor()->set_intercept_main_request(true);
1959 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1960 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1961
1962 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361963 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161964 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1965 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501966 req->set_method("GET");
1967 req->Start();
1968 base::RunLoop().Run();
1969
1970 // Check that the interceptor got called as expected.
1971 EXPECT_TRUE(interceptor()->did_restart_main());
1972 EXPECT_TRUE(interceptor()->did_intercept_main());
1973
1974 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501975 int status = d.request_status();
1976 EXPECT_EQ(OK, status);
1977 if (status == OK)
bengr1bf8e942014-11-07 01:36:501978 EXPECT_EQ(200, req->response_headers()->response_code());
1979
1980 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1981 EXPECT_EQ(1, d.response_started_count());
1982 EXPECT_EQ(0, d.received_redirect_count());
1983}
1984
1985TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1986 // Intercept the main request and cancel from within the restarted job.
1987 interceptor()->set_cancel_main_request(true);
1988
1989 // Set up to intercept the final response and override it with an OK response.
1990 interceptor()->set_intercept_final_response(true);
1991 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1992 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1993
1994 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361995 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161996 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1997 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501998 req->set_method("GET");
1999 req->Start();
2000 base::RunLoop().Run();
2001
2002 // Check that the interceptor got called as expected.
2003 EXPECT_TRUE(interceptor()->did_cancel_main());
2004 EXPECT_FALSE(interceptor()->did_intercept_final());
2005
2006 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502007 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502008}
2009
2010TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2011 // Intercept the main request and respond with a redirect.
2012 interceptor()->set_intercept_main_request(true);
2013 interceptor()->set_main_headers(
2014 MockURLRequestInterceptor::redirect_headers());
2015 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2016
2017 // Intercept the redirect and cancel from within that job.
2018 interceptor()->set_cancel_redirect_request(true);
2019
2020 // Set up to intercept the final response and override it with an OK response.
2021 interceptor()->set_intercept_final_response(true);
2022 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2023 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2024
2025 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362026 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162027 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2028 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502029 req->set_method("GET");
2030 req->Start();
2031 base::RunLoop().Run();
2032
2033 // Check that the interceptor got called as expected.
2034 EXPECT_TRUE(interceptor()->did_intercept_main());
2035 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2036 EXPECT_FALSE(interceptor()->did_intercept_final());
2037
2038 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502039 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502040}
2041
2042TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2043 // Intercept the main request to simulate a network error.
2044 interceptor()->set_simulate_main_network_error(true);
2045
2046 // Set up to intercept final the response and cancel from within that job.
2047 interceptor()->set_cancel_final_request(true);
2048
2049 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362050 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162051 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2052 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502053 req->set_method("GET");
2054 req->Start();
2055 base::RunLoop().Run();
2056
2057 // Check that the interceptor got called as expected.
2058 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2059 EXPECT_TRUE(interceptor()->did_cancel_final());
2060
2061 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502062 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502063}
2064
2065TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2066 // Intercept the main request and cancel then restart from within that job.
2067 interceptor()->set_cancel_then_restart_main_request(true);
2068
2069 // Set up to intercept the final response and override it with an OK response.
2070 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502071 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2072 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502073
2074 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362075 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162076 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2077 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502078 req->set_method("GET");
2079 req->Start();
2080 base::RunLoop().Run();
2081
2082 // Check that the interceptor got called as expected.
2083 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2084 EXPECT_FALSE(interceptor()->did_intercept_final());
2085
2086 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502087 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592088}
2089
2090// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2091// reused. |connect_time_flags| is used to indicate if there should be dns
2092// or SSL times, and |used_proxy| is used for proxy times.
2093LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2094 int connect_time_flags,
2095 bool used_proxy) {
2096 LoadTimingInfo load_timing;
2097 load_timing.socket_log_id = 1;
2098
2099 if (used_proxy) {
2100 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2101 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2102 }
2103
2104 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2105 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2106 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2107 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2108 }
2109 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2110 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2111 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2112 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2113 }
2114 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2115
2116 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2117 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2118 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2119 return load_timing;
2120}
2121
2122// Same as above, but in the case of a reused socket.
2123LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2124 bool used_proxy) {
2125 LoadTimingInfo load_timing;
2126 load_timing.socket_log_id = 1;
2127 load_timing.socket_reused = true;
2128
2129 if (used_proxy) {
2130 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2131 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2132 }
2133
2134 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2135 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2136 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2137 return load_timing;
2138}
2139
bengr1bf8e942014-11-07 01:36:502140LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2141 const LoadTimingInfo& job_load_timing,
2142 const URLRequestContext& context,
2143 MockURLRequestInterceptor* interceptor) {
2144 interceptor->set_intercept_main_request(true);
2145 interceptor->set_main_request_load_timing_info(job_load_timing);
2146 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162147 std::unique_ptr<URLRequest> req(
2148 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2149 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502150 req->Start();
2151 base::RunLoop().Run();
2152
2153 LoadTimingInfo resulting_load_timing;
2154 req->GetLoadTimingInfo(&resulting_load_timing);
2155
2156 // None of these should be modified by the URLRequest.
2157 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2158 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2159 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2160 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
2161 EXPECT_EQ(job_load_timing.receive_headers_end,
2162 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572163 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2164 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502165
2166 return resulting_load_timing;
2167}
2168
[email protected]2bba3252013-04-08 19:50:592169// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502170TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592171 base::TimeTicks now = base::TimeTicks::Now();
2172 LoadTimingInfo job_load_timing =
2173 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2174
[email protected]2ca01e52013-10-31 22:05:192175 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502176 RunURLRequestInterceptorLoadTimingTest(
2177 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592178
2179 // Nothing should have been changed by the URLRequest.
2180 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2181 load_timing_result.proxy_resolve_start);
2182 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2183 load_timing_result.proxy_resolve_end);
2184 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2185 load_timing_result.connect_timing.dns_start);
2186 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2187 load_timing_result.connect_timing.dns_end);
2188 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2189 load_timing_result.connect_timing.connect_start);
2190 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2191 load_timing_result.connect_timing.connect_end);
2192 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2193 load_timing_result.connect_timing.ssl_start);
2194 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2195 load_timing_result.connect_timing.ssl_end);
2196
2197 // Redundant sanity check.
2198 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2199}
2200
2201// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502202TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592203 base::TimeTicks now = base::TimeTicks::Now();
2204 LoadTimingInfo job_load_timing =
2205 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2206
[email protected]2ca01e52013-10-31 22:05:192207 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502208 RunURLRequestInterceptorLoadTimingTest(
2209 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592210
2211 // Nothing should have been changed by the URLRequest.
2212 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2213 load_timing_result.proxy_resolve_start);
2214 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2215 load_timing_result.proxy_resolve_end);
2216 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2217 load_timing_result.connect_timing.dns_start);
2218 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2219 load_timing_result.connect_timing.dns_end);
2220 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2221 load_timing_result.connect_timing.connect_start);
2222 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2223 load_timing_result.connect_timing.connect_end);
2224 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2225 load_timing_result.connect_timing.ssl_start);
2226 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2227 load_timing_result.connect_timing.ssl_end);
2228
2229 // Redundant sanity check.
2230 TestLoadTimingNotReusedWithProxy(load_timing_result,
2231 CONNECT_TIMING_HAS_SSL_TIMES);
2232}
2233
2234// Make sure that URLRequest correctly adjusts proxy times when they're before
2235// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102236// the case of reusing a SPDY session. The connected socket is not considered
2237// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592238//
2239// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502240TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592241 base::TimeTicks now = base::TimeTicks::Now();
2242 LoadTimingInfo job_load_timing =
2243 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2244 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2245 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2246 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2247 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2248 job_load_timing.connect_timing.connect_start =
2249 now - base::TimeDelta::FromDays(2);
2250 job_load_timing.connect_timing.connect_end =
2251 now - base::TimeDelta::FromDays(1);
2252
[email protected]2ca01e52013-10-31 22:05:192253 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502254 RunURLRequestInterceptorLoadTimingTest(
2255 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592256
2257 // Proxy times, connect times, and DNS times should all be replaced with
2258 // request_start.
2259 EXPECT_EQ(load_timing_result.request_start,
2260 load_timing_result.proxy_resolve_start);
2261 EXPECT_EQ(load_timing_result.request_start,
2262 load_timing_result.proxy_resolve_end);
2263 EXPECT_EQ(load_timing_result.request_start,
2264 load_timing_result.connect_timing.dns_start);
2265 EXPECT_EQ(load_timing_result.request_start,
2266 load_timing_result.connect_timing.dns_end);
2267 EXPECT_EQ(load_timing_result.request_start,
2268 load_timing_result.connect_timing.connect_start);
2269 EXPECT_EQ(load_timing_result.request_start,
2270 load_timing_result.connect_timing.connect_end);
2271
2272 // Other times should have been left null.
2273 TestLoadTimingNotReusedWithProxy(load_timing_result,
2274 CONNECT_TIMING_HAS_DNS_TIMES);
2275}
2276
2277// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502278TEST_F(URLRequestInterceptorTest,
2279 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592280 base::TimeTicks now = base::TimeTicks::Now();
2281 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2282 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2283 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2284
[email protected]2ca01e52013-10-31 22:05:192285 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502286 RunURLRequestInterceptorLoadTimingTest(
2287 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592288
2289 // Proxy times and connect times should all be replaced with request_start.
2290 EXPECT_EQ(load_timing_result.request_start,
2291 load_timing_result.proxy_resolve_start);
2292 EXPECT_EQ(load_timing_result.request_start,
2293 load_timing_result.proxy_resolve_end);
2294
2295 // Other times should have been left null.
2296 TestLoadTimingReusedWithProxy(load_timing_result);
2297}
2298
2299// Make sure that URLRequest correctly adjusts connect times when they're before
2300// |request_start|, due to reusing a connected socket. The connected socket is
2301// not considered reused in this test (May be a preconnect).
2302//
2303// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502304TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592305 base::TimeTicks now = base::TimeTicks::Now();
2306 LoadTimingInfo job_load_timing =
2307 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2308 job_load_timing.connect_timing.connect_start =
2309 now - base::TimeDelta::FromDays(1);
2310 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2311 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2312 job_load_timing.connect_timing.connect_end =
2313 now - base::TimeDelta::FromDays(4);
2314
[email protected]2ca01e52013-10-31 22:05:192315 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502316 RunURLRequestInterceptorLoadTimingTest(
2317 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592318
2319 // Connect times, and SSL times should be replaced with request_start.
2320 EXPECT_EQ(load_timing_result.request_start,
2321 load_timing_result.connect_timing.connect_start);
2322 EXPECT_EQ(load_timing_result.request_start,
2323 load_timing_result.connect_timing.ssl_start);
2324 EXPECT_EQ(load_timing_result.request_start,
2325 load_timing_result.connect_timing.ssl_end);
2326 EXPECT_EQ(load_timing_result.request_start,
2327 load_timing_result.connect_timing.connect_end);
2328
2329 // Other times should have been left null.
2330 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2331}
2332
2333// Make sure that URLRequest correctly adjusts connect times when they're before
2334// |request_start|, due to reusing a connected socket in the case that there
2335// are also proxy times. The connected socket is not considered reused in this
2336// test (May be a preconnect).
2337//
2338// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502339TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592340 base::TimeTicks now = base::TimeTicks::Now();
2341 LoadTimingInfo job_load_timing =
2342 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2343 job_load_timing.connect_timing.connect_start =
2344 now - base::TimeDelta::FromDays(1);
2345 job_load_timing.connect_timing.connect_end =
2346 now - base::TimeDelta::FromDays(2);
2347
[email protected]2ca01e52013-10-31 22:05:192348 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502349 RunURLRequestInterceptorLoadTimingTest(
2350 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592351
2352 // Connect times should be replaced with proxy_resolve_end.
2353 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2354 load_timing_result.connect_timing.connect_start);
2355 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2356 load_timing_result.connect_timing.connect_end);
2357
2358 // Other times should have been left null.
2359 TestLoadTimingNotReusedWithProxy(load_timing_result,
2360 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2361}
2362
[email protected]316c1e5e2012-09-12 15:17:442363// Check that two different URL requests have different identifiers.
2364TEST_F(URLRequestTest, Identifiers) {
2365 TestDelegate d;
2366 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362367 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162368 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2369 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362370 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162371 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2372 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442373
mmenke19378d22014-09-09 04:12:592374 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442375}
2376
blundellb8163592f2015-12-16 14:22:422377#if defined(OS_IOS)
2378// TODO(droger): Check that a failure to connect to the proxy is reported to
2379// the network delegate. crbug.com/496743
2380#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2381#else
2382#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2383#endif
2384TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442385 MockHostResolver host_resolver;
2386 host_resolver.rules()->AddSimulatedFailure("*");
2387
[email protected]ceefd7fd2012-11-29 00:36:242388 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442389 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2390
2391 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362392 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162393 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2394 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192395 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442396
[email protected]f7022f32014-08-21 16:32:192397 req->Start();
[email protected]255620da2013-08-19 13:14:292398 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442399
2400 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152401 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472402 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502403 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442404
2405 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012406 EXPECT_THAT(network_delegate.last_error(),
2407 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442408 EXPECT_EQ(1, network_delegate.completed_requests());
2409}
2410
[email protected]cba24642014-08-15 20:49:592411// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442412// content is empty.
2413TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2414 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162415 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
2416 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192417 req->Start();
[email protected]255620da2013-08-19 13:14:292418 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442419 EXPECT_EQ("", d.data_received());
2420 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2421}
2422
[email protected]5033ab82013-03-22 20:17:462423// Make sure that SetPriority actually sets the URLRequest's priority
2424// correctly, both before and after start.
2425TEST_F(URLRequestTest, SetPriorityBasic) {
2426 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362427 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162428 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2429 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192430 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462431
[email protected]f7022f32014-08-21 16:32:192432 req->SetPriority(LOW);
2433 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462434
[email protected]f7022f32014-08-21 16:32:192435 req->Start();
2436 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462437
[email protected]f7022f32014-08-21 16:32:192438 req->SetPriority(MEDIUM);
2439 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462440}
2441
2442// Make sure that URLRequest calls SetPriority on a job before calling
2443// Start on it.
2444TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2445 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362446 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162447 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2448 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192449 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462450
mmenkeed0498b2015-12-08 23:20:422451 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362452 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422453 req.get(), &default_network_delegate_, &job_priority));
2454 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2455 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462456
[email protected]f7022f32014-08-21 16:32:192457 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462458
[email protected]f7022f32014-08-21 16:32:192459 req->Start();
mmenkeed0498b2015-12-08 23:20:422460 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462461}
2462
2463// Make sure that URLRequest passes on its priority updates to its
2464// job.
2465TEST_F(URLRequestTest, SetJobPriority) {
2466 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362467 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162468 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2469 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462470
mmenkeed0498b2015-12-08 23:20:422471 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362472 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422473 req.get(), &default_network_delegate_, &job_priority));
2474 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462475
[email protected]f7022f32014-08-21 16:32:192476 req->SetPriority(LOW);
2477 req->Start();
mmenkeed0498b2015-12-08 23:20:422478 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462479
[email protected]f7022f32014-08-21 16:32:192480 req->SetPriority(MEDIUM);
2481 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422482 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462483}
2484
[email protected]bb1c4662013-11-14 00:00:072485// Setting the IGNORE_LIMITS load flag should be okay if the priority
2486// is MAXIMUM_PRIORITY.
2487TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2488 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362489 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162490 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2491 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192492 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072493
mmenkeed0498b2015-12-08 23:20:422494 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362495 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422496 req.get(), &default_network_delegate_, &job_priority));
2497 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072498
[email protected]f7022f32014-08-21 16:32:192499 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2500 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072501
[email protected]f7022f32014-08-21 16:32:192502 req->SetPriority(MAXIMUM_PRIORITY);
2503 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072504
[email protected]f7022f32014-08-21 16:32:192505 req->Start();
2506 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422507 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072508}
2509
nick5d570de92015-05-04 20:16:162510namespace {
2511
2512// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552513class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442514 public:
tommycli59a63432015-11-06 00:10:552515 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2516 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272517 }
tommycli59a63432015-11-06 00:10:552518
2519 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2520};
tommyclieae5f75f2015-11-05 19:07:272521
nick5d570de92015-05-04 20:16:162522} // namespace
2523
[email protected]f2f31b32013-01-16 23:24:092524TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442525 LocalHttpTestServer test_server;
2526 ASSERT_TRUE(test_server.Start());
2527
2528 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362529 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502530 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442531
2532 // Set up a cookie.
2533 {
2534 TestNetworkDelegate network_delegate;
2535 context.set_network_delegate(&network_delegate);
2536 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362537 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552538 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162539 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192540 req->Start();
[email protected]255620da2013-08-19 13:14:292541 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442542 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2543 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2544 EXPECT_EQ(1, network_delegate.set_cookie_count());
2545 }
2546
2547 // Verify that the cookie is set.
2548 {
2549 TestNetworkDelegate network_delegate;
2550 context.set_network_delegate(&network_delegate);
2551 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362552 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162553 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2554 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192555 req->Start();
[email protected]255620da2013-08-19 13:14:292556 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442557
2558 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2559 != std::string::npos);
2560 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2561 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2562 }
2563}
2564
[email protected]f2f31b32013-01-16 23:24:092565TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442566 LocalHttpTestServer test_server;
2567 ASSERT_TRUE(test_server.Start());
2568
2569 // Set up a cookie.
2570 {
2571 TestNetworkDelegate network_delegate;
2572 default_context_.set_network_delegate(&network_delegate);
2573 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362574 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552575 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162576 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192577 req->Start();
[email protected]255620da2013-08-19 13:14:292578 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442579 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2580 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2581 }
2582
2583 // Verify that the cookie is set.
2584 {
2585 TestNetworkDelegate network_delegate;
2586 default_context_.set_network_delegate(&network_delegate);
2587 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362588 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162589 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2590 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192591 req->Start();
[email protected]255620da2013-08-19 13:14:292592 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442593
2594 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2595 != std::string::npos);
2596 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2597 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2598 }
2599
2600 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2601 {
2602 TestNetworkDelegate network_delegate;
2603 default_context_.set_network_delegate(&network_delegate);
2604 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362605 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162606 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2607 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192608 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2609 req->Start();
[email protected]255620da2013-08-19 13:14:292610 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442611
2612 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2613 == std::string::npos);
2614
2615 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2616 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2617 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2618 }
2619}
2620
2621TEST_F(URLRequestTest, DoNotSaveCookies) {
2622 LocalHttpTestServer test_server;
2623 ASSERT_TRUE(test_server.Start());
2624
2625 // Set up a cookie.
2626 {
2627 TestNetworkDelegate network_delegate;
2628 default_context_.set_network_delegate(&network_delegate);
2629 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362630 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552631 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162632 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192633 req->Start();
[email protected]255620da2013-08-19 13:14:292634 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442635
2636 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2637 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2638 EXPECT_EQ(1, network_delegate.set_cookie_count());
2639 }
2640
2641 // Try to set-up another cookie and update the previous cookie.
2642 {
2643 TestNetworkDelegate network_delegate;
2644 default_context_.set_network_delegate(&network_delegate);
2645 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362646 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552647 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162648 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192649 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2650 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442651
[email protected]255620da2013-08-19 13:14:292652 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442653
2654 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2655 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2656 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2657 EXPECT_EQ(0, network_delegate.set_cookie_count());
2658 }
2659
2660 // Verify the cookies weren't saved or updated.
2661 {
2662 TestNetworkDelegate network_delegate;
2663 default_context_.set_network_delegate(&network_delegate);
2664 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362665 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162666 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2667 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192668 req->Start();
[email protected]255620da2013-08-19 13:14:292669 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442670
2671 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2672 == std::string::npos);
2673 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2674 != std::string::npos);
2675
2676 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2677 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2678 EXPECT_EQ(0, network_delegate.set_cookie_count());
2679 }
2680}
2681
2682TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2683 LocalHttpTestServer test_server;
2684 ASSERT_TRUE(test_server.Start());
2685
2686 // Set up a cookie.
2687 {
2688 TestNetworkDelegate network_delegate;
2689 default_context_.set_network_delegate(&network_delegate);
2690 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362691 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552692 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162693 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192694 req->Start();
[email protected]255620da2013-08-19 13:14:292695 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442696
2697 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2698 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2699 }
2700
2701 // Verify that the cookie is set.
2702 {
2703 TestNetworkDelegate network_delegate;
2704 default_context_.set_network_delegate(&network_delegate);
2705 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362706 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162707 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2708 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192709 req->Start();
[email protected]255620da2013-08-19 13:14:292710 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442711
2712 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2713 != std::string::npos);
2714
2715 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2716 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2717 }
2718
2719 // Verify that the cookie isn't sent.
2720 {
2721 TestNetworkDelegate network_delegate;
2722 default_context_.set_network_delegate(&network_delegate);
2723 TestDelegate d;
2724 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362725 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162726 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2727 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192728 req->Start();
[email protected]255620da2013-08-19 13:14:292729 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442730
2731 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2732 == std::string::npos);
2733
[email protected]22e045f2013-09-20 03:54:032734 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442735 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2736 }
2737}
2738
marqf14fff8d2015-12-02 15:52:292739// TODO(crbug.com/564656) This test is flaky on iOS.
2740#if defined(OS_IOS)
2741#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2742#else
2743#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2744#endif
[email protected]316c1e5e2012-09-12 15:17:442745TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2746 LocalHttpTestServer test_server;
2747 ASSERT_TRUE(test_server.Start());
2748
2749 // Set up a cookie.
2750 {
2751 TestNetworkDelegate network_delegate;
2752 default_context_.set_network_delegate(&network_delegate);
2753 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362754 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552755 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162756 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192757 req->Start();
[email protected]255620da2013-08-19 13:14:292758 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442759
2760 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2761 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2762 }
2763
2764 // Try to set-up another cookie and update the previous cookie.
2765 {
2766 TestNetworkDelegate network_delegate;
2767 default_context_.set_network_delegate(&network_delegate);
2768 TestDelegate d;
2769 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362770 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552771 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162772 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192773 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442774
[email protected]255620da2013-08-19 13:14:292775 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442776
2777 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2778 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2779 }
2780
2781 // Verify the cookies weren't saved or updated.
2782 {
2783 TestNetworkDelegate network_delegate;
2784 default_context_.set_network_delegate(&network_delegate);
2785 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362786 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162787 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2788 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192789 req->Start();
[email protected]255620da2013-08-19 13:14:292790 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442791
2792 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2793 == std::string::npos);
2794 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2795 != std::string::npos);
2796
2797 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2798 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2799 }
2800}
2801
2802TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2803 LocalHttpTestServer test_server;
2804 ASSERT_TRUE(test_server.Start());
2805
2806 // Set up an empty cookie.
2807 {
2808 TestNetworkDelegate network_delegate;
2809 default_context_.set_network_delegate(&network_delegate);
2810 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362811 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162812 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
2813 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192814 req->Start();
[email protected]255620da2013-08-19 13:14:292815 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442816
2817 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2818 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2819 EXPECT_EQ(0, network_delegate.set_cookie_count());
2820 }
2821}
2822
2823TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2824 LocalHttpTestServer test_server;
2825 ASSERT_TRUE(test_server.Start());
2826
2827 // Set up a cookie.
2828 {
2829 TestNetworkDelegate network_delegate;
2830 default_context_.set_network_delegate(&network_delegate);
2831 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362832 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552833 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162834 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192835 req->Start();
[email protected]255620da2013-08-19 13:14:292836 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442837
2838 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2839 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2840 }
2841
2842 // Verify that the cookie is set.
2843 {
2844 TestNetworkDelegate network_delegate;
2845 default_context_.set_network_delegate(&network_delegate);
2846 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362847 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162848 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2849 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192850 req->Start();
[email protected]255620da2013-08-19 13:14:292851 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442852
2853 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2854 != std::string::npos);
2855
2856 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2857 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2858 }
2859
2860 // Verify that the cookie isn't sent.
2861 {
2862 TestNetworkDelegate network_delegate;
2863 default_context_.set_network_delegate(&network_delegate);
2864 TestDelegate d;
2865 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362866 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162867 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2868 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192869 req->Start();
[email protected]255620da2013-08-19 13:14:292870 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442871
2872 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2873 == std::string::npos);
2874
[email protected]22e045f2013-09-20 03:54:032875 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442876 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2877 }
2878}
2879
2880TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2881 LocalHttpTestServer test_server;
2882 ASSERT_TRUE(test_server.Start());
2883
2884 // Set up a cookie.
2885 {
2886 TestNetworkDelegate network_delegate;
2887 default_context_.set_network_delegate(&network_delegate);
2888 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362889 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552890 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162891 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192892 req->Start();
[email protected]255620da2013-08-19 13:14:292893 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442894
2895 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2896 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2897 }
2898
2899 // Try to set-up another cookie and update the previous cookie.
2900 {
2901 TestNetworkDelegate network_delegate;
2902 default_context_.set_network_delegate(&network_delegate);
2903 TestDelegate d;
2904 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362905 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552906 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162907 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192908 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442909
[email protected]255620da2013-08-19 13:14:292910 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442911
2912 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2913 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2914 }
2915
2916 // Verify the cookies weren't saved or updated.
2917 {
2918 TestNetworkDelegate network_delegate;
2919 default_context_.set_network_delegate(&network_delegate);
2920 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362921 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162922 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2923 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192924 req->Start();
[email protected]255620da2013-08-19 13:14:292925 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442926
2927 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2928 == std::string::npos);
2929 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2930 != std::string::npos);
2931
2932 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2933 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2934 }
2935}
2936
mkwstc5fa7762016-03-28 09:28:232937TEST_F(URLRequestTest, SameSiteCookies) {
mkwst3f3daac2015-02-26 20:15:262938 LocalHttpTestServer test_server;
2939 ASSERT_TRUE(test_server.Start());
2940
mkwst202534e32016-01-15 16:07:152941 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152942 default_context_.set_network_delegate(&network_delegate);
2943
mkwstf71d0bd2016-03-21 14:15:242944 const std::string kHost = "example.test";
2945 const std::string kSubHost = "subdomain.example.test";
2946 const std::string kCrossHost = "cross-origin.test";
2947
2948 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262949 {
mkwst3f3daac2015-02-26 20:15:262950 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362951 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242952 test_server.GetURL(kHost,
2953 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2954 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:162955 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst3f3daac2015-02-26 20:15:262956 req->Start();
2957 base::RunLoop().Run();
2958 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2959 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242960 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262961 }
2962
mkwstf71d0bd2016-03-21 14:15:242963 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262964 {
mkwst3f3daac2015-02-26 20:15:262965 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362966 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162967 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2968 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462969 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
mkwstf71d0bd2016-03-21 14:15:242970 req->set_initiator(url::Origin(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262971 req->Start();
2972 base::RunLoop().Run();
2973
mkwstf71d0bd2016-03-21 14:15:242974 EXPECT_NE(std::string::npos,
2975 d.data_received().find("StrictSameSiteCookie=1"));
2976 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262977 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2978 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2979 }
2980
clamyfd58ca072016-12-21 17:18:322981 // Verify that both cookies are sent when the request has no initiator (can
2982 // happen for main frame browser-initiated navigations).
2983 {
2984 TestDelegate d;
2985 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162986 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2987 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462988 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:322989 req->Start();
2990 base::RunLoop().Run();
2991
2992 EXPECT_NE(std::string::npos,
2993 d.data_received().find("StrictSameSiteCookie=1"));
2994 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
2995 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2996 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2997 }
2998
mkwstf71d0bd2016-03-21 14:15:242999 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263000 {
mkwst3f3daac2015-02-26 20:15:263001 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363002 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163003 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3004 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463005 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
mkwstf71d0bd2016-03-21 14:15:243006 req->set_initiator(url::Origin(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153007 req->Start();
3008 base::RunLoop().Run();
3009
mkwstf71d0bd2016-03-21 14:15:243010 EXPECT_NE(std::string::npos,
3011 d.data_received().find("StrictSameSiteCookie=1"));
3012 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153013 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3014 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3015 }
3016
mkwstf71d0bd2016-03-21 14:15:243017 // Verify that neither cookie is not sent for cross-site requests.
3018 {
3019 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363020 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163021 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3022 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463023 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
mkwstf71d0bd2016-03-21 14:15:243024 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
3025 req->Start();
3026 base::RunLoop().Run();
3027
3028 EXPECT_EQ(std::string::npos,
3029 d.data_received().find("StrictSameSiteCookie=1"));
3030 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3031 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3032 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3033 }
3034
3035 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153036 // method is "safe".
3037 {
3038 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363039 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163040 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3041 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463042 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
mkwstf71d0bd2016-03-21 14:15:243043 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
3044 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153045 req->Start();
3046 base::RunLoop().Run();
3047
mkwstf71d0bd2016-03-21 14:15:243048 EXPECT_EQ(std::string::npos,
3049 d.data_received().find("StrictSameSiteCookie=1"));
3050 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153051 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3052 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3053 }
3054
mkwstf71d0bd2016-03-21 14:15:243055 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153056 // method is unsafe (e.g. POST).
3057 {
3058 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363059 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163060 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3061 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463062 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
mkwstf71d0bd2016-03-21 14:15:243063 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153064 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263065 req->Start();
3066 base::RunLoop().Run();
3067
mkwstf71d0bd2016-03-21 14:15:243068 EXPECT_EQ(std::string::npos,
3069 d.data_received().find("StrictSameSiteCookie=1"));
3070 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263071 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3072 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3073 }
3074}
3075
estark557a5eb82015-12-01 22:57:103076// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363077TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553078 EmbeddedTestServer http_server;
3079 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363080 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553081 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3082 https_server.AddDefaultHandlers(
3083 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3084 ASSERT_TRUE(http_server.Start());
3085 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363086
estarkb15166b2015-12-18 16:56:383087 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363088 TestURLRequestContext context(true);
3089 context.set_network_delegate(&network_delegate);
3090 context.Init();
3091
estarkb15166b2015-12-18 16:56:383092 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363093 {
3094 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363095 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103096 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163097 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363098 req->Start();
3099 base::RunLoop().Run();
3100 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3101 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3102 }
3103
3104 // Verify that the cookie is not set.
3105 {
3106 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363107 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163108 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3109 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363110 req->Start();
3111 base::RunLoop().Run();
3112
jww79aceda2015-12-07 01:56:343113 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3114 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363115 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3116 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3117 }
3118}
3119
estarkb15166b2015-12-18 16:56:383120TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553121 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3122 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363123 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553124 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363125
3126 TestNetworkDelegate network_delegate;
3127 TestURLRequestContext context(true);
3128 context.set_network_delegate(&network_delegate);
3129 context.Init();
3130
estarkb15166b2015-12-18 16:56:383131 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363132 {
3133 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163134 std::unique_ptr<URLRequest> req(context.CreateRequest(
3135 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3136 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363137 req->Start();
3138 base::RunLoop().Run();
3139 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3140 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3141 }
3142
3143 // Verify that the cookie is not set.
3144 {
3145 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363146 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163147 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3148 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363149 req->Start();
3150 base::RunLoop().Run();
3151
jww79aceda2015-12-07 01:56:343152 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363153 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3154 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3155 }
3156}
3157
estarkb15166b2015-12-18 16:56:383158TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553159 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3160 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363161 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553162 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363163
estarkb15166b2015-12-18 16:56:383164 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363165 TestURLRequestContext context(true);
3166 context.set_network_delegate(&network_delegate);
3167 context.Init();
3168
estarkb15166b2015-12-18 16:56:383169 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363170 {
3171 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363172 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103173 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163174 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363175 req->Start();
3176 base::RunLoop().Run();
3177 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3178 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3179 }
3180
3181 // Verify that the cookie is set.
3182 {
3183 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363184 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163185 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3186 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363187 req->Start();
3188 base::RunLoop().Run();
3189
jww79aceda2015-12-07 01:56:343190 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3191 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3192 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3193 }
3194}
3195
3196// Tests that secure cookies can't be set on non-secure origins if strict secure
3197// cookies are enabled.
3198TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3199 EmbeddedTestServer http_server;
3200 http_server.AddDefaultHandlers(
3201 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3202 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3203 https_server.AddDefaultHandlers(
3204 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3205 ASSERT_TRUE(http_server.Start());
3206 ASSERT_TRUE(https_server.Start());
3207
3208 TestExperimentalFeaturesNetworkDelegate network_delegate;
3209 TestURLRequestContext context(true);
3210 context.set_network_delegate(&network_delegate);
3211 context.Init();
3212
3213 // Try to set a Secure cookie, with experimental features enabled.
3214 {
3215 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363216 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343217 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163218 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343219 req->Start();
3220 base::RunLoop().Run();
3221 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3222 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3223 }
3224
3225 // Verify that the cookie is not set.
3226 {
3227 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363228 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163229 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3230 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343231 req->Start();
3232 base::RunLoop().Run();
3233
3234 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3235 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3236 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3237 }
3238}
3239
3240// Tests that secure cookies can be set on secure origins even if strict secure
3241// cookies are enabled.
3242TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
3243 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3244 https_server.AddDefaultHandlers(
3245 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3246 ASSERT_TRUE(https_server.Start());
3247
3248 TestExperimentalFeaturesNetworkDelegate network_delegate;
3249 TestURLRequestContext context(true);
3250 context.set_network_delegate(&network_delegate);
3251 context.Init();
3252
3253 // Try to set a Secure cookie, with experimental features enabled.
3254 {
3255 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363256 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343257 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163258 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343259 req->Start();
3260 base::RunLoop().Run();
3261 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3262 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3263 }
3264
3265 // Verify that the cookie is not set.
3266 {
3267 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363268 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163269 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3270 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343271 req->Start();
3272 base::RunLoop().Run();
3273
3274 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363275 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3276 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3277 }
3278}
3279
Mike West86149882017-07-28 10:41:493280TEST_F(URLRequestTest, CookieAgeMetrics) {
3281 EmbeddedTestServer http_server;
3282 http_server.AddDefaultHandlers(
3283 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3284 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3285 https_server.AddDefaultHandlers(
3286 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3287 ASSERT_TRUE(http_server.Start());
3288 ASSERT_TRUE(https_server.Start());
3289
3290 TestNetworkDelegate network_delegate;
3291 default_context_.set_network_delegate(&network_delegate);
3292 base::HistogramTester histograms;
3293
3294 const std::string kHost = "example.test";
3295 const std::string kCrossHost = "cross-origin.test";
3296
3297 // Set a test cookie.
3298 {
3299 TestDelegate d;
3300 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3301 http_server.GetURL(kHost, "/set-cookie?cookie=value"), DEFAULT_PRIORITY,
3302 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3303 req->Start();
3304 base::RunLoop().Run();
3305 ASSERT_EQ(1, network_delegate.set_cookie_count());
3306 }
3307
3308 // Make a secure request to `example.test`: we shouldn't record data.
3309 {
3310 TestDelegate d;
3311 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3312 https_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3313 TRAFFIC_ANNOTATION_FOR_TESTS));
3314 req->Start();
3315 base::RunLoop().Run();
3316 histograms.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3317 histograms.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3318 }
3319
3320 // Make a non-secure same-site request.
3321 {
3322 TestDelegate d;
3323 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3324 http_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3325 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463326 req->set_site_for_cookies(http_server.GetURL(kHost, "/"));
Mike West86149882017-07-28 10:41:493327 req->set_initiator(url::Origin(http_server.GetURL(kHost, "/")));
3328 req->Start();
3329 base::RunLoop().Run();
3330 histograms.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3331 histograms.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 1);
3332 }
3333
3334 // Make a non-secure cross-site request.
3335 {
3336 TestDelegate d;
3337 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3338 http_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3339 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463340 req->set_site_for_cookies(http_server.GetURL(kCrossHost, "/"));
Mike West86149882017-07-28 10:41:493341 req->set_initiator(url::Origin(http_server.GetURL(kCrossHost, "/")));
3342 req->Start();
3343 base::RunLoop().Run();
3344 histograms.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 1);
3345 histograms.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 1);
3346 }
3347}
3348
mmenkefb18c772015-09-30 22:22:503349// Tests that a request is cancelled while entering suspend mode. Uses mocks
3350// rather than a spawned test server because the connection used to talk to
3351// the test server is affected by entering suspend mode on Android.
3352TEST_F(URLRequestTest, CancelOnSuspend) {
3353 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363354 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503355
3356 URLRequestFailedJob::AddUrlHandler();
3357
3358 TestDelegate d;
3359 // Request that just hangs.
3360 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
rhalavatib7bd7c792017-04-27 05:25:163361 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3362 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mmenkefb18c772015-09-30 22:22:503363 r->Start();
3364
3365 power_monitor_source->Suspend();
3366 // Wait for the suspend notification to cause the request to fail.
3367 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:503368 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503369 EXPECT_TRUE(d.request_failed());
3370 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3371
3372 URLRequestFilter::GetInstance()->ClearHandlers();
3373
3374 // Shouldn't be needed, but just in case.
3375 power_monitor_source->Resume();
3376}
3377
[email protected]5095cd72012-11-01 10:29:163378// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3379// value for the |fixed_date| argument given to the constructor.
3380class FixedDateNetworkDelegate : public TestNetworkDelegate {
3381 public:
3382 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3383 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203384 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163385
[email protected]cba24642014-08-15 20:49:593386 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203387 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593388 URLRequest* request,
3389 const CompletionCallback& callback,
3390 const HttpResponseHeaders* original_response_headers,
3391 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133392 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163393
3394 private:
3395 std::string fixed_date_;
3396
3397 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3398};
3399
3400int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593401 URLRequest* request,
3402 const CompletionCallback& callback,
3403 const HttpResponseHeaders* original_response_headers,
3404 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163405 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593406 HttpResponseHeaders* new_response_headers =
3407 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163408
3409 new_response_headers->RemoveHeader("Date");
3410 new_response_headers->AddHeader("Date: " + fixed_date_);
3411
3412 *override_response_headers = new_response_headers;
3413 return TestNetworkDelegate::OnHeadersReceived(request,
3414 callback,
3415 original_response_headers,
[email protected]5f714132014-03-26 10:41:163416 override_response_headers,
3417 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163418}
3419
3420// Test that cookie expiration times are adjusted for server/client clock
3421// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3422// headers by defaulting to GMT. (crbug.com/135131)
3423TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3424 LocalHttpTestServer test_server;
3425 ASSERT_TRUE(test_server.Start());
3426
3427 // Set up an expired cookie.
3428 {
3429 TestNetworkDelegate network_delegate;
3430 default_context_.set_network_delegate(&network_delegate);
3431 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363432 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193433 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553434 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163435 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193436 req->Start();
[email protected]255620da2013-08-19 13:14:293437 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163438 }
3439 // Verify that the cookie is not set.
3440 {
3441 TestNetworkDelegate network_delegate;
3442 default_context_.set_network_delegate(&network_delegate);
3443 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363444 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163445 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3446 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193447 req->Start();
[email protected]255620da2013-08-19 13:14:293448 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163449
3450 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3451 }
3452 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3453 {
3454 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3455 default_context_.set_network_delegate(&network_delegate);
3456 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363457 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193458 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553459 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163460 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193461 req->Start();
[email protected]255620da2013-08-19 13:14:293462 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163463 }
3464 // Verify that the cookie is set.
3465 {
3466 TestNetworkDelegate network_delegate;
3467 default_context_.set_network_delegate(&network_delegate);
3468 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363469 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163470 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3471 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193472 req->Start();
[email protected]255620da2013-08-19 13:14:293473 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163474
3475 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3476 }
3477}
3478
3479
[email protected]316c1e5e2012-09-12 15:17:443480// Check that it is impossible to change the referrer in the extra headers of
3481// an URLRequest.
3482TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3483 LocalHttpTestServer test_server;
3484 ASSERT_TRUE(test_server.Start());
3485
3486 // If extra headers contain referer and the request contains a referer,
3487 // only the latter shall be respected.
3488 {
3489 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363490 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163491 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3492 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193493 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443494
3495 HttpRequestHeaders headers;
3496 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193497 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443498
[email protected]f7022f32014-08-21 16:32:193499 req->Start();
[email protected]255620da2013-08-19 13:14:293500 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443501
3502 EXPECT_EQ("http://foo.com/", d.data_received());
3503 }
3504
3505 // If extra headers contain a referer but the request does not, no referer
3506 // shall be sent in the header.
3507 {
3508 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363509 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163510 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3511 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:443512
3513 HttpRequestHeaders headers;
3514 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193515 req->SetExtraRequestHeaders(headers);
3516 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443517
[email protected]f7022f32014-08-21 16:32:193518 req->Start();
[email protected]255620da2013-08-19 13:14:293519 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443520
3521 EXPECT_EQ("None", d.data_received());
3522 }
3523}
3524
[email protected]b89290212009-08-14 22:37:353525class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113526 public:
mmenke9f2ec60c2015-06-01 20:59:473527 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113528
[email protected]b89290212009-08-14 22:37:353529 protected:
[email protected]21184962011-10-26 00:50:303530 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3531 // |request_method| is the method to use for the initial request.
3532 // |redirect_method| is the method that is expected to be used for the second
3533 // request, after redirection.
3534 // If |include_data| is true, data is uploaded with the request. The
3535 // response body is expected to match it exactly, if and only if
3536 // |request_method| == |redirect_method|.
3537 void HTTPRedirectMethodTest(const GURL& redirect_url,
3538 const std::string& request_method,
3539 const std::string& redirect_method,
3540 bool include_data) {
3541 static const char kData[] = "hello world";
3542 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163543 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3544 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193545 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303546 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073547 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303548 HttpRequestHeaders headers;
3549 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513550 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543551 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193552 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303553 }
[email protected]f7022f32014-08-21 16:32:193554 req->Start();
[email protected]255620da2013-08-19 13:14:293555 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193556 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:503557 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:303558 if (include_data) {
3559 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543560 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3561 HttpRequestHeaders::kContentLength));
3562 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3563 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303564 EXPECT_EQ(kData, d.data_received());
3565 } else {
svaldez5b3a8972015-10-09 23:23:543566 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3567 HttpRequestHeaders::kContentLength));
3568 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3569 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303570 EXPECT_NE(kData, d.data_received());
3571 }
3572 }
3573 if (HasFailure())
3574 LOG(WARNING) << "Request method was: " << request_method;
3575 }
3576
jww5fe460ff2015-03-28 00:22:513577 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3578 // |request_method| is the method to use for the initial request.
3579 // |redirect_method| is the method that is expected to be used for the second
3580 // request, after redirection.
3581 // |origin_value| is the expected value for the Origin header after
3582 // redirection. If empty, expects that there will be no Origin header.
3583 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3584 const std::string& request_method,
3585 const std::string& redirect_method,
3586 const std::string& origin_value) {
3587 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163588 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3589 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:513590 req->set_method(request_method);
3591 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3592 redirect_url.GetOrigin().spec(), false);
3593 req->Start();
3594
3595 base::RunLoop().Run();
3596
3597 EXPECT_EQ(redirect_method, req->method());
3598 // Note that there is no check for request success here because, for
3599 // purposes of testing, the request very well may fail. For example, if the
3600 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3601 // origin, there is not an HTTPS server in this unit test framework, so the
3602 // request would fail. However, that's fine, as long as the request headers
3603 // are in order and pass the checks below.
3604 if (origin_value.empty()) {
3605 EXPECT_FALSE(
3606 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3607 } else {
3608 std::string origin_header;
3609 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3610 HttpRequestHeaders::kOrigin, &origin_header));
3611 EXPECT_EQ(origin_value, origin_header);
3612 }
3613 }
3614
[email protected]762d2db2010-01-11 19:03:013615 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013616 const int kMsgSize = 20000; // multiple of 10
3617 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483618 char* uploadBytes = new char[kMsgSize+1];
3619 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013620 char marker = 'a';
3621 for (int idx = 0; idx < kMsgSize/10; idx++) {
3622 memcpy(ptr, "----------", 10);
3623 ptr += 10;
3624 if (idx % 100 == 0) {
3625 ptr--;
3626 *ptr++ = marker;
3627 if (++marker > 'z')
3628 marker = 'a';
3629 }
3630 }
3631 uploadBytes[kMsgSize] = '\0';
3632
[email protected]762d2db2010-01-11 19:03:013633 for (int i = 0; i < kIterations; ++i) {
3634 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363635 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163636 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
3637 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193638 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013639
mmenkecbc2b712014-10-09 20:29:073640 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013641
[email protected]f7022f32014-08-21 16:32:193642 r->Start();
3643 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013644
[email protected]255620da2013-08-19 13:14:293645 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013646
maksim.sisovb53724b52016-09-16 05:30:503647 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
3648 << d.request_status();
[email protected]762d2db2010-01-11 19:03:013649
3650 EXPECT_FALSE(d.received_data_before_response());
3651 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013652 }
3653 delete[] uploadBytes;
3654 }
3655
[email protected]ede03212012-09-07 12:52:263656 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343657 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363658 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553659 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363660 base::IntToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:163661 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:343662
[email protected]f7022f32014-08-21 16:32:193663 r->Start();
3664 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343665
[email protected]255620da2013-08-19 13:14:293666 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343667
maksim.sisovb53724b52016-09-16 05:30:503668 if (d.request_status() != OK) {
3669 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
3670 return false;
3671 }
[email protected]263163f2012-06-14 22:40:343672
maksim.sisovb53724b52016-09-16 05:30:503673 return true;
[email protected]263163f2012-06-14 22:40:343674 }
3675
tommycli59a63432015-11-06 00:10:553676 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503677
tommycli59a63432015-11-06 00:10:553678 private:
[email protected]1700c6a2012-02-22 18:07:073679 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353680};
3681
tommycli59a63432015-11-06 00:10:553682namespace {
3683
danakj8522a25b2016-04-16 00:17:363684std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:553685 const test_server::HttpRequest& request) {
3686 if (request.headers.find("Host") == request.headers.end() ||
3687 request.headers.at("Host") != "www.redirect.com" ||
3688 request.method != test_server::METHOD_CONNECT) {
3689 return nullptr;
3690 }
3691
danakj8522a25b2016-04-16 00:17:363692 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:553693 new test_server::BasicHttpResponse);
3694 http_response->set_code(HTTP_FOUND);
3695 http_response->AddCustomHeader("Location",
3696 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483697 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553698}
3699
3700} // namespace
3701
nharperb7441ef2016-01-25 23:54:143702class TestSSLConfigService : public SSLConfigService {
3703 public:
3704 TestSSLConfigService(bool ev_enabled,
3705 bool online_rev_checking,
3706 bool rev_checking_required_local_anchors,
3707 bool token_binding_enabled)
3708 : ev_enabled_(ev_enabled),
3709 online_rev_checking_(online_rev_checking),
3710 rev_checking_required_local_anchors_(
3711 rev_checking_required_local_anchors),
3712 token_binding_enabled_(token_binding_enabled),
davidben095ebb52017-04-12 22:23:343713 min_version_(kDefaultSSLVersionMin),
3714 max_version_(kDefaultSSLVersionMax) {}
nharperb7441ef2016-01-25 23:54:143715
davidben095ebb52017-04-12 22:23:343716 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:143717 void set_min_version(uint16_t version) { min_version_ = version; }
3718
nharperb7441ef2016-01-25 23:54:143719 // SSLConfigService:
3720 void GetSSLConfig(SSLConfig* config) override {
3721 *config = SSLConfig();
3722 config->rev_checking_enabled = online_rev_checking_;
3723 config->verify_ev_cert = ev_enabled_;
3724 config->rev_checking_required_local_anchors =
3725 rev_checking_required_local_anchors_;
davidben095ebb52017-04-12 22:23:343726 config->version_min = min_version_;
3727 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:143728 if (token_binding_enabled_) {
3729 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3730 }
3731 }
3732
3733 protected:
3734 ~TestSSLConfigService() override {}
3735
3736 private:
3737 const bool ev_enabled_;
3738 const bool online_rev_checking_;
3739 const bool rev_checking_required_local_anchors_;
3740 const bool token_binding_enabled_;
3741 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:343742 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:143743};
3744
3745// TODO(svaldez): Update tests to use EmbeddedTestServer.
3746#if !defined(OS_IOS)
3747class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3748 public:
fdoray9f0b4782017-02-10 12:55:473749 TokenBindingURLRequestTest() = default;
fdoraya89e673c2017-01-31 21:44:213750
nharperb7441ef2016-01-25 23:54:143751 void SetUp() override {
3752 default_context_.set_ssl_config_service(
3753 new TestSSLConfigService(false, false, false, true));
fdoraya89e673c2017-01-31 21:44:213754 channel_id_service_.reset(
3755 new ChannelIDService(new DefaultChannelIDStore(NULL)));
nharperb7441ef2016-01-25 23:54:143756 default_context_.set_channel_id_service(channel_id_service_.get());
3757 URLRequestTestHTTP::SetUp();
3758 }
3759
3760 protected:
danakj8522a25b2016-04-16 00:17:363761 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:143762};
3763
3764TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3765 SpawnedTestServer::SSLOptions ssl_options;
3766 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3767 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3768 ssl_options,
3769 base::FilePath(kTestFilePath));
3770 ASSERT_TRUE(https_test_server.Start());
3771
3772 TestDelegate d;
3773 {
danakj8522a25b2016-04-16 00:17:363774 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163775 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d,
3776 TRAFFIC_ANNOTATION_FOR_TESTS));
nharperb7441ef2016-01-25 23:54:143777 r->Start();
3778 EXPECT_TRUE(r->is_pending());
3779
3780 base::RunLoop().Run();
3781
maksim.sisovb53724b52016-09-16 05:30:503782 EXPECT_EQ(OK, d.request_status());
nharperb7441ef2016-01-25 23:54:143783
3784 HttpRequestHeaders headers;
3785 std::string token_binding_header, token_binding_message;
3786 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3787 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3788 &token_binding_header));
3789 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353790 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperb7441ef2016-01-25 23:54:143791 &token_binding_message));
nharperd6e65822016-03-30 23:05:483792 std::vector<TokenBinding> token_bindings;
3793 ASSERT_TRUE(
3794 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3795 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:143796
3797 EXPECT_GT(d.bytes_received(), 0);
3798 std::string ekm = d.data_received();
3799
nharperd6e65822016-03-30 23:05:483800 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353801 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3802 token_bindings[0].signature,
3803 TokenBindingType::PROVIDED, ekm));
nharperb7441ef2016-01-25 23:54:143804 }
3805}
nharperd6e65822016-03-30 23:05:483806
3807TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
3808 SpawnedTestServer::SSLOptions ssl_options;
3809 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3810 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3811 ssl_options,
3812 base::FilePath(kTestFilePath));
3813 ASSERT_TRUE(https_test_server.Start());
3814
3815 TestDelegate d;
3816 {
3817 GURL redirect_url =
3818 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
rhalavatib7bd7c792017-04-27 05:25:163819 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3820 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:483821 r->Start();
3822 EXPECT_TRUE(r->is_pending());
3823
3824 base::RunLoop().Run();
3825
maksim.sisovb53724b52016-09-16 05:30:503826 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483827
3828 HttpRequestHeaders headers;
3829 std::string token_binding_header, token_binding_message;
3830 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3831 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3832 &token_binding_header));
3833 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353834 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483835 &token_binding_message));
3836 std::vector<TokenBinding> token_bindings;
3837 ASSERT_TRUE(
3838 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3839 ASSERT_EQ(2ull, token_bindings.size());
3840
3841 EXPECT_GT(d.bytes_received(), 0);
3842 std::string ekm = d.data_received();
3843
3844 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353845 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3846 token_bindings[0].signature,
3847 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483848 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
nharper78e6d2b2016-09-21 05:42:353849 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[1].ec_point,
3850 token_bindings[1].signature,
3851 TokenBindingType::REFERRED, ekm));
nharperd6e65822016-03-30 23:05:483852 }
3853}
3854
3855// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
3856// EmbeddedTestServer once crbug.com/599187 is resolved.
3857#if !defined(OS_ANDROID)
3858TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
Sergey Ulanov9e8d6f32017-08-14 22:12:583859 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP, base::FilePath());
nharperd6e65822016-03-30 23:05:483860 ASSERT_TRUE(http_server.Start());
3861 SpawnedTestServer::SSLOptions ssl_options;
3862 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3863 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3864 ssl_options,
3865 base::FilePath(kTestFilePath));
3866 ASSERT_TRUE(https_test_server.Start());
3867
3868 TestDelegate d;
3869 {
3870 GURL redirect_url = http_server.GetURL(
3871 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
rhalavatib7bd7c792017-04-27 05:25:163872 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3873 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:483874 r->Start();
3875 EXPECT_TRUE(r->is_pending());
3876
3877 base::RunLoop().Run();
3878
maksim.sisovb53724b52016-09-16 05:30:503879 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483880
3881 HttpRequestHeaders headers;
3882 std::string token_binding_header, token_binding_message;
3883 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3884 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3885 &token_binding_header));
3886 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353887 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483888 &token_binding_message));
3889 std::vector<TokenBinding> token_bindings;
3890 ASSERT_TRUE(
3891 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3892 ASSERT_EQ(1ull, token_bindings.size());
3893
3894 EXPECT_GT(d.bytes_received(), 0);
3895 std::string ekm = d.data_received();
3896
3897 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353898 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3899 token_bindings[0].signature,
3900 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483901 }
3902}
3903
3904// Test that if a server supporting Token Binding redirects (with
nharper86f0be22016-07-14 00:49:363905// Include-Referred-Token-Binding-ID) to an https url on a server that does not
nharperd6e65822016-03-30 23:05:483906// support Token Binding, then we do not send a Sec-Token-Binding when following
3907// the redirect.
3908TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
3909 SpawnedTestServer::SSLOptions ssl_options;
3910 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3911 ssl_options,
3912 base::FilePath(kTestFilePath));
3913 ASSERT_TRUE(https_test_server.Start());
3914 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3915 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
3916 ssl_options,
3917 base::FilePath(kTestFilePath));
3918 ASSERT_TRUE(token_binding_test_server.Start());
3919
3920 TestDelegate d;
3921 {
3922 GURL redirect_url = token_binding_test_server.GetURL(
3923 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
rhalavatib7bd7c792017-04-27 05:25:163924 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3925 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:483926 r->Start();
3927 EXPECT_TRUE(r->is_pending());
3928
3929 base::RunLoop().Run();
3930
maksim.sisovb53724b52016-09-16 05:30:503931 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483932
3933 HttpRequestHeaders headers;
3934 std::string token_binding_header, token_binding_message;
3935 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3936 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3937 &token_binding_header));
3938 }
3939}
3940#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:143941#endif // !defined(OS_IOS)
3942
3943// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113944// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553945// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113946// follow.
[email protected]f2f31b32013-01-16 23:24:093947TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553948 http_test_server()->RegisterRequestHandler(
3949 base::Bind(&HandleRedirectConnect));
3950 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113951
[email protected]ceefd7fd2012-11-29 00:36:243952 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043953 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553954 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503955
[email protected]d1ec59082009-02-11 02:48:153956 TestDelegate d;
3957 {
danakj8522a25b2016-04-16 00:17:363958 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163959 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
3960 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193961 r->Start();
3962 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153963
[email protected]255620da2013-08-19 13:14:293964 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153965
[email protected]d8fc4722014-06-13 13:17:153966 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:473967 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:503968 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:083969 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153970 // We should not have followed the redirect.
3971 EXPECT_EQ(0, d.received_redirect_count());
3972 }
3973}
3974
[email protected]8202d0c2011-02-23 08:31:143975// This is the same as the previous test, but checks that the network delegate
3976// registers the error.
[email protected]c044616e2013-02-20 02:01:263977TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553978 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143979
[email protected]ceefd7fd2012-11-29 00:36:243980 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043981 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553982 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503983
[email protected]8202d0c2011-02-23 08:31:143984 TestDelegate d;
3985 {
danakj8522a25b2016-04-16 00:17:363986 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163987 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
3988 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193989 r->Start();
3990 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143991
[email protected]255620da2013-08-19 13:14:293992 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143993
[email protected]d8fc4722014-06-13 13:17:153994 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:473995 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:143996 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:503997 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:143998 // We should not have followed the redirect.
3999 EXPECT_EQ(0, d.received_redirect_count());
4000
4001 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014002 EXPECT_THAT(network_delegate.last_error(),
4003 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144004 }
4005}
4006
[email protected]dc5a5cf2012-09-26 02:49:304007// Tests that we can block and asynchronously return OK in various stages.
4008TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4009 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4010 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4011 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4012 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4013 };
4014 static const size_t blocking_stages_length = arraysize(blocking_stages);
4015
tommycli59a63432015-11-06 00:10:554016 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304017
4018 TestDelegate d;
4019 BlockingNetworkDelegate network_delegate(
4020 BlockingNetworkDelegate::USER_CALLBACK);
4021 network_delegate.set_block_on(
4022 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4023 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4024 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4025
4026 TestURLRequestContext context(true);
4027 context.set_network_delegate(&network_delegate);
4028 context.Init();
4029
4030 {
danakj8522a25b2016-04-16 00:17:364031 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164032 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4033 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304034
[email protected]f7022f32014-08-21 16:32:194035 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304036 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:294037 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304038 EXPECT_EQ(blocking_stages[i],
4039 network_delegate.stage_blocked_for_callback());
4040 network_delegate.DoCallback(OK);
4041 }
[email protected]255620da2013-08-19 13:14:294042 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194043 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504044 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304045 EXPECT_EQ(1, network_delegate.created_requests());
4046 EXPECT_EQ(0, network_delegate.destroyed_requests());
4047 }
4048 EXPECT_EQ(1, network_delegate.destroyed_requests());
4049}
4050
[email protected]4c76d7c2011-04-15 19:14:124051// Tests that the network delegate can block and cancel a request.
4052TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554053 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124054
4055 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304056 BlockingNetworkDelegate network_delegate(
4057 BlockingNetworkDelegate::AUTO_CALLBACK);
4058 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4059 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124060
[email protected]d5a4dd62012-05-23 01:41:044061 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554062 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504063
[email protected]4c76d7c2011-04-15 19:14:124064 {
rhalavatib7bd7c792017-04-27 05:25:164065 std::unique_ptr<URLRequest> r(
4066 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4067 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124068
[email protected]f7022f32014-08-21 16:32:194069 r->Start();
[email protected]255620da2013-08-19 13:14:294070 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:124071
[email protected]d8fc4722014-06-13 13:17:154072 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474073 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504074 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124075 EXPECT_EQ(1, network_delegate.created_requests());
4076 EXPECT_EQ(0, network_delegate.destroyed_requests());
4077 }
4078 EXPECT_EQ(1, network_delegate.destroyed_requests());
4079}
4080
[email protected]b4438d32012-09-27 06:15:304081// Helper function for NetworkDelegateCancelRequestAsynchronously and
4082// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4083// delegate operating in |block_mode| and a request for |url|. It blocks the
4084// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4085void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4086 BlockingNetworkDelegate::Stage stage,
4087 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364088 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304089 BlockingNetworkDelegate network_delegate(block_mode);
4090 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4091 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364092
[email protected]b4438d32012-09-27 06:15:304093 TestURLRequestContext context(true);
4094 context.set_network_delegate(&network_delegate);
4095 context.Init();
[email protected]3cd384c602011-08-31 16:12:364096
4097 {
rhalavatib7bd7c792017-04-27 05:25:164098 std::unique_ptr<URLRequest> r(context.CreateRequest(
4099 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364100
[email protected]f7022f32014-08-21 16:32:194101 r->Start();
[email protected]255620da2013-08-19 13:14:294102 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:364103
[email protected]d8fc4722014-06-13 13:17:154104 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474105 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4106 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4107 EXPECT_FALSE(r->proxy_server().is_valid());
4108 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4109 EXPECT_TRUE(r->proxy_server().is_direct());
4110 } else {
4111 NOTREACHED();
4112 }
maksim.sisovb53724b52016-09-16 05:30:504113 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364114 EXPECT_EQ(1, network_delegate.created_requests());
4115 EXPECT_EQ(0, network_delegate.destroyed_requests());
4116 }
4117 EXPECT_EQ(1, network_delegate.destroyed_requests());
4118}
4119
[email protected]b4438d32012-09-27 06:15:304120// The following 3 tests check that the network delegate can cancel a request
4121// synchronously in various stages of the request.
4122TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554123 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304124 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4125 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554126 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304127}
4128
4129TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554130 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304131 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4132 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554133 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304134}
4135
4136TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554137 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304138 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4139 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554140 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304141}
4142
4143// The following 3 tests check that the network delegate can cancel a request
4144// asynchronously in various stages of the request.
4145TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554146 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304147 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4148 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554149 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304150}
4151
4152TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554153 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304154 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4155 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554156 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304157}
4158
4159TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554160 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304161 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4162 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554163 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304164}
4165
[email protected]4c76d7c2011-04-15 19:14:124166// Tests that the network delegate can block and redirect a request to a new
4167// URL.
4168TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554169 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124170
4171 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304172 BlockingNetworkDelegate network_delegate(
4173 BlockingNetworkDelegate::AUTO_CALLBACK);
4174 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554175 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:124176 network_delegate.set_redirect_url(redirect_url);
4177
[email protected]d5a4dd62012-05-23 01:41:044178 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554179 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504180
[email protected]4c76d7c2011-04-15 19:14:124181 {
tommycli59a63432015-11-06 00:10:554182 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164183 std::unique_ptr<URLRequest> r(context.CreateRequest(
4184 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124185
[email protected]6be6fa92014-08-06 23:44:564186 // Quit after hitting the redirect, so can check the headers.
4187 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194188 r->Start();
[email protected]255620da2013-08-19 13:14:294189 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:124190
[email protected]6be6fa92014-08-06 23:44:564191 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194192 EXPECT_EQ(307, r->GetResponseCode());
4193 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564194 std::string location;
[email protected]f7022f32014-08-21 16:32:194195 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4196 &location));
[email protected]6be6fa92014-08-06 23:44:564197 EXPECT_EQ(redirect_url, GURL(location));
4198
4199 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194200 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564201 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:504202 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474203 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4204 http_test_server()->host_port_pair()),
4205 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094206 // before_send_headers_with_proxy_count only increments for headers sent
4207 // through an untunneled proxy.
4208 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554209 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4210 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274211
maksim.sisovb53724b52016-09-16 05:30:504212 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194213 EXPECT_EQ(redirect_url, r->url());
4214 EXPECT_EQ(original_url, r->original_url());
4215 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124216 EXPECT_EQ(1, network_delegate.created_requests());
4217 EXPECT_EQ(0, network_delegate.destroyed_requests());
4218 }
4219 EXPECT_EQ(1, network_delegate.destroyed_requests());
4220}
4221
[email protected]b813ed72012-04-05 08:21:364222// Tests that the network delegate can block and redirect a request to a new
4223// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4224TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554225 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364226
4227 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304228 BlockingNetworkDelegate network_delegate(
4229 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:554230 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:364231 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364232
[email protected]d5a4dd62012-05-23 01:41:044233 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554234 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364235
4236 {
tommycli59a63432015-11-06 00:10:554237 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164238 std::unique_ptr<URLRequest> r(context.CreateRequest(
4239 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364240
[email protected]6be6fa92014-08-06 23:44:564241 // Quit after hitting the redirect, so can check the headers.
4242 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194243 r->Start();
[email protected]255620da2013-08-19 13:14:294244 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:364245
[email protected]6be6fa92014-08-06 23:44:564246 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194247 EXPECT_EQ(307, r->GetResponseCode());
4248 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564249 std::string location;
[email protected]f7022f32014-08-21 16:32:194250 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4251 &location));
[email protected]6be6fa92014-08-06 23:44:564252 EXPECT_EQ(redirect_url, GURL(location));
4253
4254 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194255 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564256 base::RunLoop().Run();
4257
maksim.sisovb53724b52016-09-16 05:30:504258 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474259 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4260 http_test_server()->host_port_pair()),
4261 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094262 // before_send_headers_with_proxy_count only increments for headers sent
4263 // through an untunneled proxy.
4264 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554265 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4266 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504267 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194268 EXPECT_EQ(redirect_url, r->url());
4269 EXPECT_EQ(original_url, r->original_url());
4270 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364271 EXPECT_EQ(1, network_delegate.created_requests());
4272 EXPECT_EQ(0, network_delegate.destroyed_requests());
4273 }
4274 EXPECT_EQ(1, network_delegate.destroyed_requests());
4275}
4276
[email protected]3c5ca8c2011-09-29 01:14:514277// Tests that redirects caused by the network delegate preserve POST data.
4278TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554279 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514280
4281 const char kData[] = "hello world";
4282
4283 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304284 BlockingNetworkDelegate network_delegate(
4285 BlockingNetworkDelegate::AUTO_CALLBACK);
4286 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554287 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514288 network_delegate.set_redirect_url(redirect_url);
4289
[email protected]ef2bf422012-05-11 03:27:094290 TestURLRequestContext context(true);
4291 context.set_network_delegate(&network_delegate);
4292 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514293
4294 {
tommycli59a63432015-11-06 00:10:554295 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164296 std::unique_ptr<URLRequest> r(context.CreateRequest(
4297 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194298 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074299 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514300 HttpRequestHeaders headers;
4301 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:514302 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194303 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564304
4305 // Quit after hitting the redirect, so can check the headers.
4306 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194307 r->Start();
[email protected]255620da2013-08-19 13:14:294308 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:514309
[email protected]6be6fa92014-08-06 23:44:564310 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194311 EXPECT_EQ(307, r->GetResponseCode());
4312 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564313 std::string location;
[email protected]f7022f32014-08-21 16:32:194314 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4315 &location));
[email protected]6be6fa92014-08-06 23:44:564316 EXPECT_EQ(redirect_url, GURL(location));
4317
4318 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194319 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564320 base::RunLoop().Run();
4321
maksim.sisovb53724b52016-09-16 05:30:504322 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194323 EXPECT_EQ(redirect_url, r->url());
4324 EXPECT_EQ(original_url, r->original_url());
4325 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514326 EXPECT_EQ(1, network_delegate.created_requests());
4327 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194328 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514329 EXPECT_EQ(kData, d.data_received());
4330 }
4331 EXPECT_EQ(1, network_delegate.destroyed_requests());
4332}
4333
[email protected]5f714132014-03-26 10:41:164334// Tests that the network delegate can block and redirect a request to a new
4335// URL during OnHeadersReceived.
4336TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554337 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164338
4339 TestDelegate d;
4340 BlockingNetworkDelegate network_delegate(
4341 BlockingNetworkDelegate::AUTO_CALLBACK);
4342 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:554343 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:164344 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4345
4346 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554347 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164348
4349 {
tommycli59a63432015-11-06 00:10:554350 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164351 std::unique_ptr<URLRequest> r(context.CreateRequest(
4352 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164353
[email protected]f7022f32014-08-21 16:32:194354 r->Start();
[email protected]5f714132014-03-26 10:41:164355 base::RunLoop().Run();
4356
maksim.sisovb53724b52016-09-16 05:30:504357 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474358 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4359 http_test_server()->host_port_pair()),
4360 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094361 // before_send_headers_with_proxy_count only increments for headers sent
4362 // through an untunneled proxy.
4363 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554364 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4365 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194366
maksim.sisovb53724b52016-09-16 05:30:504367 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194368 EXPECT_EQ(redirect_url, r->url());
4369 EXPECT_EQ(original_url, r->original_url());
4370 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164371 EXPECT_EQ(2, network_delegate.created_requests());
4372 EXPECT_EQ(0, network_delegate.destroyed_requests());
4373 }
4374 EXPECT_EQ(1, network_delegate.destroyed_requests());
4375}
4376
[email protected]c2911d72011-10-03 22:16:364377// Tests that the network delegate can synchronously complete OnAuthRequired
4378// by taking no action. This indicates that the NetworkDelegate does not want to
4379// handle the challenge, and is passing the buck along to the
4380// URLRequest::Delegate.
4381TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554382 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364383
4384 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304385 BlockingNetworkDelegate network_delegate(
4386 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364387
[email protected]ef2bf422012-05-11 03:27:094388 TestURLRequestContext context(true);
4389 context.set_network_delegate(&network_delegate);
4390 context.Init();
[email protected]c2911d72011-10-03 22:16:364391
[email protected]f3cf9802011-10-28 18:44:584392 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364393
4394 {
tommycli59a63432015-11-06 00:10:554395 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164396 std::unique_ptr<URLRequest> r(context.CreateRequest(
4397 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194398 r->Start();
[email protected]79e1fd62013-06-20 06:50:044399
[email protected]255620da2013-08-19 13:14:294400 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044401
maksim.sisovb53724b52016-09-16 05:30:504402 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194403 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044404 EXPECT_TRUE(d.auth_required_called());
4405 EXPECT_EQ(1, network_delegate.created_requests());
4406 EXPECT_EQ(0, network_delegate.destroyed_requests());
4407 }
4408 EXPECT_EQ(1, network_delegate.destroyed_requests());
4409}
4410
4411TEST_F(URLRequestTestHTTP,
4412 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554413 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044414
4415 TestDelegate d;
4416 BlockingNetworkDelegate network_delegate(
4417 BlockingNetworkDelegate::SYNCHRONOUS);
4418
4419 TestURLRequestContext context(true);
4420 context.set_network_delegate(&network_delegate);
4421 context.Init();
4422
4423 d.set_credentials(AuthCredentials(kUser, kSecret));
4424
4425 {
tommycli59a63432015-11-06 00:10:554426 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164427 std::unique_ptr<URLRequest> r(context.CreateRequest(
4428 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194429 r->Start();
[email protected]79e1fd62013-06-20 06:50:044430
shivanisha8061c4202017-06-13 23:35:524431 base::RunLoop().Run();
4432
[email protected]79e1fd62013-06-20 06:50:044433 {
4434 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194435 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524436 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044437 }
4438
maksim.sisovb53724b52016-09-16 05:30:504439 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194440 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364441 EXPECT_TRUE(d.auth_required_called());
4442 EXPECT_EQ(1, network_delegate.created_requests());
4443 EXPECT_EQ(0, network_delegate.destroyed_requests());
4444 }
4445 EXPECT_EQ(1, network_delegate.destroyed_requests());
4446}
4447
4448// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404449// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364450TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554451 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364452
4453 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304454 BlockingNetworkDelegate network_delegate(
4455 BlockingNetworkDelegate::SYNCHRONOUS);
4456 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364457 network_delegate.set_auth_retval(
4458 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4459
[email protected]f3cf9802011-10-28 18:44:584460 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364461
[email protected]ef2bf422012-05-11 03:27:094462 TestURLRequestContext context(true);
4463 context.set_network_delegate(&network_delegate);
4464 context.Init();
[email protected]c2911d72011-10-03 22:16:364465
4466 {
tommycli59a63432015-11-06 00:10:554467 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164468 std::unique_ptr<URLRequest> r(context.CreateRequest(
4469 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194470 r->Start();
[email protected]255620da2013-08-19 13:14:294471 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364472
maksim.sisovb53724b52016-09-16 05:30:504473 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194474 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364475 EXPECT_FALSE(d.auth_required_called());
4476 EXPECT_EQ(1, network_delegate.created_requests());
4477 EXPECT_EQ(0, network_delegate.destroyed_requests());
4478 }
4479 EXPECT_EQ(1, network_delegate.destroyed_requests());
4480}
4481
[email protected]79e1fd62013-06-20 06:50:044482// Same as above, but also tests that GetFullRequestHeaders returns the proper
4483// headers (for the first or second request) when called at the proper times.
4484TEST_F(URLRequestTestHTTP,
4485 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554486 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044487
4488 TestDelegate d;
4489 BlockingNetworkDelegate network_delegate(
4490 BlockingNetworkDelegate::SYNCHRONOUS);
4491 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4492 network_delegate.set_auth_retval(
4493 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4494
4495 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4496
4497 TestURLRequestContext context(true);
4498 context.set_network_delegate(&network_delegate);
4499 context.Init();
4500
4501 {
tommycli59a63432015-11-06 00:10:554502 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164503 std::unique_ptr<URLRequest> r(context.CreateRequest(
4504 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194505 r->Start();
[email protected]255620da2013-08-19 13:14:294506 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044507
maksim.sisovb53724b52016-09-16 05:30:504508 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194509 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044510 EXPECT_FALSE(d.auth_required_called());
4511 EXPECT_EQ(1, network_delegate.created_requests());
4512 EXPECT_EQ(0, network_delegate.destroyed_requests());
4513
4514 {
4515 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194516 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044517 EXPECT_TRUE(headers.HasHeader("Authorization"));
4518 }
4519 }
4520 EXPECT_EQ(1, network_delegate.destroyed_requests());
4521}
4522
[email protected]c2911d72011-10-03 22:16:364523// Tests that the network delegate can synchronously complete OnAuthRequired
4524// by cancelling authentication.
4525TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554526 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364527
4528 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304529 BlockingNetworkDelegate network_delegate(
4530 BlockingNetworkDelegate::SYNCHRONOUS);
4531 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364532 network_delegate.set_auth_retval(
4533 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4534
[email protected]ef2bf422012-05-11 03:27:094535 TestURLRequestContext context(true);
4536 context.set_network_delegate(&network_delegate);
4537 context.Init();
[email protected]c2911d72011-10-03 22:16:364538
4539 {
tommycli59a63432015-11-06 00:10:554540 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164541 std::unique_ptr<URLRequest> r(context.CreateRequest(
4542 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194543 r->Start();
[email protected]255620da2013-08-19 13:14:294544 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364545
maksim.sisovb53724b52016-09-16 05:30:504546 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194547 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364548 EXPECT_FALSE(d.auth_required_called());
4549 EXPECT_EQ(1, network_delegate.created_requests());
4550 EXPECT_EQ(0, network_delegate.destroyed_requests());
4551 }
4552 EXPECT_EQ(1, network_delegate.destroyed_requests());
4553}
4554
4555// Tests that the network delegate can asynchronously complete OnAuthRequired
4556// by taking no action. This indicates that the NetworkDelegate does not want
4557// to handle the challenge, and is passing the buck along to the
4558// URLRequest::Delegate.
4559TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554560 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364561
4562 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304563 BlockingNetworkDelegate network_delegate(
4564 BlockingNetworkDelegate::AUTO_CALLBACK);
4565 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364566
[email protected]ef2bf422012-05-11 03:27:094567 TestURLRequestContext context(true);
4568 context.set_network_delegate(&network_delegate);
4569 context.Init();
[email protected]c2911d72011-10-03 22:16:364570
[email protected]f3cf9802011-10-28 18:44:584571 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364572
4573 {
tommycli59a63432015-11-06 00:10:554574 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164575 std::unique_ptr<URLRequest> r(context.CreateRequest(
4576 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194577 r->Start();
[email protected]255620da2013-08-19 13:14:294578 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364579
maksim.sisovb53724b52016-09-16 05:30:504580 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194581 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364582 EXPECT_TRUE(d.auth_required_called());
4583 EXPECT_EQ(1, network_delegate.created_requests());
4584 EXPECT_EQ(0, network_delegate.destroyed_requests());
4585 }
4586 EXPECT_EQ(1, network_delegate.destroyed_requests());
4587}
4588
4589// Tests that the network delegate can asynchronously complete OnAuthRequired
4590// by setting credentials.
4591TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554592 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364593
4594 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304595 BlockingNetworkDelegate network_delegate(
4596 BlockingNetworkDelegate::AUTO_CALLBACK);
4597 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364598 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364599 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4600
[email protected]f3cf9802011-10-28 18:44:584601 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364602 network_delegate.set_auth_credentials(auth_credentials);
4603
[email protected]ef2bf422012-05-11 03:27:094604 TestURLRequestContext context(true);
4605 context.set_network_delegate(&network_delegate);
4606 context.Init();
[email protected]c2911d72011-10-03 22:16:364607
4608 {
tommycli59a63432015-11-06 00:10:554609 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164610 std::unique_ptr<URLRequest> r(context.CreateRequest(
4611 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194612 r->Start();
[email protected]255620da2013-08-19 13:14:294613 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364614
maksim.sisovb53724b52016-09-16 05:30:504615 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194616 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364617 EXPECT_FALSE(d.auth_required_called());
4618 EXPECT_EQ(1, network_delegate.created_requests());
4619 EXPECT_EQ(0, network_delegate.destroyed_requests());
4620 }
4621 EXPECT_EQ(1, network_delegate.destroyed_requests());
4622}
4623
4624// Tests that the network delegate can asynchronously complete OnAuthRequired
4625// by cancelling authentication.
4626TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554627 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364628
4629 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304630 BlockingNetworkDelegate network_delegate(
4631 BlockingNetworkDelegate::AUTO_CALLBACK);
4632 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364633 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364634 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4635
[email protected]ef2bf422012-05-11 03:27:094636 TestURLRequestContext context(true);
4637 context.set_network_delegate(&network_delegate);
4638 context.Init();
[email protected]c2911d72011-10-03 22:16:364639
4640 {
tommycli59a63432015-11-06 00:10:554641 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164642 std::unique_ptr<URLRequest> r(context.CreateRequest(
4643 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194644 r->Start();
[email protected]255620da2013-08-19 13:14:294645 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364646
maksim.sisovb53724b52016-09-16 05:30:504647 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194648 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364649 EXPECT_FALSE(d.auth_required_called());
4650 EXPECT_EQ(1, network_delegate.created_requests());
4651 EXPECT_EQ(0, network_delegate.destroyed_requests());
4652 }
4653 EXPECT_EQ(1, network_delegate.destroyed_requests());
4654}
4655
[email protected]9045b8822012-01-13 20:35:354656// Tests that we can handle when a network request was canceled while we were
4657// waiting for the network delegate.
4658// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4659TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554660 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354661
4662 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304663 BlockingNetworkDelegate network_delegate(
4664 BlockingNetworkDelegate::USER_CALLBACK);
4665 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354666
[email protected]ef2bf422012-05-11 03:27:094667 TestURLRequestContext context(true);
4668 context.set_network_delegate(&network_delegate);
4669 context.Init();
[email protected]9045b8822012-01-13 20:35:354670
4671 {
rhalavatib7bd7c792017-04-27 05:25:164672 std::unique_ptr<URLRequest> r(
4673 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4674 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354675
[email protected]f7022f32014-08-21 16:32:194676 r->Start();
[email protected]255620da2013-08-19 13:14:294677 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304678 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4679 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354680 EXPECT_EQ(0, network_delegate.completed_requests());
4681 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194682 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354683 // Ensure that network delegate is notified.
4684 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504685 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354686 EXPECT_EQ(1, network_delegate.created_requests());
4687 EXPECT_EQ(0, network_delegate.destroyed_requests());
4688 }
4689 EXPECT_EQ(1, network_delegate.destroyed_requests());
4690}
4691
4692// Tests that we can handle when a network request was canceled while we were
4693// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:004694// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
4695// callback.
[email protected]9045b8822012-01-13 20:35:354696TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554697 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354698
4699 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304700 BlockingNetworkDelegate network_delegate(
4701 BlockingNetworkDelegate::USER_CALLBACK);
4702 network_delegate.set_block_on(
4703 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354704
[email protected]ef2bf422012-05-11 03:27:094705 TestURLRequestContext context(true);
4706 context.set_network_delegate(&network_delegate);
4707 context.Init();
[email protected]9045b8822012-01-13 20:35:354708
4709 {
rhalavatib7bd7c792017-04-27 05:25:164710 std::unique_ptr<URLRequest> r(
4711 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4712 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354713
[email protected]f7022f32014-08-21 16:32:194714 r->Start();
[email protected]255620da2013-08-19 13:14:294715 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304716 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4717 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354718 EXPECT_EQ(0, network_delegate.completed_requests());
4719 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194720 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354721 // Ensure that network delegate is notified.
4722 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504723 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354724 EXPECT_EQ(1, network_delegate.created_requests());
4725 EXPECT_EQ(0, network_delegate.destroyed_requests());
4726 }
4727 EXPECT_EQ(1, network_delegate.destroyed_requests());
4728}
4729
4730// Tests that we can handle when a network request was canceled while we were
4731// waiting for the network delegate.
4732// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4733TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554734 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354735
4736 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304737 BlockingNetworkDelegate network_delegate(
4738 BlockingNetworkDelegate::USER_CALLBACK);
4739 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354740
[email protected]ef2bf422012-05-11 03:27:094741 TestURLRequestContext context(true);
4742 context.set_network_delegate(&network_delegate);
4743 context.Init();
[email protected]9045b8822012-01-13 20:35:354744
4745 {
rhalavatib7bd7c792017-04-27 05:25:164746 std::unique_ptr<URLRequest> r(
4747 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4748 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354749
[email protected]f7022f32014-08-21 16:32:194750 r->Start();
[email protected]255620da2013-08-19 13:14:294751 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304752 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4753 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354754 EXPECT_EQ(0, network_delegate.completed_requests());
4755 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194756 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354757 // Ensure that network delegate is notified.
4758 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504759 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354760 EXPECT_EQ(1, network_delegate.created_requests());
4761 EXPECT_EQ(0, network_delegate.destroyed_requests());
4762 }
4763 EXPECT_EQ(1, network_delegate.destroyed_requests());
4764}
4765
4766// Tests that we can handle when a network request was canceled while we were
4767// waiting for the network delegate.
4768// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024769TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554770 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354771
4772 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304773 BlockingNetworkDelegate network_delegate(
4774 BlockingNetworkDelegate::USER_CALLBACK);
4775 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354776
[email protected]ef2bf422012-05-11 03:27:094777 TestURLRequestContext context(true);
4778 context.set_network_delegate(&network_delegate);
4779 context.Init();
[email protected]9045b8822012-01-13 20:35:354780
4781 {
danakj8522a25b2016-04-16 00:17:364782 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164783 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
4784 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354785
[email protected]f7022f32014-08-21 16:32:194786 r->Start();
[email protected]255620da2013-08-19 13:14:294787 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304788 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4789 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354790 EXPECT_EQ(0, network_delegate.completed_requests());
4791 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194792 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354793 // Ensure that network delegate is notified.
4794 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504795 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354796 EXPECT_EQ(1, network_delegate.created_requests());
4797 EXPECT_EQ(0, network_delegate.destroyed_requests());
4798 }
4799 EXPECT_EQ(1, network_delegate.destroyed_requests());
4800}
4801
tommycli59a63432015-11-06 00:10:554802namespace {
4803
danakj8522a25b2016-04-16 00:17:364804std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:554805 const test_server::HttpRequest& request) {
4806 if (request.headers.find("Host") == request.headers.end() ||
4807 request.headers.at("Host") != "www.server-auth.com" ||
4808 request.method != test_server::METHOD_CONNECT) {
4809 return nullptr;
4810 }
4811
danakj8522a25b2016-04-16 00:17:364812 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554813 new test_server::BasicHttpResponse);
4814 http_response->set_code(HTTP_UNAUTHORIZED);
4815 http_response->AddCustomHeader("WWW-Authenticate",
4816 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484817 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554818}
4819
4820} // namespace
4821
4822// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114823// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554824// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354825TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554826 http_test_server()->RegisterRequestHandler(
4827 base::Bind(&HandleServerAuthConnect));
4828 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114829
[email protected]ceefd7fd2012-11-29 00:36:244830 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044831 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554832 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504833
[email protected]dc651782009-02-14 01:45:084834 TestDelegate d;
4835 {
danakj8522a25b2016-04-16 00:17:364836 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164837 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
4838 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:084839
[email protected]f7022f32014-08-21 16:32:194840 r->Start();
4841 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084842
[email protected]255620da2013-08-19 13:14:294843 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084844
[email protected]d8fc4722014-06-13 13:17:154845 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474846 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504847 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084848 }
4849}
4850
[email protected]b89290212009-08-14 22:37:354851TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554852 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114853
initial.commit586acc5fe2008-07-26 22:42:524854 TestDelegate d;
4855 {
danakj8522a25b2016-04-16 00:17:364856 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164857 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4858 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:524859
[email protected]f7022f32014-08-21 16:32:194860 r->Start();
4861 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524862
[email protected]255620da2013-08-19 13:14:294863 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524864
4865 EXPECT_EQ(1, d.response_started_count());
4866 EXPECT_FALSE(d.received_data_before_response());
4867 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554868 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194869 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554870 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194871 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164872
[email protected]9e743cd2010-03-16 07:03:534873 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524874 }
initial.commit586acc5fe2008-07-26 22:42:524875}
4876
[email protected]263163f2012-06-14 22:40:344877// This test has the server send a large number of cookies to the client.
4878// To ensure that no number of cookies causes a crash, a galloping binary
4879// search is used to estimate that maximum number of cookies that are accepted
4880// by the browser. Beyond the maximum number, the request will fail with
4881// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304882#if defined(OS_WIN)
4883// http://crbug.com/177916
4884#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4885#else
4886#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4887#endif // defined(OS_WIN)
4888TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554889 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344890
4891 int lower_bound = 0;
4892 int upper_bound = 1;
4893
4894 // Double the number of cookies until the response header limits are
4895 // exceeded.
4896 while (DoManyCookiesRequest(upper_bound)) {
4897 lower_bound = upper_bound;
4898 upper_bound *= 2;
4899 ASSERT_LT(upper_bound, 1000000);
4900 }
4901
pkasting6b68a162014-12-01 22:10:294902 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344903 if (tolerance < 2)
4904 tolerance = 2;
4905
4906 // Perform a binary search to find the highest possible number of cookies,
4907 // within the desired tolerance.
4908 while (upper_bound - lower_bound >= tolerance) {
4909 int num_cookies = (lower_bound + upper_bound) / 2;
4910
4911 if (DoManyCookiesRequest(num_cookies))
4912 lower_bound = num_cookies;
4913 else
4914 upper_bound = num_cookies;
4915 }
4916 // Success: the test did not crash.
4917}
4918
[email protected]b89290212009-08-14 22:37:354919TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554920 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114921
initial.commit586acc5fe2008-07-26 22:42:524922 TestDelegate d;
4923 {
danakj8522a25b2016-04-16 00:17:364924 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164925 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4926 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:524927
[email protected]f7022f32014-08-21 16:32:194928 r->Start();
4929 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524930
[email protected]255620da2013-08-19 13:14:294931 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524932
4933 EXPECT_EQ(1, d.response_started_count());
4934 EXPECT_FALSE(d.received_data_before_response());
4935 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554936 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194937 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554938 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194939 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524940 }
[email protected]5d7b373e2009-09-02 07:19:034941}
4942
[email protected]79e1fd62013-06-20 06:50:044943TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554944 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044945
4946 TestDelegate d;
4947 {
tommycli59a63432015-11-06 00:10:554948 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164949 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
4950 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:044951
4952 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194953 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044954
[email protected]f7022f32014-08-21 16:32:194955 r->Start();
4956 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044957
[email protected]255620da2013-08-19 13:14:294958 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044959
4960 EXPECT_EQ(1, d.response_started_count());
4961 EXPECT_FALSE(d.received_data_before_response());
4962 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554963 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194964 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554965 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194966 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044967
4968 EXPECT_TRUE(d.have_full_request_headers());
4969 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4970 }
4971}
4972
[email protected]58e32bb2013-01-21 18:23:254973TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554974 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254975
4976 TestDelegate d;
4977 {
danakj8522a25b2016-04-16 00:17:364978 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164979 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4980 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:254981
[email protected]f7022f32014-08-21 16:32:194982 r->Start();
4983 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254984
[email protected]255620da2013-08-19 13:14:294985 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254986
4987 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194988 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254989 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4990
4991 EXPECT_EQ(1, d.response_started_count());
4992 EXPECT_FALSE(d.received_data_before_response());
4993 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554994 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194995 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554996 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194997 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254998 }
4999}
5000
tommycli59a63432015-11-06 00:10:555001// TODO(svaldez): Update tests to use EmbeddedTestServer.
5002#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395003TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555004 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555005 base::FilePath(kTestFilePath));
5006
5007 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395008
5009 // Parameter that specifies the Content-Length field in the response:
5010 // C - Compressed length.
5011 // U - Uncompressed length.
5012 // L - Large length (larger than both C & U).
5013 // M - Medium length (between C & U).
5014 // S - Small length (smaller than both C & U).
5015 const char test_parameters[] = "CULMS";
5016 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
5017 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445018 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395019 // S has too little data, but we seem to accept it.
5020 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375021 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395022
xunjielifb4da222016-07-14 18:38:595023 base::FilePath file_path;
5024 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
5025 file_path = file_path.Append(kTestFilePath);
5026 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5027 std::string expected_content;
5028 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5029
5030 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395031 TestDelegate d;
5032 {
tommycli59a63432015-11-06 00:10:555033 std::string test_file = base::StringPrintf(
5034 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395035
[email protected]ceefd7fd2012-11-29 00:36:245036 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095037 TestURLRequestContext context(true);
5038 context.set_network_delegate(&network_delegate);
5039 context.Init();
[email protected]87a09a92011-07-14 15:50:505040
rhalavatib7bd7c792017-04-27 05:25:165041 std::unique_ptr<URLRequest> r(
5042 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5043 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195044 r->Start();
5045 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395046
[email protected]255620da2013-08-19 13:14:295047 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:395048
5049 EXPECT_EQ(1, d.response_started_count());
5050 EXPECT_FALSE(d.received_data_before_response());
5051 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505052 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395053 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505054 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5055 << "\"";
xunjielifb4da222016-07-14 18:38:595056 if (test_parameters[i] == 'S') {
5057 // When content length is smaller than both compressed length and
5058 // uncompressed length, HttpStreamParser might not read the full
5059 // response body.
5060 continue;
5061 }
5062 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395063 } else {
maksim.sisovb53724b52016-09-16 05:30:505064 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395065 << " Parameter = \"" << test_file << "\"";
5066 }
5067 }
5068 }
5069}
tommycli59a63432015-11-06 00:10:555070#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395071
[email protected]58e32bb2013-01-21 18:23:255072TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555073 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255074
tommycli59a63432015-11-06 00:10:555075 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455076 GURL original_url =
tommycli59a63432015-11-06 00:10:555077 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255078 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165079 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5080 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195081 req->Start();
[email protected]255620da2013-08-19 13:14:295082 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255083
5084 EXPECT_EQ(1, d.response_started_count());
5085 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195086 EXPECT_EQ(destination_url, req->url());
5087 EXPECT_EQ(original_url, req->original_url());
5088 ASSERT_EQ(2U, req->url_chain().size());
5089 EXPECT_EQ(original_url, req->url_chain()[0]);
5090 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255091
5092 LoadTimingInfo load_timing_info_before_redirect;
5093 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5094 &load_timing_info_before_redirect));
5095 TestLoadTimingNotReused(load_timing_info_before_redirect,
5096 CONNECT_TIMING_HAS_DNS_TIMES);
5097
5098 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195099 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255100 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5101
5102 // Check that a new socket was used on redirect, since the server does not
5103 // supposed keep-alive sockets, and that the times before the redirect are
5104 // before the ones recorded for the second request.
5105 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5106 load_timing_info.socket_log_id);
5107 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5108 load_timing_info.connect_timing.connect_start);
5109}
5110
[email protected]8f1ac082011-04-19 21:14:135111TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555112 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135113
tommycli59a63432015-11-06 00:10:555114 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455115 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555116 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5117 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5118 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135119 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165120 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5121 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195122 req->Start();
[email protected]255620da2013-08-19 13:14:295123 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:135124
5125 EXPECT_EQ(1, d.response_started_count());
5126 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195127 EXPECT_EQ(destination_url, req->url());
5128 EXPECT_EQ(original_url, req->original_url());
5129 ASSERT_EQ(3U, req->url_chain().size());
5130 EXPECT_EQ(original_url, req->url_chain()[0]);
5131 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5132 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135133}
5134
[email protected]abe1c4a2013-10-25 19:28:515135// First and second pieces of information logged by delegates to URLRequests.
5136const char kFirstDelegateInfo[] = "Wonderful delegate";
5137const char kSecondDelegateInfo[] = "Exciting delegate";
5138
5139// Logs delegate information to a URLRequest. The first string is logged
5140// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5141// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5142// another asynchronous call is used to clear the delegate information
5143// before calling a callback. The object then deletes itself.
5144class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5145 public:
5146 typedef base::Callback<void()> Callback;
5147
5148 // Each time delegate information is added to the URLRequest, the resulting
5149 // load state is checked. The expected load state after each request is
5150 // passed in as an argument.
5151 static void Run(URLRequest* url_request,
5152 LoadState expected_first_load_state,
5153 LoadState expected_second_load_state,
5154 LoadState expected_third_load_state,
5155 const Callback& callback) {
5156 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
5157 url_request,
5158 expected_first_load_state,
5159 expected_second_load_state,
5160 expected_third_load_state,
5161 callback);
5162 logger->Start();
5163 }
5164
5165 // Checks that the log entries, starting with log_position, contain the
5166 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5167 // recorded. Returns the index of entry after the expected number of
5168 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465169 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515170 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515171 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5172 if (log_position + 3 >= entries.size()) {
5173 ADD_FAILURE() << "Not enough log entries";
5174 return entries.size();
5175 }
5176 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005177 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5178 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075179 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515180 &delegate_info));
5181 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5182
5183 ++log_position;
mikecirone8b85c432016-09-08 19:11:005184 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5185 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515186
5187 ++log_position;
mikecirone8b85c432016-09-08 19:11:005188 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5189 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075190 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515191 &delegate_info));
5192 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5193
5194 ++log_position;
mikecirone8b85c432016-09-08 19:11:005195 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5196 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515197
5198 return log_position + 1;
5199 }
5200
5201 private:
5202 friend class base::RefCounted<AsyncDelegateLogger>;
5203
5204 AsyncDelegateLogger(URLRequest* url_request,
5205 LoadState expected_first_load_state,
5206 LoadState expected_second_load_state,
5207 LoadState expected_third_load_state,
5208 const Callback& callback)
5209 : url_request_(url_request),
5210 expected_first_load_state_(expected_first_load_state),
5211 expected_second_load_state_(expected_second_load_state),
5212 expected_third_load_state_(expected_third_load_state),
5213 callback_(callback) {
5214 }
5215
5216 ~AsyncDelegateLogger() {}
5217
5218 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535219 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515220 LoadStateWithParam load_state = url_request_->GetLoadState();
5221 EXPECT_EQ(expected_first_load_state_, load_state.state);
5222 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455223 base::ThreadTaskRunnerHandle::Get()->PostTask(
5224 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515225 }
5226
5227 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535228 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515229 LoadStateWithParam load_state = url_request_->GetLoadState();
5230 EXPECT_EQ(expected_second_load_state_, load_state.state);
5231 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5232 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5233 } else {
5234 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5235 }
skyostil4891b25b2015-06-11 11:43:455236 base::ThreadTaskRunnerHandle::Get()->PostTask(
5237 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515238 }
5239
5240 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535241 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515242 LoadStateWithParam load_state = url_request_->GetLoadState();
5243 EXPECT_EQ(expected_third_load_state_, load_state.state);
5244 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085245 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515246 callback_.Run();
5247 }
5248
5249 URLRequest* url_request_;
5250 const int expected_first_load_state_;
5251 const int expected_second_load_state_;
5252 const int expected_third_load_state_;
5253 const Callback callback_;
5254
5255 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5256};
5257
5258// NetworkDelegate that logs delegate information before a request is started,
5259// before headers are sent, when headers are read, and when auth information
5260// is requested. Uses AsyncDelegateLogger.
5261class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5262 public:
5263 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:205264 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:515265
5266 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205267 int OnBeforeURLRequest(URLRequest* request,
5268 const CompletionCallback& callback,
5269 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:515270 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
5271 return RunCallbackAsynchronously(request, callback);
5272 }
5273
ryansturm2343cb62016-06-15 01:09:005274 int OnBeforeStartTransaction(URLRequest* request,
5275 const CompletionCallback& callback,
5276 HttpRequestHeaders* headers) override {
5277 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]abe1c4a2013-10-25 19:28:515278 return RunCallbackAsynchronously(request, callback);
5279 }
5280
dchengb03027d2014-10-21 12:00:205281 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515282 URLRequest* request,
5283 const CompletionCallback& callback,
5284 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165285 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135286 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:165287 TestNetworkDelegate::OnHeadersReceived(request,
5288 callback,
[email protected]abe1c4a2013-10-25 19:28:515289 original_response_headers,
[email protected]5f714132014-03-26 10:41:165290 override_response_headers,
5291 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:515292 return RunCallbackAsynchronously(request, callback);
5293 }
5294
dchengb03027d2014-10-21 12:00:205295 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515296 URLRequest* request,
5297 const AuthChallengeInfo& auth_info,
5298 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:135299 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515300 AsyncDelegateLogger::Run(
5301 request,
5302 LOAD_STATE_WAITING_FOR_DELEGATE,
5303 LOAD_STATE_WAITING_FOR_DELEGATE,
5304 LOAD_STATE_WAITING_FOR_DELEGATE,
5305 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5306 callback, credentials));
5307 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5308 }
5309
5310 private:
5311 static int RunCallbackAsynchronously(
5312 URLRequest* request,
5313 const CompletionCallback& callback) {
5314 AsyncDelegateLogger::Run(
5315 request,
5316 LOAD_STATE_WAITING_FOR_DELEGATE,
5317 LOAD_STATE_WAITING_FOR_DELEGATE,
5318 LOAD_STATE_WAITING_FOR_DELEGATE,
5319 base::Bind(callback, OK));
5320 return ERR_IO_PENDING;
5321 }
5322
5323 static void SetAuthAndResume(const AuthCallback& callback,
5324 AuthCredentials* credentials) {
5325 *credentials = AuthCredentials(kUser, kSecret);
5326 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5327 }
5328
5329 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5330};
5331
5332// URLRequest::Delegate that logs delegate information when the headers
5333// are received, when each read completes, and during redirects. Uses
5334// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5335//
5336// Inherits from TestDelegate to reuse the TestDelegate code to handle
5337// advancing to the next step in most cases, as well as cancellation.
5338class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5339 public:
5340 enum CancelStage {
5341 NO_CANCEL = 0,
5342 CANCEL_ON_RECEIVED_REDIRECT,
5343 CANCEL_ON_RESPONSE_STARTED,
5344 CANCEL_ON_READ_COMPLETED
5345 };
5346
5347 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5348 : cancel_stage_(cancel_stage) {
5349 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5350 set_cancel_in_received_redirect(true);
5351 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5352 set_cancel_in_response_started(true);
5353 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5354 set_cancel_in_received_data(true);
5355 }
dchengb03027d2014-10-21 12:00:205356 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:515357
5358 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205359 void OnReceivedRedirect(URLRequest* request,
5360 const RedirectInfo& redirect_info,
5361 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515362 *defer_redirect = true;
5363 AsyncDelegateLogger::Run(
5364 request,
5365 LOAD_STATE_WAITING_FOR_DELEGATE,
5366 LOAD_STATE_WAITING_FOR_DELEGATE,
5367 LOAD_STATE_WAITING_FOR_DELEGATE,
5368 base::Bind(
5369 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595370 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515371 }
5372
maksim.sisov0f4aa142016-09-05 05:55:285373 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515374 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285375 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5376 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5377 base::Bind(
5378 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5379 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515380 }
5381
dchengb03027d2014-10-21 12:00:205382 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515383 AsyncDelegateLogger::Run(
5384 request,
5385 LOAD_STATE_IDLE,
5386 LOAD_STATE_IDLE,
5387 LOAD_STATE_IDLE,
5388 base::Bind(
5389 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5390 base::Unretained(this), request, bytes_read));
5391 }
5392
5393 private:
5394 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595395 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515396 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595397 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515398 // FollowDeferredRedirect should not be called after cancellation.
5399 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5400 return;
5401 if (!defer_redirect)
5402 request->FollowDeferredRedirect();
5403 }
5404
maksim.sisov0f4aa142016-09-05 05:55:285405 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515406 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285407 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515408 }
5409
5410 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5411 // The parent class continues the request.
5412 TestDelegate::OnReadCompleted(request, bytes_read);
5413 }
5414
5415 const CancelStage cancel_stage_;
5416
5417 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5418};
5419
5420// Tests handling of delegate info before a request starts.
5421TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555422 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515423
5424 TestDelegate request_delegate;
5425 TestURLRequestContext context(true);
5426 context.set_network_delegate(NULL);
5427 context.set_net_log(&net_log_);
5428 context.Init();
5429
5430 {
rhalavatib7bd7c792017-04-27 05:25:165431 std::unique_ptr<URLRequest> r(context.CreateRequest(
5432 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5433 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195434 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515435 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085436 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515437
5438 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195439 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515440 LOAD_STATE_WAITING_FOR_DELEGATE,
5441 LOAD_STATE_WAITING_FOR_DELEGATE,
5442 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195443 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515444
5445 base::RunLoop().Run();
5446
[email protected]f7022f32014-08-21 16:32:195447 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505448 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515449 }
5450
mmenke43758e62015-05-04 21:09:465451 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515452 net_log_.GetEntries(&entries);
5453 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005454 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515455
5456 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5457
5458 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005459 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5460 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515461}
5462
5463// Tests handling of delegate info from a network delegate.
5464TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555465 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515466
5467 TestDelegate request_delegate;
5468 AsyncLoggingNetworkDelegate network_delegate;
5469 TestURLRequestContext context(true);
5470 context.set_network_delegate(&network_delegate);
5471 context.set_net_log(&net_log_);
5472 context.Init();
5473
5474 {
rhalavatib7bd7c792017-04-27 05:25:165475 std::unique_ptr<URLRequest> r(context.CreateRequest(
5476 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
5477 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195478 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515479 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085480 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515481
[email protected]f7022f32014-08-21 16:32:195482 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515483 base::RunLoop().Run();
5484
[email protected]f7022f32014-08-21 16:32:195485 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505486 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515487 EXPECT_EQ(1, network_delegate.created_requests());
5488 EXPECT_EQ(0, network_delegate.destroyed_requests());
5489 }
5490 EXPECT_EQ(1, network_delegate.destroyed_requests());
5491
5492 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465493 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515494 net_log_.GetEntries(&entries);
5495 for (size_t i = 0; i < 3; ++i) {
5496 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005497 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5498 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515499
5500 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5501 log_position + 1);
5502
5503 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005504 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5505 entries[log_position].type);
5506 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515507 }
5508
mikecirone8b85c432016-09-08 19:11:005509 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5510 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515511}
5512
5513// Tests handling of delegate info from a network delegate in the case of an
5514// HTTP redirect.
5515TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555516 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515517
5518 TestDelegate request_delegate;
5519 AsyncLoggingNetworkDelegate network_delegate;
5520 TestURLRequestContext context(true);
5521 context.set_network_delegate(&network_delegate);
5522 context.set_net_log(&net_log_);
5523 context.Init();
5524
5525 {
danakj8522a25b2016-04-16 00:17:365526 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555527 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165528 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195529 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515530 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085531 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515532
[email protected]f7022f32014-08-21 16:32:195533 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515534 base::RunLoop().Run();
5535
[email protected]f7022f32014-08-21 16:32:195536 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505537 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515538 EXPECT_EQ(2, network_delegate.created_requests());
5539 EXPECT_EQ(0, network_delegate.destroyed_requests());
5540 }
5541 EXPECT_EQ(1, network_delegate.destroyed_requests());
5542
5543 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465544 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515545 net_log_.GetEntries(&entries);
5546 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005547 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:515548 for (size_t i = 0; i < 3; ++i) {
5549 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005550 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5551 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515552
5553 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5554 log_position + 1);
5555
5556 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005557 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5558 entries[log_position].type);
5559 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515560 }
5561
5562 // The URLRequest::Delegate then gets informed about the redirect.
5563 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005564 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5565 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515566
5567 // The NetworkDelegate logged information in the same three events as before.
5568 for (size_t i = 0; i < 3; ++i) {
5569 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005570 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5571 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515572
5573 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5574 log_position + 1);
5575
5576 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005577 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5578 entries[log_position].type);
5579 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515580 }
5581
mikecirone8b85c432016-09-08 19:11:005582 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5583 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515584}
5585
5586// Tests handling of delegate info from a network delegate in the case of HTTP
5587// AUTH.
5588TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555589 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515590
5591 TestDelegate request_delegate;
5592 AsyncLoggingNetworkDelegate network_delegate;
5593 TestURLRequestContext context(true);
5594 context.set_network_delegate(&network_delegate);
5595 context.set_net_log(&net_log_);
5596 context.Init();
5597
5598 {
rhalavatib7bd7c792017-04-27 05:25:165599 std::unique_ptr<URLRequest> r(context.CreateRequest(
5600 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
5601 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195602 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515603 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085604 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515605
[email protected]f7022f32014-08-21 16:32:195606 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515607 base::RunLoop().Run();
5608
[email protected]f7022f32014-08-21 16:32:195609 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505610 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515611 EXPECT_EQ(1, network_delegate.created_requests());
5612 EXPECT_EQ(0, network_delegate.destroyed_requests());
5613 }
5614 EXPECT_EQ(1, network_delegate.destroyed_requests());
5615
5616 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465617 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515618 net_log_.GetEntries(&entries);
5619 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005620 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
5621 // in
5622 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:515623 for (size_t i = 0; i < 6; ++i) {
5624 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005625 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5626 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515627
5628 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5629 log_position + 1);
5630
5631 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005632 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5633 entries[log_position].type);
5634 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515635 }
5636
mikecirone8b85c432016-09-08 19:11:005637 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5638 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515639}
5640
tommycli59a63432015-11-06 00:10:555641// TODO(svaldez): Update tests to use EmbeddedTestServer.
5642#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515643// Tests handling of delegate info from a URLRequest::Delegate.
5644TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555645 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555646 base::FilePath(kTestFilePath));
5647
5648 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515649
5650 AsyncLoggingUrlRequestDelegate request_delegate(
5651 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5652 TestURLRequestContext context(true);
5653 context.set_network_delegate(NULL);
5654 context.set_net_log(&net_log_);
5655 context.Init();
5656
5657 {
5658 // A chunked response with delays between chunks is used to make sure that
5659 // attempts by the URLRequest delegate to log information while reading the
5660 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485661 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515662 // that it occurs.
danakj8522a25b2016-04-16 00:17:365663 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555664 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:165665 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195666 LoadStateWithParam load_state = r->GetLoadState();
5667 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515668 base::RunLoop().Run();
5669
[email protected]f7022f32014-08-21 16:32:195670 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505671 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515672 }
5673
mmenke43758e62015-05-04 21:09:465674 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515675 net_log_.GetEntries(&entries);
5676
[email protected]1826a402014-01-08 15:40:485677 size_t log_position = 0;
5678
[email protected]abe1c4a2013-10-25 19:28:515679 // The delegate info should only have been logged on header complete. Other
5680 // times it should silently be ignored.
mikecirone8b85c432016-09-08 19:11:005681 log_position = ExpectLogContainsSomewhereAfter(
5682 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5683 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515684
5685 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5686 log_position + 1);
5687
5688 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005689 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE, entries[log_position].type);
5690 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515691
mikecirone8b85c432016-09-08 19:11:005692 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5693 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515694 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005695 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515696}
tommycli59a63432015-11-06 00:10:555697#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515698
5699// Tests handling of delegate info from a URLRequest::Delegate in the case of
5700// an HTTP redirect.
5701TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555702 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515703
5704 AsyncLoggingUrlRequestDelegate request_delegate(
5705 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5706 TestURLRequestContext context(true);
5707 context.set_network_delegate(NULL);
5708 context.set_net_log(&net_log_);
5709 context.Init();
5710
5711 {
danakj8522a25b2016-04-16 00:17:365712 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555713 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165714 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195715 LoadStateWithParam load_state = r->GetLoadState();
5716 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515717 base::RunLoop().Run();
5718
[email protected]f7022f32014-08-21 16:32:195719 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505720 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515721 }
5722
mmenke43758e62015-05-04 21:09:465723 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515724 net_log_.GetEntries(&entries);
5725
5726 // Delegate info should only have been logged in OnReceivedRedirect and
5727 // OnResponseStarted.
5728 size_t log_position = 0;
5729 for (int i = 0; i < 2; ++i) {
5730 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005731 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5732 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515733
5734 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5735 log_position + 1);
5736
5737 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005738 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5739 entries[log_position].type);
5740 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515741 }
5742
mikecirone8b85c432016-09-08 19:11:005743 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5744 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515745 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005746 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515747}
5748
5749// Tests handling of delegate info from a URLRequest::Delegate in the case of
5750// an HTTP redirect, with cancellation at various points.
5751TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555752 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515753
5754 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5755 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5756 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5757 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5758 };
5759
5760 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5761 ++test_case) {
5762 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
vishal.b62985ca92015-04-17 08:45:515763 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:045764 TestURLRequestContext context(true);
[email protected]abe1c4a2013-10-25 19:28:515765 context.set_network_delegate(NULL);
5766 context.set_net_log(&net_log);
5767 context.Init();
5768
5769 {
danakj8522a25b2016-04-16 00:17:365770 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555771 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165772 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195773 LoadStateWithParam load_state = r->GetLoadState();
5774 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515775 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:505776 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515777 }
5778
mmenke43758e62015-05-04 21:09:465779 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515780 net_log.GetEntries(&entries);
5781
5782 // Delegate info is always logged in both OnReceivedRedirect and
5783 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5784 // OnResponseStarted delegate call is after cancellation, but logging is
5785 // still currently supported in that call.
5786 size_t log_position = 0;
5787 for (int i = 0; i < 2; ++i) {
5788 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005789 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5790 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515791
5792 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5793 log_position + 1);
5794
5795 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005796 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5797 entries[log_position].type);
5798 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515799 }
5800
mikecirone8b85c432016-09-08 19:11:005801 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5802 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515803 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005804 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515805 }
5806}
5807
[email protected]847c0fa92012-11-06 16:37:425808namespace {
5809
5810const char kExtraHeader[] = "Allow-Snafu";
5811const char kExtraValue[] = "fubar";
5812
5813class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205814 void OnReceivedRedirect(URLRequest* request,
5815 const RedirectInfo& redirect_info,
5816 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595817 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425818 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5819 }
5820};
5821
5822} // namespace
5823
5824TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555825 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425826
tommycli59a63432015-11-06 00:10:555827 GURL destination_url =
5828 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5829 GURL original_url =
5830 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425831 RedirectWithAdditionalHeadersDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165832 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5833 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195834 req->Start();
[email protected]255620da2013-08-19 13:14:295835 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425836
5837 std::string value;
[email protected]f7022f32014-08-21 16:32:195838 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425839 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5840 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195841 EXPECT_FALSE(req->is_pending());
5842 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425843 EXPECT_EQ(kExtraValue, d.data_received());
5844}
5845
[email protected]251a1b92012-11-13 11:01:095846namespace {
5847
5848const char kExtraHeaderToRemove[] = "To-Be-Removed";
5849
5850class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205851 void OnReceivedRedirect(URLRequest* request,
5852 const RedirectInfo& redirect_info,
5853 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595854 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095855 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5856 }
5857};
5858
5859} // namespace
5860
5861TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555862 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095863
tommycli59a63432015-11-06 00:10:555864 GURL destination_url = http_test_server()->GetURL(
5865 "/echoheader?" + std::string(kExtraHeaderToRemove));
5866 GURL original_url =
5867 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095868 RedirectWithHeaderRemovalDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165869 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5870 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195871 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5872 req->Start();
[email protected]255620da2013-08-19 13:14:295873 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095874
5875 std::string value;
[email protected]f7022f32014-08-21 16:32:195876 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095877 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195878 EXPECT_FALSE(req->is_pending());
5879 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095880 EXPECT_EQ("None", d.data_received());
5881}
5882
mmenke94f1bd92016-12-07 21:13:055883TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:445884 TestDelegate d;
5885 {
danakj8522a25b2016-04-16 00:17:365886 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165887 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
5888 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:445889
[email protected]f7022f32014-08-21 16:32:195890 r->Start();
5891 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445892
[email protected]f7022f32014-08-21 16:32:195893 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445894
[email protected]255620da2013-08-19 13:14:295895 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445896
5897 // We expect to receive OnResponseStarted even though the request has been
5898 // cancelled.
5899 EXPECT_EQ(1, d.response_started_count());
5900 EXPECT_EQ(0, d.bytes_received());
5901 EXPECT_FALSE(d.received_data_before_response());
5902 }
5903}
5904
mmenke94f1bd92016-12-07 21:13:055905TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:555906 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445907
5908 TestDelegate d;
5909 {
danakj8522a25b2016-04-16 00:17:365910 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165911 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
5912 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:445913
5914 d.set_cancel_in_response_started(true);
5915
[email protected]f7022f32014-08-21 16:32:195916 r->Start();
5917 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445918
[email protected]255620da2013-08-19 13:14:295919 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445920
5921 EXPECT_EQ(1, d.response_started_count());
5922 EXPECT_EQ(0, d.bytes_received());
5923 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505924 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445925 }
5926}
5927
mmenke94f1bd92016-12-07 21:13:055928TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:555929 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445930
5931 TestDelegate d;
5932 {
danakj8522a25b2016-04-16 00:17:365933 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165934 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5935 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:055936
5937 d.set_cancel_in_received_data(true);
5938
5939 r->Start();
5940 EXPECT_TRUE(r->is_pending());
5941
5942 base::RunLoop().Run();
5943
5944 EXPECT_EQ(1, d.response_started_count());
5945 EXPECT_NE(0, d.received_bytes_count());
5946 EXPECT_FALSE(d.received_data_before_response());
5947 EXPECT_EQ(ERR_ABORTED, d.request_status());
5948 }
5949}
5950
5951TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
5952 ASSERT_TRUE(http_test_server()->Start());
5953
5954 TestDelegate d;
5955 {
5956 // This returns an empty response (With headers).
5957 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165958 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
5959 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:445960
5961 d.set_cancel_in_received_data(true);
5962
[email protected]f7022f32014-08-21 16:32:195963 r->Start();
5964 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445965
[email protected]255620da2013-08-19 13:14:295966 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445967
5968 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:055969 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:445970 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505971 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445972 }
5973}
5974
mmenke94f1bd92016-12-07 21:13:055975TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:555976 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445977
5978 TestDelegate d;
5979 {
danakj8522a25b2016-04-16 00:17:365980 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165981 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
5982 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:445983
[email protected]f7022f32014-08-21 16:32:195984 r->Start();
5985 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445986
5987 // The request will be implicitly canceled when it is destroyed. The
5988 // test delegate must not post a quit message when this happens because
5989 // this test doesn't actually have a message loop. The quit message would
5990 // get put on this thread's message queue and the next test would exit
5991 // early, causing problems.
5992 d.set_quit_on_complete(false);
5993 }
5994 // expect things to just cleanup properly.
5995
kimwjdalsl2bb4ff02015-12-16 22:06:025996 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:445997 // message loop
5998 EXPECT_FALSE(d.received_data_before_response());
5999 EXPECT_EQ(0, d.bytes_received());
6000}
6001
mmenke94f1bd92016-12-07 21:13:056002TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556003 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446004
6005 // populate cache
6006 {
6007 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366008 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166009 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6010 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196011 r->Start();
[email protected]255620da2013-08-19 13:14:296012 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506013 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446014 }
6015
6016 // cancel read from cache (see bug 990242)
6017 {
6018 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366019 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166020 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6021 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196022 r->Start();
6023 r->Cancel();
[email protected]255620da2013-08-19 13:14:296024 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446025
maksim.sisovb53724b52016-09-16 05:30:506026 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446027 EXPECT_EQ(1, d.response_started_count());
6028 EXPECT_EQ(0, d.bytes_received());
6029 EXPECT_FALSE(d.received_data_before_response());
6030 }
6031}
6032
6033TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556034 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446035 HTTPUploadDataOperationTest("POST");
6036}
6037
6038TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556039 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446040 HTTPUploadDataOperationTest("PUT");
6041}
6042
6043TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556044 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446045
6046 TestDelegate d;
6047 {
danakj8522a25b2016-04-16 00:17:366048 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166049 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6050 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196051 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446052
[email protected]f7022f32014-08-21 16:32:196053 r->Start();
6054 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446055
[email protected]255620da2013-08-19 13:14:296056 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446057
maksim.sisovb53724b52016-09-16 05:30:506058 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6059 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446060
6061 EXPECT_FALSE(d.received_data_before_response());
6062 EXPECT_TRUE(d.data_received().empty());
6063 }
6064}
6065
6066TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556067 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446068
6069 TestDelegate d;
6070 {
danakj8522a25b2016-04-16 00:17:366071 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166072 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6073 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196074 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446075
[email protected]6cdfd7f2013-02-08 20:40:156076 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:446077 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026078 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446079
danakj8522a25b2016-04-16 00:17:366080 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446081
[email protected]6cdfd7f2013-02-08 20:40:156082 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446083 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476084 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446085 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196086 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146087 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076088 std::numeric_limits<uint64_t>::max(), base::Time()));
danakj8522a25b2016-04-16 00:17:366089 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:226090 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:446091
[email protected]f7022f32014-08-21 16:32:196092 r->Start();
6093 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446094
[email protected]255620da2013-08-19 13:14:296095 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446096
avibf0746c2015-12-09 19:53:146097 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296098 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6099 ASSERT_LE(size64, std::numeric_limits<int>::max());
6100 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366101 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446102
[email protected]7600d0b2013-12-08 21:43:306103 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446104
maksim.sisovb53724b52016-09-16 05:30:506105 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6106 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446107
6108 EXPECT_FALSE(d.received_data_before_response());
6109
[email protected]329b68b2012-11-14 17:54:276110 EXPECT_EQ(size, d.bytes_received());
6111 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446112 }
6113}
6114
[email protected]999dd8c2013-11-12 06:45:546115TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556116 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546117
6118 TestDelegate d;
6119 {
danakj8522a25b2016-04-16 00:17:366120 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166121 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6122 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196123 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546124
danakj8522a25b2016-04-16 00:17:366125 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546126
Jeremy Roman0579ed62017-08-29 15:56:196127 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456128 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546129 base::FilePath(FILE_PATH_LITERAL(
6130 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076131 0, std::numeric_limits<uint64_t>::max(), base::Time()));
danakj8522a25b2016-04-16 00:17:366132 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:226133 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:546134
[email protected]f7022f32014-08-21 16:32:196135 r->Start();
6136 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546137
6138 base::RunLoop().Run();
6139
[email protected]999dd8c2013-11-12 06:45:546140 EXPECT_TRUE(d.request_failed());
6141 EXPECT_FALSE(d.received_data_before_response());
6142 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506143 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546144 }
6145}
6146
mmenke56b0cbb912016-03-28 21:34:536147namespace {
6148
6149// Adds a standard set of data to an upload for chunked upload integration
6150// tests.
6151void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6152 writer->AppendData("a", 1, false);
6153 writer->AppendData("bcd", 3, false);
6154 writer->AppendData("this is a longer chunk than before.", 35, false);
6155 writer->AppendData("\r\n\r\n", 4, false);
6156 writer->AppendData("0", 1, false);
6157 writer->AppendData("2323", 4, true);
6158}
6159
6160// Checks that the upload data added in AddChunksToUpload() was echoed back from
6161// the server.
6162void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6163 // This should match the chunks sent by AddChunksToUpload().
6164 const std::string expected_data =
6165 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6166
maksim.sisovb53724b52016-09-16 05:30:506167 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6168 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536169
6170 EXPECT_FALSE(d->received_data_before_response());
6171
6172 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6173 EXPECT_EQ(expected_data, d->data_received());
6174}
6175
6176} // namespace
6177
[email protected]316c1e5e2012-09-12 15:17:446178TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556179 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446180
6181 TestDelegate d;
6182 {
danakj8522a25b2016-04-16 00:17:366183 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166184 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6185 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366186 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536187 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366188 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536189 upload_data_stream->CreateWriter();
6190 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196191 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536192 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196193 r->Start();
6194 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446195
[email protected]255620da2013-08-19 13:14:296196 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446197
[email protected]f7022f32014-08-21 16:32:196198 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446199 }
6200}
6201
[email protected]329b68b2012-11-14 17:54:276202TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556203 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276204
6205 TestDelegate d;
6206 {
danakj8522a25b2016-04-16 00:17:366207 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166208 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6209 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366210 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536211 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366212 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536213 upload_data_stream->CreateWriter();
danakj8522a25b2016-04-16 00:17:366214 r->set_upload(base::WrapUnique(upload_data_stream.release()));
[email protected]f7022f32014-08-21 16:32:196215 r->set_method("POST");
6216 r->Start();
6217 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536218 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:296219 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:276220
[email protected]f7022f32014-08-21 16:32:196221 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276222 }
6223}
6224
[email protected]316c1e5e2012-09-12 15:17:446225TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556226 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446227
6228 TestDelegate d;
6229 {
danakj8522a25b2016-04-16 00:17:366230 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166231 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6232 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366233 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536234 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366235 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536236 upload_data_stream->CreateWriter();
6237 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196238 r->set_method("POST");
6239 r->Start();
6240 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446241
[email protected]255620da2013-08-19 13:14:296242 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:536243 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:296244 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446245
[email protected]f7022f32014-08-21 16:32:196246 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446247 }
6248}
6249
6250TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556251 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446252
6253 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366254 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166255 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6256 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196257 req->Start();
[email protected]255620da2013-08-19 13:14:296258 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446259
[email protected]f7022f32014-08-21 16:32:196260 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446261
6262 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196263 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446264
6265 std::string header;
6266 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6267 EXPECT_EQ("private", header);
6268
6269 header.clear();
6270 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6271 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6272
6273 // The response has two "X-Multiple-Entries" headers.
6274 // This verfies our output has them concatenated together.
6275 header.clear();
6276 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6277 EXPECT_EQ("a, b", header);
6278}
6279
tommycli59a63432015-11-06 00:10:556280// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6281// security state. (see http://crbug.com/550977).
6282#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466283TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556284 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6285 https_test_server.SetSSLConfig(
6286 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6287 https_test_server.ServeFilesFromSourceDirectory(
6288 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466289 ASSERT_TRUE(https_test_server.Start());
6290
tommycli59a63432015-11-06 00:10:556291 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466292 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366293 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166294 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6295 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196296 request->Start();
[email protected]255620da2013-08-19 13:14:296297 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466298
6299 TransportSecurityState* security_state =
6300 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406301 TransportSecurityState::STSState sts_state;
6302 TransportSecurityState::PKPState pkp_state;
6303 EXPECT_TRUE(
6304 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6305 EXPECT_FALSE(
6306 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6307 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6308 sts_state.upgrade_mode);
6309 EXPECT_TRUE(sts_state.include_subdomains);
6310 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036311#if defined(OS_ANDROID)
6312 // Android's CertVerifyProc does not (yet) handle pins.
6313#else
martijnc0d6b622015-06-30 19:14:406314 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036315#endif
[email protected]37fd55fb2013-06-29 13:13:276316}
6317
estarka5da76702015-04-09 04:00:166318TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556319 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6320 https_test_server.ServeFilesFromSourceDirectory(
6321 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166322 ASSERT_TRUE(https_test_server.Start());
6323 // Make sure this test fails if the test server is changed to not
6324 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556325 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6326 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166327
6328 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366329 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166330 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6331 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166332 request->Start();
6333 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:166334 TransportSecurityState* security_state =
6335 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406336 TransportSecurityState::STSState sts_state;
6337 EXPECT_FALSE(
6338 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166339}
6340
estark06e0dac2015-08-07 21:56:016341namespace {
estark1614475f2016-03-10 03:46:476342const char kExpectCTStaticHostname[] = "preloaded-expect-ct.badssl.com";
dadriand476e652016-07-26 21:33:246343const char kExpectStapleStaticHostname[] = "preloaded-expect-staple.badssl.com";
6344const char kExpectStapleReportURI[] = "https://report.badssl.com/expect-staple";
estark06e0dac2015-08-07 21:56:016345const char kHPKPReportUri[] = "https://hpkp-report.test";
6346} // namespace
6347
[email protected]37fd55fb2013-06-29 13:13:276348// Tests that enabling HPKP on a domain does not affect the HSTS
6349// validity/expiration.
dadrian2faf2062016-07-16 00:03:176350TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:016351 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556352 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6353 https_test_server.SetSSLConfig(
6354 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6355 https_test_server.ServeFilesFromSourceDirectory(
6356 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276357 ASSERT_TRUE(https_test_server.Start());
6358
tommycli59a63432015-11-06 00:10:556359 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166360
[email protected]37fd55fb2013-06-29 13:13:276361 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366362 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166363 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6364 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196365 request->Start();
[email protected]255620da2013-08-19 13:14:296366 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276367 TransportSecurityState* security_state =
6368 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406369 TransportSecurityState::STSState sts_state;
6370 TransportSecurityState::PKPState pkp_state;
6371 EXPECT_FALSE(
6372 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6373 EXPECT_TRUE(
6374 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6375 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
6376 sts_state.upgrade_mode);
6377 EXPECT_FALSE(sts_state.include_subdomains);
6378 EXPECT_FALSE(pkp_state.include_subdomains);
6379 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:016380 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:406381 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:466382}
6383
estark06e0dac2015-08-07 21:56:016384// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:176385TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:016386 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556387 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6388 https_test_server.SetSSLConfig(
6389 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6390 https_test_server.ServeFilesFromSourceDirectory(
6391 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016392 ASSERT_TRUE(https_test_server.Start());
6393
tommycli59a63432015-11-06 00:10:556394 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016395
6396 // Set up a pin for |test_server_hostname|.
6397 TransportSecurityState security_state;
6398 const base::Time current_time(base::Time::Now());
6399 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6400 HashValueVector hashes;
6401 HashValue hash1;
6402 HashValue hash2;
6403 // The values here don't matter, as long as they are different from
6404 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446405 ASSERT_TRUE(
6406 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6407 ASSERT_TRUE(
6408 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016409 hashes.push_back(hash1);
6410 hashes.push_back(hash2);
6411 security_state.AddHPKP(test_server_hostname, expiry,
6412 false, /* include subdomains */
6413 hashes, report_uri);
6414
6415 MockCertificateReportSender mock_report_sender;
6416 security_state.SetReportSender(&mock_report_sender);
6417
6418 // Set up a MockCertVerifier to trigger a violation of the previously
6419 // set pin.
6420 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6421 ASSERT_TRUE(cert);
6422
6423 MockCertVerifier cert_verifier;
6424 CertVerifyResult verify_result;
6425 verify_result.verified_cert = cert;
6426 verify_result.is_issued_by_known_root = true;
6427 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446428 ASSERT_TRUE(
6429 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016430 verify_result.public_key_hashes.push_back(hash3);
6431 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6432
6433 TestNetworkDelegate network_delegate;
6434 TestURLRequestContext context(true);
6435 context.set_transport_security_state(&security_state);
6436 context.set_network_delegate(&network_delegate);
6437 context.set_cert_verifier(&cert_verifier);
6438 context.Init();
6439
6440 // Now send a request to trigger the violation.
6441 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366442 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166443 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
6444 TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016445 violating_request->Start();
6446 base::RunLoop().Run();
6447
6448 // Check that a report was sent.
6449 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6450 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446451 EXPECT_EQ("application/json; charset=utf-8",
6452 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366453 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016454 base::JSONReader::Read(mock_report_sender.latest_report()));
6455 ASSERT_TRUE(value);
jdoerriedc72ee942016-12-07 15:43:286456 ASSERT_TRUE(value->IsType(base::Value::Type::DICTIONARY));
estark06e0dac2015-08-07 21:56:016457 base::DictionaryValue* report_dict;
6458 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6459 std::string report_hostname;
6460 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6461 EXPECT_EQ(test_server_hostname, report_hostname);
6462}
6463
6464// Tests that reports get sent on requests with
6465// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176466TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016467 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556468 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6469 https_test_server.SetSSLConfig(
6470 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6471 https_test_server.ServeFilesFromSourceDirectory(
6472 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016473 ASSERT_TRUE(https_test_server.Start());
6474
tommycli59a63432015-11-06 00:10:556475 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016476
6477 TransportSecurityState security_state;
6478 MockCertificateReportSender mock_report_sender;
6479 security_state.SetReportSender(&mock_report_sender);
6480
6481 // Set up a MockCertVerifier to violate the pin in the Report-Only
6482 // header.
6483 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6484 ASSERT_TRUE(cert);
6485
6486 MockCertVerifier cert_verifier;
6487 CertVerifyResult verify_result;
6488 verify_result.verified_cert = cert;
6489 verify_result.is_issued_by_known_root = true;
6490 HashValue hash;
6491 // This value doesn't matter, as long as it is different from the pins
6492 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446493 ASSERT_TRUE(
6494 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016495 verify_result.public_key_hashes.push_back(hash);
6496 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6497
6498 TestNetworkDelegate network_delegate;
6499 TestURLRequestContext context(true);
6500 context.set_transport_security_state(&security_state);
6501 context.set_network_delegate(&network_delegate);
6502 context.set_cert_verifier(&cert_verifier);
6503 context.Init();
6504
6505 // Now send a request to trigger the violation.
6506 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366507 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556508 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:166509 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016510 violating_request->Start();
6511 base::RunLoop().Run();
6512
6513 // Check that a report was sent.
6514 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6515 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446516 EXPECT_EQ("application/json; charset=utf-8",
6517 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366518 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016519 base::JSONReader::Read(mock_report_sender.latest_report()));
6520 ASSERT_TRUE(value);
jdoerriedc72ee942016-12-07 15:43:286521 ASSERT_TRUE(value->IsType(base::Value::Type::DICTIONARY));
estark06e0dac2015-08-07 21:56:016522 base::DictionaryValue* report_dict;
6523 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6524 std::string report_hostname;
6525 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6526 EXPECT_EQ(test_server_hostname, report_hostname);
6527}
6528
6529// Tests that reports do not get sent on requests with
6530// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:176531TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016532 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556533 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6534 https_test_server.SetSSLConfig(
6535 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6536 https_test_server.ServeFilesFromSourceDirectory(
6537 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016538 ASSERT_TRUE(https_test_server.Start());
6539
tommycli59a63432015-11-06 00:10:556540 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016541
6542 TransportSecurityState security_state;
6543 MockCertificateReportSender mock_report_sender;
6544 security_state.SetReportSender(&mock_report_sender);
6545
6546 TestNetworkDelegate network_delegate;
6547 MockCertVerifier mock_cert_verifier;
6548 TestURLRequestContext context(true);
6549 context.set_transport_security_state(&security_state);
6550 context.set_network_delegate(&network_delegate);
6551 context.set_cert_verifier(&mock_cert_verifier);
6552 mock_cert_verifier.set_default_result(OK);
6553 context.Init();
6554
6555 // Now send a request that does not trigger the violation.
6556 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366557 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556558 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:166559 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016560 request->Start();
6561 base::RunLoop().Run();
6562
6563 // Check that a report was not sent.
6564 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6565 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6566}
6567
estarka5da76702015-04-09 04:00:166568TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556569 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6570 https_test_server.ServeFilesFromSourceDirectory(
6571 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166572 ASSERT_TRUE(https_test_server.Start());
6573 // Make sure this test fails if the test server is changed to not
6574 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556575 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6576 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166577
6578 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366579 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166580 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6581 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166582 request->Start();
6583 base::RunLoop().Run();
6584
6585 TransportSecurityState* security_state =
6586 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406587 TransportSecurityState::PKPState pkp_state;
6588 EXPECT_FALSE(
6589 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166590}
6591
dadriandf302c42016-06-10 18:48:596592TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6593 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6594 https_test_server.SetSSLConfig(
6595 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6596 https_test_server.ServeFilesFromSourceDirectory(
6597 base::FilePath(kTestFilePath));
6598 ASSERT_TRUE(https_test_server.Start());
6599
6600 // Set up a MockCertVerifier to be a local root that violates the pin
6601 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6602 ASSERT_TRUE(cert);
6603
6604 MockCertVerifier cert_verifier;
6605 CertVerifyResult verify_result;
6606 verify_result.verified_cert = cert;
6607 verify_result.is_issued_by_known_root = false;
6608 HashValue hash;
6609 ASSERT_TRUE(
6610 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6611 verify_result.public_key_hashes.push_back(hash);
6612 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6613 cert_verifier.set_default_result(OK);
6614
6615 std::string test_server_hostname = https_test_server.GetURL("/").host();
6616
6617 // Set up HPKP
6618 base::Time current_time = base::Time::Now();
6619 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
6620 HashValue pin;
6621 ASSERT_TRUE(
6622 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
6623 HashValueVector hashes;
6624 hashes.push_back(pin);
6625 GURL report_uri(kHPKPReportUri);
6626 TransportSecurityState security_state;
6627 security_state.AddHPKP(test_server_hostname, expiry,
6628 false, /* include subdomains */
6629 hashes, report_uri);
6630
6631 TestNetworkDelegate network_delegate;
6632 TestURLRequestContext context(true);
6633 context.set_transport_security_state(&security_state);
6634 context.set_network_delegate(&network_delegate);
6635 context.set_cert_verifier(&cert_verifier);
6636 context.Init();
6637
6638 TestDelegate d;
6639 std::unique_ptr<URLRequest> request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166640 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6641 TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:596642 request->Start();
6643 base::RunLoop().Run();
6644
6645 TransportSecurityState::PKPState pkp_state;
6646 EXPECT_TRUE(
6647 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
6648 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6649}
6650
[email protected]242d8562012-10-30 21:20:466651TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556652 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6653 https_test_server.SetSSLConfig(
6654 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6655 https_test_server.ServeFilesFromSourceDirectory(
6656 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466657 ASSERT_TRUE(https_test_server.Start());
6658
tommycli59a63432015-11-06 00:10:556659 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166660
[email protected]242d8562012-10-30 21:20:466661 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366662 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556663 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166664 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196665 request->Start();
[email protected]255620da2013-08-19 13:14:296666 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466667
6668 // We should have set parameters from the first header, not the second.
6669 TransportSecurityState* security_state =
6670 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406671 TransportSecurityState::STSState sts_state;
6672 EXPECT_TRUE(
6673 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6674 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6675 sts_state.upgrade_mode);
6676 EXPECT_FALSE(sts_state.include_subdomains);
6677 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466678}
6679
[email protected]9f972ec2013-04-10 20:24:366680TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556681 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6682 https_test_server.SetSSLConfig(
6683 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6684 https_test_server.ServeFilesFromSourceDirectory(
6685 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366686 ASSERT_TRUE(https_test_server.Start());
6687
tommycli59a63432015-11-06 00:10:556688 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166689
[email protected]9f972ec2013-04-10 20:24:366690 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366691 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556692 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166693 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196694 request->Start();
[email protected]255620da2013-08-19 13:14:296695 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366696
6697 // We should have set parameters from the first header, not the second.
6698 TransportSecurityState* security_state =
6699 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406700 TransportSecurityState::STSState sts_state;
6701 TransportSecurityState::PKPState pkp_state;
6702 EXPECT_TRUE(
6703 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6704 EXPECT_TRUE(
6705 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6706 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6707 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036708#if defined(OS_ANDROID)
6709 // Android's CertVerifyProc does not (yet) handle pins.
6710#else
martijnc0d6b622015-06-30 19:14:406711 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036712#endif
martijnc0d6b622015-06-30 19:14:406713 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366714
[email protected]a165f092013-06-12 16:10:056715 // Even though there is an HSTS header asserting includeSubdomains, it is
6716 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406717 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056718 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406719 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366720}
6721
[email protected]37fd55fb2013-06-29 13:13:276722// Tests that when multiple HPKP headers are present, asserting different
6723// policies, that only the first such policy is processed.
6724TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556725 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6726 https_test_server.SetSSLConfig(
6727 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6728 https_test_server.ServeFilesFromSourceDirectory(
6729 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276730 ASSERT_TRUE(https_test_server.Start());
6731
tommycli59a63432015-11-06 00:10:556732 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166733
[email protected]37fd55fb2013-06-29 13:13:276734 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366735 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556736 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
rhalavatib7bd7c792017-04-27 05:25:166737 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196738 request->Start();
[email protected]255620da2013-08-19 13:14:296739 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276740
6741 TransportSecurityState* security_state =
6742 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406743 TransportSecurityState::STSState sts_state;
6744 TransportSecurityState::PKPState pkp_state;
6745 EXPECT_TRUE(
6746 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6747 EXPECT_TRUE(
6748 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6749 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6750 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036751#if defined(OS_ANDROID)
6752 // Android's CertVerifyProc does not (yet) handle pins.
6753#else
martijnc0d6b622015-06-30 19:14:406754 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036755#endif
martijnc0d6b622015-06-30 19:14:406756 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276757
martijnc0d6b622015-06-30 19:14:406758 EXPECT_TRUE(sts_state.include_subdomains);
6759 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276760}
6761
estark1614475f2016-03-10 03:46:476762// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6763// called.
6764class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6765 public:
6766 MockExpectCTReporter() : num_failures_(0) {}
6767 ~MockExpectCTReporter() override {}
6768
6769 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6770 const GURL& report_uri,
estarkae028b462017-06-20 23:25:016771 base::Time expiration,
estarkbf1b52962017-05-05 17:05:256772 const X509Certificate* validated_certificate_chain,
6773 const X509Certificate* served_certificate_chain,
6774 const SignedCertificateTimestampAndStatusList&
6775 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:476776 num_failures_++;
6777 }
6778
6779 uint32_t num_failures() { return num_failures_; }
6780
6781 private:
6782 uint32_t num_failures_;
6783};
6784
estark1614475f2016-03-10 03:46:476785// A CTPolicyEnforcer that returns a default CertPolicyCompliance value
6786// for every certificate.
6787class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6788 public:
6789 MockCTPolicyEnforcer()
6790 : default_result_(
6791 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) {}
6792 ~MockCTPolicyEnforcer() override {}
6793
6794 ct::CertPolicyCompliance DoesConformToCertPolicy(
6795 X509Certificate* cert,
6796 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:206797 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:476798 return default_result_;
6799 }
6800
6801 void set_default_result(ct::CertPolicyCompliance default_result) {
6802 default_result_ = default_result;
6803 }
6804
6805 private:
6806 ct::CertPolicyCompliance default_result_;
6807};
6808
Emily Stark4cfecf072017-08-08 01:05:516809// Tests that Expect CT headers for the preload list are processed correctly.
6810TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
xunjieli815ad5b2017-07-18 15:51:356811#if !BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
6812 SetTransportSecurityStateSourceForTesting(&test0::kHSTSSource);
6813#endif
estark1614475f2016-03-10 03:46:476814 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6815 https_test_server.SetSSLConfig(
6816 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6817 https_test_server.ServeFilesFromSourceDirectory(
6818 base::FilePath(kTestFilePath));
6819 ASSERT_TRUE(https_test_server.Start());
6820
6821 MockExpectCTReporter reporter;
6822 TransportSecurityState transport_security_state;
6823 transport_security_state.enable_static_expect_ct_ = true;
6824 transport_security_state.SetExpectCTReporter(&reporter);
6825
6826 // Set up a MockCertVerifier to accept the certificate that the server sends.
6827 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6828 ASSERT_TRUE(cert);
6829 MockCertVerifier cert_verifier;
6830 CertVerifyResult verify_result;
6831 verify_result.verified_cert = cert;
6832 verify_result.is_issued_by_known_root = true;
6833 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6834
rsleevi22cae1672016-12-28 01:53:366835 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
6836 // CT violation.
6837 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:476838 MockCTPolicyEnforcer ct_policy_enforcer;
6839 ct_policy_enforcer.set_default_result(
6840 ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS);
6841
6842 TestNetworkDelegate network_delegate;
6843 // Use a MockHostResolver (which by default maps all hosts to
6844 // 127.0.0.1) so that the request can be sent to a site on the Expect
6845 // CT preload list.
6846 MockHostResolver host_resolver;
6847 TestURLRequestContext context(true);
6848 context.set_host_resolver(&host_resolver);
6849 context.set_transport_security_state(&transport_security_state);
6850 context.set_network_delegate(&network_delegate);
6851 context.set_cert_verifier(&cert_verifier);
6852 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:466853 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:476854 context.Init();
6855
6856 // Now send a request to trigger the violation.
6857 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:516858 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:476859 GURL::Replacements replace_host;
6860 replace_host.SetHostStr(kExpectCTStaticHostname);
6861 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:166862 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
6863 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:476864 violating_request->Start();
6865 base::RunLoop().Run();
6866
6867 EXPECT_EQ(1u, reporter.num_failures());
6868}
Emily Stark4cfecf072017-08-08 01:05:516869
6870// Tests that Expect CT HTTP headers are processed correctly.
6871TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6872 base::test::ScopedFeatureList feature_list;
6873 feature_list.InitAndEnableFeature(
6874 TransportSecurityState::kDynamicExpectCTFeature);
6875
6876 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6877 https_test_server.SetSSLConfig(
6878 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6879 https_test_server.ServeFilesFromSourceDirectory(
6880 base::FilePath(kTestFilePath));
6881 ASSERT_TRUE(https_test_server.Start());
6882
6883 MockExpectCTReporter reporter;
6884 TransportSecurityState transport_security_state;
6885 transport_security_state.SetExpectCTReporter(&reporter);
6886
6887 // Set up a MockCertVerifier to accept the certificate that the server sends.
6888 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6889 ASSERT_TRUE(cert);
6890 MockCertVerifier cert_verifier;
6891 CertVerifyResult verify_result;
6892 verify_result.verified_cert = cert;
6893 verify_result.is_issued_by_known_root = true;
6894 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6895
6896 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
6897 // compliance.
6898 DoNothingCTVerifier ct_verifier;
6899 MockCTPolicyEnforcer ct_policy_enforcer;
6900 ct_policy_enforcer.set_default_result(
6901 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS);
6902
6903 TestNetworkDelegate network_delegate;
6904 // Use a MockHostResolver (which by default maps all hosts to
6905 // 127.0.0.1).
6906 MockHostResolver host_resolver;
6907 TestURLRequestContext context(true);
6908 context.set_host_resolver(&host_resolver);
6909 context.set_transport_security_state(&transport_security_state);
6910 context.set_network_delegate(&network_delegate);
6911 context.set_cert_verifier(&cert_verifier);
6912 context.set_cert_transparency_verifier(&ct_verifier);
6913 context.set_ct_policy_enforcer(&ct_policy_enforcer);
6914 context.Init();
6915
6916 // Now send a request to trigger the header processing.
6917 TestDelegate d;
6918 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6919 std::unique_ptr<URLRequest> request(context.CreateRequest(
6920 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
6921 request->Start();
6922 base::RunLoop().Run();
6923
6924 TransportSecurityState::ExpectCTState state;
6925 ASSERT_TRUE(
6926 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
6927 EXPECT_TRUE(state.enforce);
6928 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
6929}
6930
6931// Tests that if multiple Expect CT HTTP headers are sent, they are all
6932// processed.
6933TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
6934 base::test::ScopedFeatureList feature_list;
6935 feature_list.InitAndEnableFeature(
6936 TransportSecurityState::kDynamicExpectCTFeature);
6937
6938 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6939 https_test_server.SetSSLConfig(
6940 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6941 https_test_server.ServeFilesFromSourceDirectory(
6942 base::FilePath(kTestFilePath));
6943 ASSERT_TRUE(https_test_server.Start());
6944
6945 MockExpectCTReporter reporter;
6946 TransportSecurityState transport_security_state;
6947 transport_security_state.SetExpectCTReporter(&reporter);
6948
6949 // Set up a MockCertVerifier to accept the certificate that the server sends.
6950 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6951 ASSERT_TRUE(cert);
6952 MockCertVerifier cert_verifier;
6953 CertVerifyResult verify_result;
6954 verify_result.verified_cert = cert;
6955 verify_result.is_issued_by_known_root = true;
6956 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6957
6958 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
6959 // compliance.
6960 DoNothingCTVerifier ct_verifier;
6961 MockCTPolicyEnforcer ct_policy_enforcer;
6962 ct_policy_enforcer.set_default_result(
6963 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS);
6964
6965 TestNetworkDelegate network_delegate;
6966 // Use a MockHostResolver (which by default maps all hosts to
6967 // 127.0.0.1).
6968 MockHostResolver host_resolver;
6969 TestURLRequestContext context(true);
6970 context.set_host_resolver(&host_resolver);
6971 context.set_transport_security_state(&transport_security_state);
6972 context.set_network_delegate(&network_delegate);
6973 context.set_cert_verifier(&cert_verifier);
6974 context.set_cert_transparency_verifier(&ct_verifier);
6975 context.set_ct_policy_enforcer(&ct_policy_enforcer);
6976 context.Init();
6977
6978 // Now send a request to trigger the header processing.
6979 TestDelegate d;
6980 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
6981 std::unique_ptr<URLRequest> request(context.CreateRequest(
6982 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
6983 request->Start();
6984 base::RunLoop().Run();
6985
6986 TransportSecurityState::ExpectCTState state;
6987 ASSERT_TRUE(
6988 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
6989 EXPECT_TRUE(state.enforce);
6990 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
6991}
6992
mmenkefd9d15c2017-06-29 13:45:546993#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:476994
mmenkefd9d15c2017-06-29 13:45:546995#if BUILDFLAG(ENABLE_REPORTING)
juliatuttle2b8dd2d12017-04-12 21:27:416996namespace {
6997
6998class TestReportingService : public ReportingService {
6999 public:
7000 struct Header {
7001 GURL url;
7002 std::string header_value;
7003 };
7004
juliatuttle2b8dd2d12017-04-12 21:27:417005 const std::vector<Header>& headers() { return headers_; }
7006
juliatuttle1d92f0152017-04-28 17:19:217007 // ReportingService implementation:
7008
7009 ~TestReportingService() override {}
7010
juliatuttle2b8dd2d12017-04-12 21:27:417011 void QueueReport(const GURL& url,
7012 const std::string& group,
7013 const std::string& type,
7014 std::unique_ptr<const base::Value> body) override {
7015 NOTIMPLEMENTED();
7016 }
7017
7018 void ProcessHeader(const GURL& url,
7019 const std::string& header_value) override {
7020 headers_.push_back({url, header_value});
7021 }
7022
juliatuttleaeb1abc2017-05-04 21:14:387023 void RemoveBrowsingData(
7024 int data_type_mask,
7025 base::Callback<bool(const GURL&)> origin_filter) override {
7026 NOTIMPLEMENTED();
7027 }
7028
juliatuttle2b8dd2d12017-04-12 21:27:417029 private:
7030 std::vector<Header> headers_;
7031};
7032
7033std::unique_ptr<test_server::HttpResponse> SendReportToHeader(
7034 const test_server::HttpRequest& request) {
7035 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7036 new test_server::BasicHttpResponse);
7037 http_response->set_code(HTTP_OK);
7038 http_response->AddCustomHeader("Report-To", "foo");
7039 http_response->AddCustomHeader("Report-To", "bar");
7040 return std::move(http_response);
7041}
7042
7043} // namespace
7044
7045TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderNoService) {
7046 http_test_server()->RegisterRequestHandler(base::Bind(&SendReportToHeader));
7047 ASSERT_TRUE(http_test_server()->Start());
7048 GURL request_url = http_test_server()->GetURL("/");
7049
7050 TestNetworkDelegate network_delegate;
7051 TestURLRequestContext context(true);
7052 context.set_network_delegate(&network_delegate);
7053 context.Init();
7054
7055 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167056 std::unique_ptr<URLRequest> request(context.CreateRequest(
7057 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417058 request->Start();
7059 base::RunLoop().Run();
7060}
7061
7062TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderHTTP) {
7063 http_test_server()->RegisterRequestHandler(base::Bind(&SendReportToHeader));
7064 ASSERT_TRUE(http_test_server()->Start());
7065 GURL request_url = http_test_server()->GetURL("/");
7066
7067 TestNetworkDelegate network_delegate;
7068 TestReportingService reporting_service;
7069 TestURLRequestContext context(true);
7070 context.set_network_delegate(&network_delegate);
7071 context.set_reporting_service(&reporting_service);
7072 context.Init();
7073
7074 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167075 std::unique_ptr<URLRequest> request(context.CreateRequest(
7076 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417077 request->Start();
7078 base::RunLoop().Run();
7079
7080 EXPECT_TRUE(reporting_service.headers().empty());
7081}
7082
7083TEST_F(URLRequestTestHTTP, ProcessReportToHeaderHTTPS) {
7084 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7085 https_test_server.RegisterRequestHandler(base::Bind(&SendReportToHeader));
7086 ASSERT_TRUE(https_test_server.Start());
7087 GURL request_url = https_test_server.GetURL("/");
7088
7089 TestNetworkDelegate network_delegate;
7090 TestReportingService reporting_service;
7091 TestURLRequestContext context(true);
7092 context.set_network_delegate(&network_delegate);
7093 context.set_reporting_service(&reporting_service);
7094 context.Init();
7095
7096 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167097 std::unique_ptr<URLRequest> request(context.CreateRequest(
7098 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417099 request->Start();
7100 base::RunLoop().Run();
7101
7102 ASSERT_EQ(1u, reporting_service.headers().size());
7103 EXPECT_EQ(request_url, reporting_service.headers()[0].url);
7104 EXPECT_EQ("foo, bar", reporting_service.headers()[0].header_value);
7105}
7106
Julia Tuttlef9b74062017-07-27 14:44:057107TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderInvalidHttps) {
juliatuttle2b8dd2d12017-04-12 21:27:417108 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7109 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
7110 https_test_server.RegisterRequestHandler(base::Bind(&SendReportToHeader));
7111 ASSERT_TRUE(https_test_server.Start());
7112 GURL request_url = https_test_server.GetURL("/");
7113
7114 TestNetworkDelegate network_delegate;
7115 TestReportingService reporting_service;
7116 TestURLRequestContext context(true);
7117 context.set_network_delegate(&network_delegate);
7118 context.set_reporting_service(&reporting_service);
7119 context.Init();
7120
7121 TestDelegate d;
7122 d.set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:167123 std::unique_ptr<URLRequest> request(context.CreateRequest(
7124 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417125 request->Start();
7126 base::RunLoop().Run();
7127
7128 EXPECT_TRUE(d.have_certificate_errors());
7129 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
7130 EXPECT_TRUE(reporting_service.headers().empty());
7131}
mmenkefd9d15c2017-06-29 13:45:547132#endif // BUILDFLAG(ENABLE_REPORTING)
tommycli59a63432015-11-06 00:10:557133
Julia Tuttlef9b74062017-07-27 14:44:057134namespace {
7135
7136class TestNetworkErrorLoggingDelegate : public NetworkErrorLoggingDelegate {
7137 public:
7138 struct Header {
7139 Header() {}
7140 ~Header() {}
7141
7142 url::Origin origin;
7143 std::string value;
7144 };
7145
7146 struct NetworkError {
7147 NetworkError() {}
7148 ~NetworkError() {}
7149
7150 url::Origin origin;
7151 Error error;
7152 NetworkErrorLoggingDelegate::ErrorDetails details;
7153 };
7154
7155 const std::vector<Header>& headers() { return headers_; }
7156 const std::vector<NetworkError>& errors() { return errors_; }
7157
7158 // NetworkErrorLoggingDelegate implementation:
7159
7160 ~TestNetworkErrorLoggingDelegate() override {}
7161
7162 void SetReportingService(ReportingService* reporting_service) override {
7163 NOTREACHED();
7164 }
7165
7166 void OnHeader(const url::Origin& origin, const std::string& value) override {
7167 Header header;
7168 header.origin = origin;
7169 header.value = value;
7170 headers_.push_back(header);
7171 }
7172
7173 void OnNetworkError(const url::Origin& origin,
7174 Error error,
7175 ErrorDetailsCallback details_callback) override {
7176 NetworkError network_error;
7177 network_error.origin = origin;
7178 network_error.error = error;
7179 std::move(details_callback).Run(&network_error.details);
7180 errors_.push_back(network_error);
7181 }
7182
7183 private:
7184 std::vector<Header> headers_;
7185 std::vector<NetworkError> errors_;
7186};
7187
7188std::unique_ptr<test_server::HttpResponse> SendNelHeader(
7189 const test_server::HttpRequest& request) {
7190 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7191 new test_server::BasicHttpResponse);
7192 http_response->set_code(HTTP_OK);
7193 http_response->AddCustomHeader(NetworkErrorLoggingDelegate::kHeaderName,
7194 "foo");
7195 return std::move(http_response);
7196}
7197
7198} // namespace
7199
7200TEST_F(URLRequestTestHTTP, DontProcessNelHeaderNoDelegate) {
7201 http_test_server()->RegisterRequestHandler(base::Bind(&SendNelHeader));
7202 ASSERT_TRUE(http_test_server()->Start());
7203 GURL request_url = http_test_server()->GetURL("/");
7204
7205 TestNetworkDelegate network_delegate;
7206 TestURLRequestContext context(true);
7207 context.set_network_delegate(&network_delegate);
7208 context.Init();
7209
7210 TestDelegate d;
7211 std::unique_ptr<URLRequest> request(context.CreateRequest(
7212 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7213 request->Start();
7214 base::RunLoop().Run();
7215}
7216
7217TEST_F(URLRequestTestHTTP, DontProcessNelHeaderHttp) {
7218 http_test_server()->RegisterRequestHandler(base::Bind(&SendNelHeader));
7219 ASSERT_TRUE(http_test_server()->Start());
7220 GURL request_url = http_test_server()->GetURL("/");
7221
7222 TestNetworkDelegate network_delegate;
7223 TestNetworkErrorLoggingDelegate nel_delegate;
7224 TestURLRequestContext context(true);
7225 context.set_network_delegate(&network_delegate);
7226 context.set_network_error_logging_delegate(&nel_delegate);
7227 context.Init();
7228
7229 TestDelegate d;
7230 std::unique_ptr<URLRequest> request(context.CreateRequest(
7231 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7232 request->Start();
7233 base::RunLoop().Run();
7234
7235 EXPECT_TRUE(nel_delegate.headers().empty());
7236}
7237
7238TEST_F(URLRequestTestHTTP, ProcessNelHeaderHttps) {
7239 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7240 https_test_server.RegisterRequestHandler(base::Bind(&SendNelHeader));
7241 ASSERT_TRUE(https_test_server.Start());
7242 GURL request_url = https_test_server.GetURL("/");
7243
7244 TestNetworkDelegate network_delegate;
7245 TestNetworkErrorLoggingDelegate nel_delegate;
7246 TestURLRequestContext context(true);
7247 context.set_network_delegate(&network_delegate);
7248 context.set_network_error_logging_delegate(&nel_delegate);
7249 context.Init();
7250
7251 TestDelegate d;
7252 std::unique_ptr<URLRequest> request(context.CreateRequest(
7253 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7254 request->Start();
7255 base::RunLoop().Run();
7256
7257 ASSERT_EQ(1u, nel_delegate.headers().size());
7258 EXPECT_EQ(url::Origin(request_url), nel_delegate.headers()[0].origin);
7259 EXPECT_EQ("foo", nel_delegate.headers()[0].value);
7260}
7261
7262TEST_F(URLRequestTestHTTP, DontProcessNelHeaderInvalidHttps) {
7263 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7264 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
7265 https_test_server.RegisterRequestHandler(base::Bind(&SendNelHeader));
7266 ASSERT_TRUE(https_test_server.Start());
7267 GURL request_url = https_test_server.GetURL("/");
7268
7269 TestNetworkDelegate network_delegate;
7270 TestNetworkErrorLoggingDelegate nel_delegate;
7271 TestURLRequestContext context(true);
7272 context.set_network_delegate(&network_delegate);
7273 context.set_network_error_logging_delegate(&nel_delegate);
7274 context.Init();
7275
7276 TestDelegate d;
7277 d.set_allow_certificate_errors(true);
7278 std::unique_ptr<URLRequest> request(context.CreateRequest(
7279 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7280 request->Start();
7281 base::RunLoop().Run();
7282
7283 EXPECT_TRUE(d.have_certificate_errors());
7284 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
7285 EXPECT_TRUE(nel_delegate.headers().empty());
7286}
7287
[email protected]316c1e5e2012-09-12 15:17:447288TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557289 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447290
7291 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367292 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557293 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167294 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197295 req->Start();
[email protected]255620da2013-08-19 13:14:297296 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447297
7298 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197299 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447300 EXPECT_EQ("text/html", mime_type);
7301
7302 std::string charset;
[email protected]f7022f32014-08-21 16:32:197303 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447304 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197305 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447306}
7307
[email protected]02494ec2014-05-07 15:05:297308TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347309 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347310 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347311 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027312 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347313
7314 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507315 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347316}
7317
brettwa1228ebb2016-10-28 03:51:347318#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297319TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7320 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7321 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457322 FileProtocolHandler file_protocol_handler(
7323 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297324 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7325
7326 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507327 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297328}
7329
[email protected]588614c22013-08-16 00:09:027330TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557331 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447332
7333 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367334 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557335 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167336 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197337 req->Start();
[email protected]255620da2013-08-19 13:14:297338 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447339
maksim.sisovb53724b52016-09-16 05:30:507340 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307341
7342 // The redirect should have been rejected before reporting it to the caller.
7343 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447344}
brettwa1228ebb2016-10-28 03:51:347345#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447346
[email protected]588614c22013-08-16 00:09:027347TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557348 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027349
7350 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367351 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557352 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167353 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197354 req->Start();
fdoray5eeb7642016-06-22 16:11:287355 base::RunLoop().Run();
[email protected]588614c22013-08-16 00:09:027356
maksim.sisovb53724b52016-09-16 05:30:507357 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307358
7359 // The redirect should have been rejected before reporting it to the
7360 // caller. See https://crbug.com/723796
7361 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027362}
7363
davidbend894710b2017-06-06 19:28:307364// Test that redirects to invalid URLs are rejected. See
7365// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447366TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557367 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447368
7369 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367370 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557371 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167372 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197373 req->Start();
[email protected]255620da2013-08-19 13:14:297374 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447375
davidbend894710b2017-06-06 19:28:307376 EXPECT_EQ(1, d.response_started_count());
7377 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7378
7379 // The redirect should have been rejected before reporting it to the caller.
7380 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447381}
7382
[email protected]e50efea2014-03-24 18:41:007383// Make sure redirects are cached, despite not reading their bodies.
7384TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557385 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007386 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557387 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007388
7389 {
7390 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167391 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7392 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197393 req->Start();
[email protected]e50efea2014-03-24 18:41:007394 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507395 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007396 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557397 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007398 }
7399
7400 {
7401 TestDelegate d;
7402 d.set_quit_on_redirect(true);
rhalavatib7bd7c792017-04-27 05:25:167403 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7404 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197405 req->Start();
[email protected]e50efea2014-03-24 18:41:007406 base::RunLoop().Run();
7407
7408 EXPECT_EQ(1, d.received_redirect_count());
7409 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197410 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007411
[email protected]f7022f32014-08-21 16:32:197412 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:007413 base::RunLoop().Run();
7414 EXPECT_EQ(1, d.received_redirect_count());
7415 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507416 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557417 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007418 }
7419}
7420
7421// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7422// when the headers are read, since the body won't have been read.
7423TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557424 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007425 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557426 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007427
7428 {
7429 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557430 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007431 default_network_delegate_.set_redirect_on_headers_received_url(
7432 redirect_to_url);
7433
7434 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167435 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7436 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197437 req->Start();
[email protected]e50efea2014-03-24 18:41:007438 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507439 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007440 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197441 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007442 }
7443
7444 {
7445 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167446 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7447 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197448 req->Start();
[email protected]e50efea2014-03-24 18:41:007449 base::RunLoop().Run();
7450
maksim.sisovb53724b52016-09-16 05:30:507451 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197452 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007453 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197454 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007455 }
7456}
7457
[email protected]5f714132014-03-26 10:41:167458// Tests that redirection to an unsafe URL is allowed when it has been marked as
7459// safe.
7460TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557461 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167462
7463 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7464 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7465 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7466
7467 TestDelegate d;
7468 {
danakj8522a25b2016-04-16 00:17:367469 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167470 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7471 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167472
[email protected]f7022f32014-08-21 16:32:197473 r->Start();
[email protected]5f714132014-03-26 10:41:167474 base::RunLoop().Run();
7475
maksim.sisovb53724b52016-09-16 05:30:507476 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197477 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197478 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167479 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7480 }
7481}
7482
7483// Tests that a redirect to a different unsafe URL is blocked, even after adding
7484// some other URL to the whitelist.
7485TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557486 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167487
7488 GURL unsafe_url("data:text/html,something");
7489 GURL different_unsafe_url("data:text/html,something-else");
7490 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7491 default_network_delegate_.set_allowed_unsafe_redirect_url(
7492 different_unsafe_url);
7493
7494 TestDelegate d;
7495 {
danakj8522a25b2016-04-16 00:17:367496 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167497 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7498 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167499
[email protected]f7022f32014-08-21 16:32:197500 r->Start();
[email protected]5f714132014-03-26 10:41:167501 base::RunLoop().Run();
7502
maksim.sisovb53724b52016-09-16 05:30:507503 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307504
7505 // The redirect should have been rejected before reporting it to the caller.
7506 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167507 }
7508}
7509
[email protected]5f714132014-03-26 10:41:167510// Redirects from an URL with fragment to an unsafe URL with fragment should
7511// be allowed, and the reference fragment of the target URL should be preserved.
7512TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557513 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167514
tommycli59a63432015-11-06 00:10:557515 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167516 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7517 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7518
7519 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7520 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7521
7522 TestDelegate d;
7523 {
rhalavatib7bd7c792017-04-27 05:25:167524 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7525 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167526
[email protected]f7022f32014-08-21 16:32:197527 r->Start();
[email protected]5f714132014-03-26 10:41:167528 base::RunLoop().Run();
7529
[email protected]f7022f32014-08-21 16:32:197530 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507531 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197532 EXPECT_EQ(original_url, r->original_url());
7533 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167534 }
7535}
7536
7537// When a delegate has specified a safe redirect URL, but it does not match the
7538// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147539TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557540 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167541
tommycli59a63432015-11-06 00:10:557542 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167543 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557544 GURL redirect_url(http_test_server()->GetURL("/target"));
7545 GURL expected_redirect_url(
7546 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167547
7548 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7549 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7550
7551 TestDelegate d;
7552 {
rhalavatib7bd7c792017-04-27 05:25:167553 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7554 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167555
[email protected]f7022f32014-08-21 16:32:197556 r->Start();
[email protected]5f714132014-03-26 10:41:167557 base::RunLoop().Run();
7558
[email protected]f7022f32014-08-21 16:32:197559 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507560 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197561 EXPECT_EQ(original_url, r->original_url());
7562 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167563 }
7564}
7565
[email protected]f878230e2014-04-03 15:36:147566// When a delegate has specified a safe redirect URL, assume that the redirect
7567// URL should not be changed. In particular, the reference fragment should not
7568// be modified.
7569TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557570 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147571
tommycli59a63432015-11-06 00:10:557572 GURL original_url(
7573 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147574 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7575
7576 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7577 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7578
7579 TestDelegate d;
7580 {
rhalavatib7bd7c792017-04-27 05:25:167581 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7582 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147583
[email protected]f7022f32014-08-21 16:32:197584 r->Start();
[email protected]f878230e2014-04-03 15:36:147585 base::RunLoop().Run();
7586
[email protected]f7022f32014-08-21 16:32:197587 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507588 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197589 EXPECT_EQ(original_url, r->original_url());
7590 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147591 }
7592}
7593
7594// When a URLRequestRedirectJob is created, the redirection must be followed and
7595// the reference fragment of the target URL must not be modified.
7596TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557597 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147598
tommycli59a63432015-11-06 00:10:557599 GURL original_url(
7600 http_test_server()->GetURL("/original#should-not-be-appended"));
7601 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147602
7603 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167604 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7605 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147606
danakj8522a25b2016-04-16 00:17:367607 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197608 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427609 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7610 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:147611
[email protected]f7022f32014-08-21 16:32:197612 r->Start();
[email protected]f878230e2014-04-03 15:36:147613 base::RunLoop().Run();
7614
maksim.sisovb53724b52016-09-16 05:30:507615 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197616 EXPECT_EQ(original_url, r->original_url());
7617 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147618}
7619
lizeb5120f6dc2016-02-19 09:29:447620TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
7621 ASSERT_TRUE(http_test_server()->Start());
7622
7623 const std::string referrer("foobar://totally.legit.referrer");
7624 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367625 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167626 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7627 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:447628 req->SetReferrer(referrer);
7629 req->Start();
7630 base::RunLoop().Run();
7631
7632 EXPECT_EQ(std::string("None"), d.data_received());
7633}
7634
[email protected]316c1e5e2012-09-12 15:17:447635TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:557636 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447637
7638 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367639 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167640 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7641 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197642 req->SetReferrer("http://user:[email protected]/");
7643 req->Start();
[email protected]255620da2013-08-19 13:14:297644 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447645
7646 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
7647}
7648
[email protected]99ecf6e2013-04-10 22:46:137649TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:557650 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137651
7652 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367653 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167654 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7655 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197656 req->SetReferrer("http://foo.com/test#fragment");
7657 req->Start();
[email protected]255620da2013-08-19 13:14:297658 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:137659
7660 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
7661}
7662
7663TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:557664 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137665
7666 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367667 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167668 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7669 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197670 req->SetReferrer("http://foo.com/test#fragment");
7671 req->SetReferrer("");
7672 req->Start();
[email protected]255620da2013-08-19 13:14:297673 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:137674
7675 EXPECT_EQ(std::string("None"), d.data_received());
7676}
7677
[email protected]316c1e5e2012-09-12 15:17:447678TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:557679 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447680
7681 TestDelegate d;
7682 {
7683 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:367684 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167685 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7686 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197687 req->Start();
[email protected]255620da2013-08-19 13:14:297688 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447689
7690 EXPECT_EQ(1, d.response_started_count());
7691 EXPECT_EQ(0, d.bytes_received());
7692 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507693 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447694 }
7695}
7696
7697TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:557698 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447699
7700 TestDelegate d;
7701 {
7702 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:557703 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:167704 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7705 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047706
[email protected]f7022f32014-08-21 16:32:197707 req->Start();
[email protected]255620da2013-08-19 13:14:297708 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447709
7710 EXPECT_EQ(1, d.received_redirect_count());
7711
[email protected]f7022f32014-08-21 16:32:197712 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:297713 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447714
7715 EXPECT_EQ(1, d.response_started_count());
7716 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507717 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447718
[email protected]6cdfd7f2013-02-08 20:40:157719 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:447720 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477721 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:447722 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7723
7724 std::string contents;
[email protected]82f84b92013-08-30 18:23:507725 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:447726 EXPECT_EQ(contents, d.data_received());
7727 }
7728}
7729
[email protected]79e1fd62013-06-20 06:50:047730TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:557731 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:047732
7733 TestDelegate d;
7734 {
7735 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:557736 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:167737 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7738 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047739
7740 EXPECT_FALSE(d.have_full_request_headers());
7741
[email protected]f7022f32014-08-21 16:32:197742 req->Start();
[email protected]255620da2013-08-19 13:14:297743 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:047744
7745 EXPECT_EQ(1, d.received_redirect_count());
7746 EXPECT_TRUE(d.have_full_request_headers());
7747 CheckFullRequestHeaders(d.full_request_headers(), test_url);
7748 d.ClearFullRequestHeaders();
7749
[email protected]f7022f32014-08-21 16:32:197750 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:297751 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:047752
tommycli59a63432015-11-06 00:10:557753 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:047754 EXPECT_EQ(1, d.response_started_count());
7755 EXPECT_TRUE(d.have_full_request_headers());
7756 CheckFullRequestHeaders(d.full_request_headers(), target_url);
7757 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507758 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:047759
7760 base::FilePath path;
7761 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477762 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:047763 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7764
7765 std::string contents;
[email protected]82f84b92013-08-30 18:23:507766 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:047767 EXPECT_EQ(contents, d.data_received());
7768 }
7769}
7770
[email protected]316c1e5e2012-09-12 15:17:447771TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:557772 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447773
7774 TestDelegate d;
7775 {
7776 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:367777 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167778 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7779 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197780 req->Start();
[email protected]255620da2013-08-19 13:14:297781 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447782
7783 EXPECT_EQ(1, d.received_redirect_count());
7784
[email protected]f7022f32014-08-21 16:32:197785 req->Cancel();
[email protected]255620da2013-08-19 13:14:297786 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447787
7788 EXPECT_EQ(1, d.response_started_count());
7789 EXPECT_EQ(0, d.bytes_received());
7790 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507791 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447792 }
7793}
7794
7795TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:557796 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447797
[email protected]3b23a222013-05-15 21:33:257798 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:447799 {
7800 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367801 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557802 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167803 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447804 HttpRequestHeaders headers;
7805 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197806 req->SetExtraRequestHeaders(headers);
7807 req->Start();
[email protected]255620da2013-08-19 13:14:297808 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:257809
7810 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197811 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257812 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447813 }
7814
[email protected]3b23a222013-05-15 21:33:257815 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:447816 {
7817 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367818 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557819 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167820 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447821 HttpRequestHeaders headers;
7822 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197823 req->SetExtraRequestHeaders(headers);
7824 req->Start();
[email protected]255620da2013-08-19 13:14:297825 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447826
[email protected]f7022f32014-08-21 16:32:197827 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257828
7829 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197830 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257831 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:447832 }
7833
[email protected]3b23a222013-05-15 21:33:257834 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:447835 {
7836 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367837 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557838 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167839 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447840 HttpRequestHeaders headers;
7841 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:197842 req->SetExtraRequestHeaders(headers);
7843 req->Start();
[email protected]255620da2013-08-19 13:14:297844 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447845
[email protected]f7022f32014-08-21 16:32:197846 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257847
7848 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197849 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257850 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447851 }
7852}
7853
7854TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:557855 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447856
7857 // populate the cache
7858 {
7859 TestDelegate d;
7860 d.set_credentials(AuthCredentials(kUser, kSecret));
7861
danakj8522a25b2016-04-16 00:17:367862 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167863 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7864 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197865 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447866
[email protected]255620da2013-08-19 13:14:297867 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447868
7869 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7870 }
7871
7872 // repeat request with end-to-end validation. since auth-basic results in a
7873 // cachable page, we expect this test to result in a 304. in which case, the
7874 // response should be fetched from the cache.
7875 {
7876 TestDelegate d;
7877 d.set_credentials(AuthCredentials(kUser, kSecret));
7878
danakj8522a25b2016-04-16 00:17:367879 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167880 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7881 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197882 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7883 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447884
[email protected]255620da2013-08-19 13:14:297885 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447886
7887 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7888
7889 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197890 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:447891 }
7892}
7893
7894// Check that Set-Cookie headers in 401 responses are respected.
7895// http://crbug.com/6450
7896TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:557897 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447898
7899 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:557900 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:447901
7902 // Request a page that will give a 401 containing a Set-Cookie header.
7903 // Verify that when the transaction is restarted, it includes the new cookie.
7904 {
[email protected]ceefd7fd2012-11-29 00:36:247905 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447906 TestURLRequestContext context(true);
7907 context.set_network_delegate(&network_delegate);
7908 context.Init();
7909
7910 TestDelegate d;
7911 d.set_credentials(AuthCredentials(kUser, kSecret));
7912
danakj8522a25b2016-04-16 00:17:367913 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:167914 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
7915 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197916 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447917
[email protected]255620da2013-08-19 13:14:297918 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447919
7920 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7921
7922 // Make sure we sent the cookie in the restarted transaction.
7923 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7924 != std::string::npos);
7925 }
7926
7927 // Same test as above, except this time the restart is initiated earlier
7928 // (without user intervention since identity is embedded in the URL).
7929 {
[email protected]ceefd7fd2012-11-29 00:36:247930 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447931 TestURLRequestContext context(true);
7932 context.set_network_delegate(&network_delegate);
7933 context.Init();
7934
7935 TestDelegate d;
7936
7937 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:187938 replacements.SetUsernameStr("user2");
7939 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:447940 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
7941
rhalavatib7bd7c792017-04-27 05:25:167942 std::unique_ptr<URLRequest> r(context.CreateRequest(
7943 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197944 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447945
[email protected]255620da2013-08-19 13:14:297946 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447947
7948 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
7949
7950 // Make sure we sent the cookie in the restarted transaction.
7951 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7952 != std::string::npos);
7953 }
7954}
7955
[email protected]58e32bb2013-01-21 18:23:257956// Tests that load timing works as expected with auth and the cache.
7957TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:557958 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:257959
7960 // populate the cache
7961 {
7962 TestDelegate d;
7963 d.set_credentials(AuthCredentials(kUser, kSecret));
7964
danakj8522a25b2016-04-16 00:17:367965 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167966 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7967 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197968 r->Start();
[email protected]58e32bb2013-01-21 18:23:257969
[email protected]255620da2013-08-19 13:14:297970 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257971
7972 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7973
7974 LoadTimingInfo load_timing_info_before_auth;
7975 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7976 &load_timing_info_before_auth));
7977 TestLoadTimingNotReused(load_timing_info_before_auth,
7978 CONNECT_TIMING_HAS_DNS_TIMES);
7979
7980 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197981 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257982 // The test server does not support keep alive sockets, so the second
7983 // request with auth should use a new socket.
7984 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7985 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7986 load_timing_info.socket_log_id);
7987 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7988 load_timing_info.connect_timing.connect_start);
7989 }
7990
[email protected]3b23a222013-05-15 21:33:257991 // Repeat request with end-to-end validation. Since auth-basic results in a
7992 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:257993 // response should be fetched from the cache.
7994 {
7995 TestDelegate d;
7996 d.set_credentials(AuthCredentials(kUser, kSecret));
7997
danakj8522a25b2016-04-16 00:17:367998 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167999 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8000 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198001 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8002 r->Start();
[email protected]58e32bb2013-01-21 18:23:258003
[email protected]255620da2013-08-19 13:14:298004 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:258005
8006 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8007
8008 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198009 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258010
[email protected]3b23a222013-05-15 21:33:258011 // Since there was a request that went over the wire, the load timing
8012 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258013 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198014 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258015 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258016 }
8017}
8018
[email protected]316c1e5e2012-09-12 15:17:448019// In this test, we do a POST which the server will 302 redirect.
8020// The subsequent transaction should use GET, and should not send the
8021// Content-Type header.
8022// http://code.google.com/p/chromium/issues/detail?id=843
8023TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558024 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448025
8026 const char kData[] = "hello world";
8027
8028 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368029 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168030 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8031 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198032 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078033 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448034
8035 // Set headers (some of which are specific to the POST).
8036 HttpRequestHeaders headers;
8037 headers.AddHeadersFromString(
8038 "Content-Type: multipart/form-data; "
8039 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
8040 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
8041 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
8042 "Accept-Language: en-US,en\r\n"
8043 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
8044 "Content-Length: 11\r\n"
8045 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198046 req->SetExtraRequestHeaders(headers);
8047 req->Start();
[email protected]255620da2013-08-19 13:14:298048 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448049
8050 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198051 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448052 EXPECT_EQ("text/html", mime_type);
8053
8054 const std::string& data = d.data_received();
8055
8056 // Check that the post-specific headers were stripped:
8057 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8058 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498059 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448060
8061 // These extra request headers should not have been stripped.
8062 EXPECT_TRUE(ContainsString(data, "Accept:"));
8063 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8064 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
[email protected]316c1e5e2012-09-12 15:17:448065}
8066
jww5fe460ff2015-03-28 00:22:518067// The following tests check that we handle mutating the request for HTTP
8068// redirects as expected.
8069// See https://crbug.com/56373, https://crbug.com/102130, and
8070// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448071
8072TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558073 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448074
tommycli59a63432015-11-06 00:10:558075 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518076 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558077 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448078
8079 HTTPRedirectMethodTest(url, "POST", "GET", true);
8080 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8081 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518082
8083 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8084 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498085 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8086 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8087 std::string());
[email protected]316c1e5e2012-09-12 15:17:448088}
8089
8090TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558091 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448092
tommycli59a63432015-11-06 00:10:558093 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518094 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558095 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448096
8097 HTTPRedirectMethodTest(url, "POST", "GET", true);
8098 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8099 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518100
8101 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8102 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498103 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8104 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8105 std::string());
[email protected]316c1e5e2012-09-12 15:17:448106}
8107
8108TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558109 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448110
tommycli59a63432015-11-06 00:10:558111 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518112 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558113 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448114
8115 HTTPRedirectMethodTest(url, "POST", "GET", true);
8116 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8117 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518118
8119 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8120 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498121 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8122 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8123 std::string());
[email protected]316c1e5e2012-09-12 15:17:448124}
8125
8126TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558127 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448128
tommycli59a63432015-11-06 00:10:558129 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518130 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558131 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448132
8133 HTTPRedirectMethodTest(url, "POST", "POST", true);
8134 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8135 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518136
8137 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8138 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8139 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8140 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:448141}
8142
[email protected]0a17aab32014-04-24 03:32:378143TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558144 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378145
tommycli59a63432015-11-06 00:10:558146 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518147 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558148 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378149
8150 HTTPRedirectMethodTest(url, "POST", "POST", true);
8151 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8152 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518153
8154 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8155 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8156 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8157 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:378158}
8159
8160// Make sure that 308 responses without bodies are not treated as redirects.
8161// Certain legacy apis that pre-date the response code expect this behavior
8162// (Like Google Drive).
8163TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558164 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378165
8166 TestDelegate d;
tommycli59a63432015-11-06 00:10:558167 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378168
rhalavatib7bd7c792017-04-27 05:25:168169 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
8170 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378171
[email protected]f7022f32014-08-21 16:32:198172 request->Start();
[email protected]0a17aab32014-04-24 03:32:378173 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:508174 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378175 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198176 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378177 EXPECT_EQ("This is not a redirect.", d.data_received());
8178}
8179
[email protected]f878230e2014-04-03 15:36:148180TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558181 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148182
tommycli59a63432015-11-06 00:10:558183 GURL original_url(
8184 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8185 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148186
8187 TestDelegate d;
8188 {
rhalavatib7bd7c792017-04-27 05:25:168189 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8190 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148191
[email protected]f7022f32014-08-21 16:32:198192 r->Start();
[email protected]f878230e2014-04-03 15:36:148193 base::RunLoop().Run();
8194
[email protected]f7022f32014-08-21 16:32:198195 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508196 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198197 EXPECT_EQ(original_url, r->original_url());
8198 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148199 }
8200}
8201
[email protected]cba24642014-08-15 20:49:598202TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558203 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598204
tommycli59a63432015-11-06 00:10:558205 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598206 GURL first_party_url("http://example.com");
8207
8208 TestDelegate d;
8209 {
rhalavatib7bd7c792017-04-27 05:25:168210 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8211 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468212 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598213
[email protected]f7022f32014-08-21 16:32:198214 r->Start();
[email protected]cba24642014-08-15 20:49:598215 base::RunLoop().Run();
8216
[email protected]f7022f32014-08-21 16:32:198217 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508218 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468219 EXPECT_EQ(first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598220 }
8221}
8222
8223TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558224 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598225
tommycli59a63432015-11-06 00:10:558226 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598227 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558228 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598229
8230 TestDelegate d;
8231 {
rhalavatib7bd7c792017-04-27 05:25:168232 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8233 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468234 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198235 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598236 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8237
[email protected]f7022f32014-08-21 16:32:198238 r->Start();
[email protected]cba24642014-08-15 20:49:598239 base::RunLoop().Run();
8240
[email protected]f7022f32014-08-21 16:32:198241 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508242 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468243 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598244 }
8245}
8246
[email protected]316c1e5e2012-09-12 15:17:448247TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558248 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448249
8250 const char kData[] = "hello world";
8251
8252 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368253 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168254 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8255 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198256 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078257 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448258 HttpRequestHeaders headers;
8259 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:518260 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198261 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448262
danakj8522a25b2016-04-16 00:17:368263 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558264 req.get(), &default_network_delegate_,
8265 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428266 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8267 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448268
[email protected]f7022f32014-08-21 16:32:198269 req->Start();
[email protected]255620da2013-08-19 13:14:298270 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198271 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:448272}
8273
8274TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:558275 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448276
8277 const char kData[] = "hello world";
8278
8279 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368280 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168281 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8282 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198283 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078284 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448285 HttpRequestHeaders headers;
8286 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:518287 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198288 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448289
danakj8522a25b2016-04-16 00:17:368290 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558291 req.get(), &default_network_delegate_,
8292 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:098293 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:428294 "Very Good Reason"));
8295 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448296
[email protected]f7022f32014-08-21 16:32:198297 req->Start();
[email protected]255620da2013-08-19 13:14:298298 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198299 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:448300 EXPECT_EQ(kData, d.data_received());
8301}
8302
8303// Check that default A-L header is sent.
8304TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558305 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448306
[email protected]8790210c2013-12-02 05:29:538307 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:248308 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448309 TestURLRequestContext context(true);
8310 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:438311 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448312 context.Init();
8313
8314 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368315 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558316 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168317 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198318 req->Start();
[email protected]255620da2013-08-19 13:14:298319 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448320 EXPECT_EQ("en", d.data_received());
8321}
8322
8323// Check that an empty A-L header is not sent. http://crbug.com/77365.
8324TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558325 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448326
[email protected]8790210c2013-12-02 05:29:538327 std::string empty_string; // Avoid most vexing parse on line below.
8328 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:248329 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448330 TestURLRequestContext context(true);
8331 context.set_network_delegate(&network_delegate);
8332 context.Init();
8333 // We override the language after initialization because empty entries
8334 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:438335 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448336
8337 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368338 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558339 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168340 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198341 req->Start();
[email protected]255620da2013-08-19 13:14:298342 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448343 EXPECT_EQ("None", d.data_received());
8344}
8345
8346// Check that if request overrides the A-L header, the default is not appended.
8347// See http://crbug.com/20894
8348TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558349 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448350
8351 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368352 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558353 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168354 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448355 HttpRequestHeaders headers;
8356 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:198357 req->SetExtraRequestHeaders(headers);
8358 req->Start();
[email protected]255620da2013-08-19 13:14:298359 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448360 EXPECT_EQ(std::string("ru"), d.data_received());
8361}
8362
8363// Check that default A-E header is sent.
8364TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558365 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448366
8367 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368368 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558369 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168370 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448371 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:198372 req->SetExtraRequestHeaders(headers);
8373 req->Start();
[email protected]255620da2013-08-19 13:14:298374 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448375 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
8376}
8377
8378// Check that if request overrides the A-E header, the default is not appended.
8379// See http://crbug.com/47381
8380TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558381 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448382
8383 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368384 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558385 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168386 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448387 HttpRequestHeaders headers;
8388 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:198389 req->SetExtraRequestHeaders(headers);
8390 req->Start();
[email protected]255620da2013-08-19 13:14:298391 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448392 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
8393 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
8394}
8395
[email protected]84f05432013-03-15 01:00:128396// Check that setting the A-C header sends the proper header.
8397TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:558398 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448399
8400 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368401 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558402 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:168403 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448404 HttpRequestHeaders headers;
8405 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:198406 req->SetExtraRequestHeaders(headers);
8407 req->Start();
[email protected]255620da2013-08-19 13:14:298408 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448409 EXPECT_EQ(std::string("koi-8r"), d.data_received());
8410}
8411
8412// Check that default User-Agent header is sent.
8413TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:558414 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448415
8416 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368417 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558418 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168419 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198420 req->Start();
[email protected]255620da2013-08-19 13:14:298421 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198422 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:378423 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448424}
8425
8426// Check that if request overrides the User-Agent header,
8427// the default is not appended.
marqf14fff8d2015-12-02 15:52:298428// TODO(crbug.com/564656) This test is flaky on iOS.
8429#if defined(OS_IOS)
8430#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
8431#else
8432#define MAYBE_OverrideUserAgent OverrideUserAgent
8433#endif
8434TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:558435 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448436
8437 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368438 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558439 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168440 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448441 HttpRequestHeaders headers;
8442 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:198443 req->SetExtraRequestHeaders(headers);
8444 req->Start();
[email protected]255620da2013-08-19 13:14:298445 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:358446 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448447}
8448
[email protected]ee4c30d2012-11-07 15:08:438449// Check that a NULL HttpUserAgentSettings causes the corresponding empty
8450// User-Agent header to be sent but does not send the Accept-Language and
8451// Accept-Charset headers.
8452TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:558453 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:438454
[email protected]ceefd7fd2012-11-29 00:36:248455 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:438456 TestURLRequestContext context(true);
8457 context.set_network_delegate(&network_delegate);
8458 context.Init();
8459 // We override the HttpUserAgentSettings after initialization because empty
8460 // entries get overridden by Init().
8461 context.set_http_user_agent_settings(NULL);
8462
8463 struct {
8464 const char* request;
8465 const char* expected_response;
tommycli59a63432015-11-06 00:10:558466 } tests[] = {{"/echoheader?Accept-Language", "None"},
8467 {"/echoheader?Accept-Charset", "None"},
8468 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:438469
viettrungluue4a8b882014-10-16 06:17:388470 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:438471 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368472 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168473 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
8474 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198475 req->Start();
[email protected]255620da2013-08-19 13:14:298476 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:438477 EXPECT_EQ(tests[i].expected_response, d.data_received())
8478 << " Request = \"" << tests[i].request << "\"";
8479 }
8480}
8481
[email protected]5033ab82013-03-22 20:17:468482// Make sure that URLRequest passes on its priority updates to
8483// newly-created jobs after the first one.
8484TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:558485 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:468486
8487 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368488 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168489 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8490 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198491 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:468492
danakj8522a25b2016-04-16 00:17:368493 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558494 req.get(), &default_network_delegate_,
8495 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428496 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8497 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:468498
[email protected]f7022f32014-08-21 16:32:198499 req->SetPriority(LOW);
8500 req->Start();
8501 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:468502
mmenkeed0498b2015-12-08 23:20:428503 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:368504 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:428505 req.get(), &default_network_delegate_, &job_priority));
8506 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:468507
8508 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:298509 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:428510 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:468511}
8512
[email protected]80abdad2014-03-15 00:20:548513// Check that creating a network request while entering/exiting suspend mode
8514// fails as it should. This is the only case where an HttpTransactionFactory
8515// does not return an HttpTransaction.
8516TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
8517 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:368518 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:178519 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:548520 network_layer->OnSuspend();
8521
dchengc7eeda422015-12-26 03:56:488522 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:038523 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:278524 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:548525
8526 TestURLRequestContext context(true);
8527 context.set_http_transaction_factory(&http_cache);
8528 context.Init();
8529
8530 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368531 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:168532 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
8533 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198534 req->Start();
[email protected]80abdad2014-03-15 00:20:548535 base::RunLoop().Run();
8536
8537 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:508538 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:548539}
8540
mmenke2281f3762015-11-02 20:38:178541namespace {
[email protected]80abdad2014-03-15 00:20:548542
mmenke2281f3762015-11-02 20:38:178543// HttpTransactionFactory that synchronously fails to create transactions.
8544class FailingHttpTransactionFactory : public HttpTransactionFactory {
8545 public:
8546 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
8547 : network_session_(network_session) {}
8548
8549 ~FailingHttpTransactionFactory() override {}
8550
8551 // HttpTransactionFactory methods:
8552 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:368553 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:178554 return ERR_FAILED;
8555 }
8556
8557 HttpCache* GetCache() override { return nullptr; }
8558
8559 HttpNetworkSession* GetSession() override { return network_session_; }
8560
8561 private:
8562 HttpNetworkSession* network_session_;
8563
8564 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
8565};
8566
8567} // namespace
8568
8569// Check that when a request that fails to create an HttpTransaction can be
8570// cancelled while the failure notification is pending, and doesn't send two
8571// failure notifications.
8572//
8573// This currently only happens when in suspend mode and there's no cache, but
8574// just use a special HttpTransactionFactory, to avoid depending on those
8575// behaviors.
8576TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
8577 FailingHttpTransactionFactory http_transaction_factory(
8578 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:548579 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:178580 context.set_http_transaction_factory(&http_transaction_factory);
8581 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:548582 context.Init();
8583
8584 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368585 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:168586 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
8587 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:178588 // Don't send cookies (Collecting cookies is asynchronous, and need request to
8589 // try to create an HttpNetworkTransaction synchronously on start).
8590 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:198591 req->Start();
mmenke2281f3762015-11-02 20:38:178592 req->Cancel();
[email protected]80abdad2014-03-15 00:20:548593 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:178594 // Run pending error task, if there is one.
8595 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:548596
8597 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:178598 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:508599 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:178600
8601 // NetworkDelegate should see the cancellation, but not the error.
8602 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
8603 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:548604}
8605
ttuttlec0c828492015-05-15 01:25:558606TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:558607 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558608
8609 TestDelegate d;
tommycli59a63432015-11-06 00:10:558610 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:168611 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8612 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:558613
8614 req->Start();
8615 base::RunLoop().Run();
8616
8617 EXPECT_TRUE(req->response_info().network_accessed);
8618}
8619
8620TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:558621 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558622
8623 // Populate the cache.
8624 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368625 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168626 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
8627 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:558628 req->Start();
8629 base::RunLoop().Run();
8630
maksim.sisovb53724b52016-09-16 05:30:508631 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:558632 EXPECT_TRUE(req->response_info().network_accessed);
8633 EXPECT_FALSE(req->response_info().was_cached);
8634
tommycli59a63432015-11-06 00:10:558635 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
rhalavatib7bd7c792017-04-27 05:25:168636 DEFAULT_PRIORITY, &d,
8637 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:558638 req->Start();
8639 base::RunLoop().Run();
8640
maksim.sisovb53724b52016-09-16 05:30:508641 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:558642 EXPECT_FALSE(req->response_info().network_accessed);
8643 EXPECT_TRUE(req->response_info().was_cached);
8644}
8645
8646TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:558647 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558648
8649 TestDelegate d;
tommycli59a63432015-11-06 00:10:558650 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:168651 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8652 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:338653 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:558654
8655 req->Start();
8656 base::RunLoop().Run();
8657
8658 EXPECT_FALSE(req->response_info().network_accessed);
8659}
8660
rdsmithbf8c3c12016-11-18 18:16:248661// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:088662// correctly in the absence of contention.
8663TEST_F(URLRequestTestHTTP, ThrottledPriority) {
8664 ASSERT_TRUE(http_test_server()->Start());
8665
8666 TestDelegate d;
8667 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:168668 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8669 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:088670 req->Start();
8671 base::RunLoop().Run();
8672
8673 EXPECT_TRUE(req->status().is_success());
8674}
8675
rdsmithbf8c3c12016-11-18 18:16:248676// A class to hold state for responding to USER_NOTIFY callbacks from
8677// BlockingNetworkDelegate. It also accepts a RunLoop that will be
8678// signaled via QuitWhenIdle() when any request is blocked.
8679//
8680class NotificationCallbackHandler {
8681 public:
8682 // Default constructed object doesn't block anything.
8683 NotificationCallbackHandler() : run_loop_(nullptr) {}
8684
8685 void AddURLRequestToBlockList(const URLRequest* request) {
8686 requests_to_block_.insert(request);
8687 }
8688
8689 Error ShouldBlockRequest(const CompletionCallback& callback,
8690 const URLRequest* request) {
8691 if (requests_to_block_.find(request) == requests_to_block_.end()) {
8692 return OK;
8693 }
8694
8695 DCHECK(blocked_callbacks_.find(request) == blocked_callbacks_.end());
8696 blocked_callbacks_[request] = callback;
8697 if (run_loop_ && blocked_callbacks_.size() == requests_to_block_.size())
8698 run_loop_->QuitWhenIdle();
8699 return ERR_IO_PENDING;
8700 }
8701
8702 // Erases object's memory of blocked callbacks as a side effect.
8703 void GetBlockedCallbacks(
8704 std::map<const URLRequest*, CompletionCallback>* blocked_callbacks) {
8705 blocked_callbacks_.swap(*blocked_callbacks);
8706 }
8707
8708 // Set a RunLoop that, if non-null, will be signaled if any request
8709 // is blocked. It is the callers responsibility to make sure the
8710 // passed object lives past the destruction of this class or
8711 // next call to SetRunLoop().
8712 void SetRunLoop(base::RunLoop* run_loop) { run_loop_ = run_loop; }
8713
8714 private:
8715 std::set<const URLRequest*> requests_to_block_;
8716 std::map<const URLRequest*, CompletionCallback> blocked_callbacks_;
8717
8718 base::RunLoop* run_loop_;
8719
8720 DISALLOW_COPY_AND_ASSIGN(NotificationCallbackHandler);
8721};
8722
8723TEST_F(URLRequestTestHTTP, MultiThrottledPriority) {
8724 ASSERT_TRUE(http_test_server()->Start());
8725
8726 base::RunLoop run_until_request_blocked;
8727
8728 NotificationCallbackHandler notification_handler;
8729 notification_handler.SetRunLoop(&run_until_request_blocked);
8730 BlockingNetworkDelegate network_delegate(
8731 BlockingNetworkDelegate::USER_NOTIFY);
8732 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8733 network_delegate.set_notification_callback(
8734 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8735 // Both objects are owned by this function, and
8736 // |*network_delegate| will be destroyed first, so
8737 // it's safe to pass it an unretained pointer.
8738 base::Unretained(&notification_handler)));
8739
8740 TestURLRequestContext context(true);
8741 context.set_network_delegate(&network_delegate);
8742 context.Init();
8743
8744 // Use different test URLs to make sure all three requests turn into
8745 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8746 // the requests may be waited on separately.
8747 TestDelegate d1;
rhalavatib7bd7c792017-04-27 05:25:168748 std::unique_ptr<URLRequest> req1(
8749 context.CreateRequest(http_test_server()->GetURL("/echoall/l"), THROTTLED,
8750 &d1, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248751 notification_handler.AddURLRequestToBlockList(req1.get());
8752
8753 TestDelegate d2;
rhalavatib7bd7c792017-04-27 05:25:168754 std::unique_ptr<URLRequest> req2(
8755 context.CreateRequest(http_test_server()->GetURL("/echoall/2"), THROTTLED,
8756 &d2, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248757 notification_handler.AddURLRequestToBlockList(req2.get());
8758
8759 TestDelegate d3;
rhalavatib7bd7c792017-04-27 05:25:168760 std::unique_ptr<URLRequest> req3(
8761 context.CreateRequest(http_test_server()->GetURL("/echoall/3"), THROTTLED,
8762 &d3, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248763 req1->Start();
8764 req2->Start();
8765 req3->Start();
8766 run_until_request_blocked.Run();
8767 notification_handler.SetRunLoop(nullptr);
8768
8769 // The first two requests should be blocked based on the notification
8770 // callback, and their status should have blocked the third request
8771 // through throttling.
8772 EXPECT_TRUE(req1->status().is_io_pending());
8773 EXPECT_TRUE(req2->status().is_io_pending());
8774 EXPECT_TRUE(req3->status().is_io_pending());
8775
8776 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8777 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8778 ASSERT_EQ(2u, blocked_callbacks.size());
8779 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8780 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8781
8782 // Unblocking one of the requests blocked on the notification callback
8783 // should let it complete, which should then let the third request
8784 // complete. Unblock the second request, then wait for the third
8785 // request to complete.
8786 // TODO(rdsmith): Find something to wait on other than the third
8787 // requests completion; if there's a bug in throttling, that will
8788 // result in this test hanging rather than failing quickly.
8789 d1.set_quit_on_complete(false);
8790 d2.set_quit_on_complete(false);
8791 d3.set_quit_on_complete(true);
8792 blocked_callbacks[req2.get()].Run(OK);
8793 base::RunLoop().Run();
8794
8795 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8796 EXPECT_EQ(0u, blocked_callbacks.size());
8797 EXPECT_TRUE(req1->status().is_io_pending());
8798 // req3 is only unblocked after req2 completes, so req2's
8799 // success is guaranteed at this point in the function.
8800 EXPECT_EQ(URLRequestStatus::SUCCESS, req2->status().status());
8801 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8802}
8803
8804// Confirm that failing a request unblocks following requests.
8805TEST_F(URLRequestTestHTTP, ThrottledFailure) {
8806 ASSERT_TRUE(http_test_server()->Start());
8807
8808 base::RunLoop run_until_request_blocked;
8809
8810 NotificationCallbackHandler notification_handler;
8811 notification_handler.SetRunLoop(&run_until_request_blocked);
8812 BlockingNetworkDelegate network_delegate(
8813 BlockingNetworkDelegate::USER_NOTIFY);
8814 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8815 network_delegate.set_notification_callback(
8816 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8817 // Both objects are owned by this function, and
8818 // |*network_delegate| will be destroyed first, so
8819 // it's safe to pass it an unretained pointer.
8820 base::Unretained(&notification_handler)));
8821
8822 TestURLRequestContext context(true);
8823 context.set_network_delegate(&network_delegate);
8824 context.Init();
8825
8826 // Use different test URLs to make sure all three requests turn into
8827 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8828 // the requests may be waited on separately.
8829 TestDelegate d1;
rhalavatib7bd7c792017-04-27 05:25:168830 std::unique_ptr<URLRequest> req1(
8831 context.CreateRequest(http_test_server()->GetURL("/echoall/l"), THROTTLED,
8832 &d1, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248833 notification_handler.AddURLRequestToBlockList(req1.get());
8834
8835 TestDelegate d2;
rhalavatib7bd7c792017-04-27 05:25:168836 std::unique_ptr<URLRequest> req2(
8837 context.CreateRequest(http_test_server()->GetURL("/echoall/2"), THROTTLED,
8838 &d2, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248839 notification_handler.AddURLRequestToBlockList(req2.get());
8840
8841 TestDelegate d3;
rhalavatib7bd7c792017-04-27 05:25:168842 std::unique_ptr<URLRequest> req3(
8843 context.CreateRequest(http_test_server()->GetURL("/echoall/3"), THROTTLED,
8844 &d3, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248845 req1->Start();
8846 req2->Start();
8847 req3->Start();
8848 run_until_request_blocked.Run();
8849 notification_handler.SetRunLoop(nullptr);
8850
8851 // The first two requests should be blocked based on the notification
8852 // callback, and their status should have blocked the third request
8853 // through throttling.
8854 EXPECT_TRUE(req1->status().is_io_pending());
8855 EXPECT_TRUE(req2->status().is_io_pending());
8856 EXPECT_TRUE(req3->status().is_io_pending());
8857
8858 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8859 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8860 ASSERT_EQ(2u, blocked_callbacks.size());
8861 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8862 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8863
8864 // Confirm canceling one of the outstanding requests allows the
8865 // blocked request to complete.
8866
8867 // TODO(rdsmith): Find something to wait on other than the third
8868 // requests completion; if there's a bug in throttling, that will
8869 // result in this test hanging rather than failing quickly.
8870 d1.set_quit_on_complete(false);
8871 d2.set_quit_on_complete(false);
8872 d3.set_quit_on_complete(true);
8873 req2->Cancel();
8874 base::RunLoop().Run();
8875
8876 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8877 EXPECT_EQ(0u, blocked_callbacks.size());
8878 EXPECT_TRUE(req1->status().is_io_pending());
8879 EXPECT_EQ(URLRequestStatus::CANCELED, req2->status().status());
8880 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8881}
8882
8883TEST_F(URLRequestTestHTTP, ThrottledRepriUnblock) {
8884 ASSERT_TRUE(http_test_server()->Start());
8885
8886 base::RunLoop run_until_request_blocked;
8887
8888 NotificationCallbackHandler notification_handler;
8889 notification_handler.SetRunLoop(&run_until_request_blocked);
8890 BlockingNetworkDelegate network_delegate(
8891 BlockingNetworkDelegate::USER_NOTIFY);
8892 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8893 network_delegate.set_notification_callback(
8894 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8895 // Both objects are owned by this function, and
8896 // |*network_delegate| will be destroyed first, so
8897 // it's safe to pass it an unretained pointer.
8898 base::Unretained(&notification_handler)));
8899
8900 TestURLRequestContext context(true);
8901 context.set_network_delegate(&network_delegate);
8902 context.Init();
8903
8904 // Use different test URLs to make sure all three requests turn into
8905 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8906 // the requests may be waited on separately.
8907 TestDelegate d1;
rhalavatib7bd7c792017-04-27 05:25:168908 std::unique_ptr<URLRequest> req1(
8909 context.CreateRequest(http_test_server()->GetURL("/echoall/l"), THROTTLED,
8910 &d1, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248911 notification_handler.AddURLRequestToBlockList(req1.get());
8912
8913 TestDelegate d2;
rhalavatib7bd7c792017-04-27 05:25:168914 std::unique_ptr<URLRequest> req2(
8915 context.CreateRequest(http_test_server()->GetURL("/echoall/2"), THROTTLED,
8916 &d2, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248917 notification_handler.AddURLRequestToBlockList(req2.get());
8918
8919 TestDelegate d3;
rhalavatib7bd7c792017-04-27 05:25:168920 std::unique_ptr<URLRequest> req3(
8921 context.CreateRequest(http_test_server()->GetURL("/echoall/3"), THROTTLED,
8922 &d3, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmithbf8c3c12016-11-18 18:16:248923 req1->Start();
8924 req2->Start();
8925 req3->Start();
8926 run_until_request_blocked.Run();
8927 notification_handler.SetRunLoop(nullptr);
8928
8929 // The first two requests should be blocked based on the notification
8930 // callback, and their status should have blocked the third request
8931 // through throttling.
8932 EXPECT_TRUE(req1->status().is_io_pending());
8933 EXPECT_TRUE(req2->status().is_io_pending());
8934 EXPECT_TRUE(req3->status().is_io_pending());
8935
8936 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8937 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8938 ASSERT_EQ(2u, blocked_callbacks.size());
8939 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8940 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8941
8942 // Confirm raising the priority of the third request allows it to complete.
8943
8944 // TODO(rdsmith): Find something to wait on other than the third
8945 // requests completion; if there's a bug in throttling, that will
8946 // result in this test hanging rather than failing quickly.
8947 d1.set_quit_on_complete(false);
8948 d2.set_quit_on_complete(false);
8949 d3.set_quit_on_complete(true);
8950 req3->SetPriority(IDLE);
8951 base::RunLoop().Run();
8952
8953 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8954 EXPECT_EQ(0u, blocked_callbacks.size());
8955 EXPECT_TRUE(req1->status().is_io_pending());
8956 EXPECT_TRUE(req2->status().is_io_pending());
8957 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8958}
8959
ricea3a1c71f2016-06-17 10:05:268960TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
8961 ASSERT_TRUE(http_test_server()->Start());
8962
8963 TestDelegate d;
8964 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168965 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
8966 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:268967 req->Start();
8968 base::RunLoop().Run();
8969
8970 EXPECT_EQ(5, req->GetRawBodyBytes());
8971}
8972
8973TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
8974 ASSERT_TRUE(http_test_server()->Start());
8975
8976 TestDelegate d;
8977 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168978 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
8979 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:268980 req->Start();
8981 base::RunLoop().Run();
8982
8983 EXPECT_EQ(30, req->GetRawBodyBytes());
8984}
8985
jamd3f5a3c2016-10-27 18:52:028986// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
8987// the delegate isn't called back synchronously.
8988TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
8989 ASSERT_TRUE(http_test_server()->Start());
8990 default_network_delegate_.set_before_start_transaction_fails();
8991
8992 TestDelegate d;
8993 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168994 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
8995 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:028996 req->Start();
8997 DCHECK(!d.response_completed());
8998 base::RunLoop().Run();
8999 DCHECK(d.response_completed());
9000 EXPECT_EQ(ERR_FAILED, d.request_status());
9001}
9002
bengr1bf8e942014-11-07 01:36:509003class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9004 public:
9005 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9006 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9007 // tests into the factory tests.
9008 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
9009 }
9010
9011 void SetUpFactory() override {
9012 interceptor_ = new MockURLRequestInterceptor();
9013 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369014 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509015 }
9016
9017 MockURLRequestInterceptor* interceptor() const {
9018 return interceptor_;
9019 }
9020
9021 private:
9022 MockURLRequestInterceptor* interceptor_;
9023};
9024
9025TEST_F(URLRequestInterceptorTestHTTP,
9026 NetworkDelegateNotificationOnRedirectIntercept) {
9027 interceptor()->set_intercept_redirect(true);
9028 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9029 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9030
tommycli59a63432015-11-06 00:10:559031 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509032
9033 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369034 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169035 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9036 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509037 req->Start();
9038 base::RunLoop().Run();
9039
9040 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9041 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509042 int status = d.request_status();
9043 EXPECT_EQ(OK, status);
9044 if (status == OK)
bengr1bf8e942014-11-07 01:36:509045 EXPECT_EQ(200, req->response_headers()->response_code());
9046
9047 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9048 EXPECT_EQ(1, d.response_started_count());
9049 EXPECT_EQ(0, d.received_redirect_count());
9050
9051 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009052 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509053 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9054}
9055
9056TEST_F(URLRequestInterceptorTestHTTP,
9057 NetworkDelegateNotificationOnErrorIntercept) {
9058 // Intercept that error and respond with an OK response.
9059 interceptor()->set_intercept_final_response(true);
9060 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9061 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9062 default_network_delegate()->set_can_be_intercepted_on_error(true);
9063
tommycli59a63432015-11-06 00:10:559064 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509065
9066 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369067 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559068 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169069 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509070 req->set_method("GET");
9071 req->Start();
9072 base::RunLoop().Run();
9073
9074 EXPECT_TRUE(interceptor()->did_intercept_final());
9075
9076 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509077 int status = d.request_status();
9078 EXPECT_EQ(OK, status);
9079 if (status == OK)
bengr1bf8e942014-11-07 01:36:509080 EXPECT_EQ(200, req->response_headers()->response_code());
9081 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9082 EXPECT_EQ(1, d.response_started_count());
9083 EXPECT_EQ(0, d.received_redirect_count());
9084
9085 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009086 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509087 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9088}
9089
9090TEST_F(URLRequestInterceptorTestHTTP,
9091 NetworkDelegateNotificationOnResponseIntercept) {
9092 // Intercept that error and respond with an OK response.
9093 interceptor()->set_intercept_final_response(true);
9094
9095 // Intercept with a real URLRequestHttpJob.
9096 interceptor()->set_use_url_request_http_job(true);
9097
tommycli59a63432015-11-06 00:10:559098 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509099
9100 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369101 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169102 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9103 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509104 req->set_method("GET");
9105 req->Start();
9106 base::RunLoop().Run();
9107
9108 EXPECT_TRUE(interceptor()->did_intercept_final());
9109
9110 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509111 int status = d.request_status();
9112 EXPECT_EQ(OK, status);
9113 if (status == OK)
bengr1bf8e942014-11-07 01:36:509114 EXPECT_EQ(200, req->response_headers()->response_code());
9115 EXPECT_EQ("hello", d.data_received());
9116 EXPECT_EQ(1, d.response_started_count());
9117 EXPECT_EQ(0, d.received_redirect_count());
9118
9119 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009120 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509121 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9122}
9123
mkwst0c5eab872014-11-21 14:18:549124class URLRequestTestReferrerPolicy : public URLRequestTest {
9125 public:
9126 URLRequestTestReferrerPolicy() {}
9127
tommycli59a63432015-11-06 00:10:559128 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9129 origin_server_.reset(new EmbeddedTestServer(type));
9130 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9131 origin_server_->AddDefaultHandlers(
9132 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9133 } else {
9134 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9135 }
mkwst0c5eab872014-11-21 14:18:549136 ASSERT_TRUE(origin_server_->Start());
9137 }
9138
tommycli59a63432015-11-06 00:10:559139 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9140 net::EmbeddedTestServer::Type dest_type) {
9141 origin_server_.reset(new EmbeddedTestServer(origin_type));
9142 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9143 origin_server_->AddDefaultHandlers(
9144 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9145 } else {
9146 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9147 }
mkwst0c5eab872014-11-21 14:18:549148 ASSERT_TRUE(origin_server_->Start());
9149
tommycli59a63432015-11-06 00:10:559150 destination_server_.reset(new EmbeddedTestServer(dest_type));
9151 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9152 destination_server_->AddDefaultHandlers(
9153 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9154 } else {
9155 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9156 }
mkwst0c5eab872014-11-21 14:18:549157 ASSERT_TRUE(destination_server_->Start());
9158 }
9159
9160 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9161 const GURL& referrer,
9162 const GURL& expected) {
9163 // Create and execute the request: we'll only have a |destination_server_|
9164 // if the origins are meant to be distinct. Otherwise, we'll use the
9165 // |origin_server_| for both endpoints.
9166 GURL destination_url =
tommycli59a63432015-11-06 00:10:559167 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9168 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549169 GURL origin_url =
tommycli59a63432015-11-06 00:10:559170 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549171
9172 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:169173 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9174 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549175 req->set_referrer_policy(policy);
9176 req->SetReferrer(referrer.spec());
9177 req->Start();
9178 base::RunLoop().Run();
9179
9180 EXPECT_EQ(1, d.response_started_count());
9181 EXPECT_EQ(1, d.received_redirect_count());
9182 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509183 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549184 EXPECT_EQ(200, req->response_headers()->response_code());
9185
9186 EXPECT_EQ(expected.spec(), req->referrer());
9187 if (expected.is_empty())
9188 EXPECT_EQ("None", d.data_received());
9189 else
9190 EXPECT_EQ(expected.spec(), d.data_received());
9191 }
9192
tommycli59a63432015-11-06 00:10:559193 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549194
9195 private:
danakj8522a25b2016-04-16 00:17:369196 std::unique_ptr<EmbeddedTestServer> origin_server_;
9197 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549198};
9199
9200TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559201 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549202
estarkc8ccba82017-06-13 22:37:409203 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549204 VerifyReferrerAfterRedirect(
9205 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409206 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549207
9208 VerifyReferrerAfterRedirect(
9209 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409210 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549211
9212 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409213 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549214
estarkc8ccba82017-06-13 22:37:409215 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9216 referrer);
9217
9218 // The original referrer set on the request is expected to obey the referrer
9219 // policy and already be stripped to the origin; thus this test case just
9220 // checks that this policy doesn't cause the referrer to change when following
9221 // a redirect.
9222 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9223 referrer.GetOrigin());
9224
9225 VerifyReferrerAfterRedirect(
9226 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9227 referrer);
9228
9229 // The original referrer set on the request is expected to obey the referrer
9230 // policy and already be stripped to the origin; thus this test case just
9231 // checks that this policy doesn't cause the referrer to change when following
9232 // a redirect.
9233 VerifyReferrerAfterRedirect(
9234 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9235 referrer.GetOrigin(), referrer.GetOrigin());
9236
9237 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549238}
9239
tommycli59a63432015-11-06 00:10:559240TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9241 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9242 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409243 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549244
9245 VerifyReferrerAfterRedirect(
9246 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409247 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549248
9249 VerifyReferrerAfterRedirect(
9250 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409251 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549252
9253 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409254 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9255 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549256
estarkc8ccba82017-06-13 22:37:409257 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9258 referrer);
9259
9260 // The original referrer set on the request is expected to obey the referrer
9261 // policy and already be stripped to the origin; thus this test case just
9262 // checks that this policy doesn't cause the referrer to change when following
9263 // a redirect.
9264 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9265 referrer.GetOrigin());
9266
9267 VerifyReferrerAfterRedirect(
9268 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9269
9270 // The original referrer set on the request is expected to obey the referrer
9271 // policy and already be stripped to the origin; thus this test case just
9272 // checks that this policy doesn't cause the referrer to change when following
9273 // a redirect.
9274 VerifyReferrerAfterRedirect(
9275 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9276 referrer.GetOrigin(), referrer.GetOrigin());
9277
9278 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549279}
9280
9281TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559282 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409283 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549284
9285 VerifyReferrerAfterRedirect(
9286 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409287 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549288
9289 VerifyReferrerAfterRedirect(
9290 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409291 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549292
9293 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409294 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549295
estarkc8ccba82017-06-13 22:37:409296 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9297 referrer);
9298
9299 // The original referrer set on the request is expected to obey the referrer
9300 // policy and already be stripped to the origin; thus this test case just
9301 // checks that this policy doesn't cause the referrer to change when following
9302 // a redirect.
9303 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9304 referrer.GetOrigin());
9305
9306 VerifyReferrerAfterRedirect(
9307 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9308 referrer);
9309
9310 // The original referrer set on the request is expected to obey the referrer
9311 // policy and already be stripped to the origin; thus this test case just
9312 // checks that this policy doesn't cause the referrer to change when following
9313 // a redirect.
9314 VerifyReferrerAfterRedirect(
9315 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9316 referrer.GetOrigin(), referrer.GetOrigin());
9317
9318 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549319}
9320
tommycli59a63432015-11-06 00:10:559321TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
9322 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9323 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409324 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549325
9326 VerifyReferrerAfterRedirect(
9327 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409328 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549329
9330 VerifyReferrerAfterRedirect(
9331 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409332 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549333
9334 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409335 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559336 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549337
estarkc8ccba82017-06-13 22:37:409338 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9339 referrer);
9340
9341 // The original referrer set on the request is expected to obey the referrer
9342 // policy and already be stripped to the origin; thus this test case just
9343 // checks that this policy doesn't cause the referrer to change when following
9344 // a redirect.
9345 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9346 referrer.GetOrigin());
9347
9348 VerifyReferrerAfterRedirect(
9349 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9350
9351 // The original referrer set on the request is expected to obey the referrer
9352 // policy and already be stripped to the origin; thus this test case just
9353 // checks that this policy doesn't cause the referrer to change when following
9354 // a redirect.
9355 VerifyReferrerAfterRedirect(
9356 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9357 referrer.GetOrigin(), referrer.GetOrigin());
9358
9359 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549360}
9361
tommycli59a63432015-11-06 00:10:559362TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
9363 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9364 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409365 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549366
9367 VerifyReferrerAfterRedirect(
9368 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409369 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549370
9371 VerifyReferrerAfterRedirect(
9372 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409373 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549374
9375 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409376 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559377 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549378
estarkc8ccba82017-06-13 22:37:409379 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9380 referrer);
9381
9382 // The original referrer set on the request is expected to obey the referrer
9383 // policy and already be stripped to the origin; thus this test case just
9384 // checks that this policy doesn't cause the referrer to change when following
9385 // a redirect.
9386 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9387 referrer.GetOrigin());
9388
9389 VerifyReferrerAfterRedirect(
9390 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9391
9392 // The original referrer set on the request is expected to obey the referrer
9393 // policy and already be stripped to the origin; thus this test case just
9394 // checks that this policy doesn't cause the referrer to change when following
9395 // a redirect.
9396 VerifyReferrerAfterRedirect(
9397 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9398 referrer.GetOrigin(), referrer.GetOrigin());
9399
9400 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549401}
9402
tommycli59a63432015-11-06 00:10:559403TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
9404 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9405 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409406 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549407
9408 VerifyReferrerAfterRedirect(
9409 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409410 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549411
9412 VerifyReferrerAfterRedirect(
9413 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409414 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549415
9416 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409417 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559418 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549419
estarkc8ccba82017-06-13 22:37:409420 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9421 referrer);
9422
9423 // The original referrer set on the request is expected to obey the referrer
9424 // policy and already be stripped to the origin; thus this test case just
9425 // checks that this policy doesn't cause the referrer to change when following
9426 // a redirect.
9427 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9428 referrer.GetOrigin());
9429
9430 VerifyReferrerAfterRedirect(
9431 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9432
9433 // The original referrer set on the request is expected to obey the referrer
9434 // policy and already be stripped to the origin, though it should be
9435 // subsequently cleared during the downgrading redirect.
9436 VerifyReferrerAfterRedirect(
9437 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9438 referrer.GetOrigin(), GURL());
9439
9440 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549441}
9442
[email protected]73e0bba2009-02-19 22:57:099443class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:509444 public:
fdorayf33fede2017-05-11 21:18:109445 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:099446 default_context_.set_network_delegate(&default_network_delegate_);
9447 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:509448 }
dcheng67be2b1f2014-10-27 21:47:299449 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:509450
9451 protected:
[email protected]ceefd7fd2012-11-29 00:36:249452 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:099453 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:469454};
9455
[email protected]c044616e2013-02-20 02:01:269456TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:559457 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9458 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229459 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119460 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469461
[email protected]ea224582008-12-07 20:25:469462 TestDelegate d;
9463 {
danakj8522a25b2016-04-16 00:17:369464 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169465 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9466 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199467 r->Start();
9468 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469469
[email protected]255620da2013-08-19 13:14:299470 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:469471
9472 EXPECT_EQ(1, d.response_started_count());
9473 EXPECT_FALSE(d.received_data_before_response());
9474 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199475 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199476 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199477 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199478 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199479 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:469480 }
[email protected]ea224582008-12-07 20:25:469481}
9482
[email protected]5774ada2010-07-15 06:30:549483TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559484 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9485 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9486 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229487 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119488 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339489
9490 bool err_allowed = true;
9491 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9492 TestDelegate d;
9493 {
9494 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369495 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169496 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9497 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339498
[email protected]f7022f32014-08-21 16:32:199499 r->Start();
9500 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339501
[email protected]255620da2013-08-19 13:14:299502 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:339503
9504 EXPECT_EQ(1, d.response_started_count());
9505 EXPECT_FALSE(d.received_data_before_response());
9506 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179507 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339508 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199509 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179510 } else {
[email protected]bacff652009-03-31 17:50:339511 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179512 }
[email protected]bacff652009-03-31 17:50:339513 }
9514 }
9515}
9516
[email protected]5774ada2010-07-15 06:30:549517TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559518 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9519 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9520 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229521 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119522 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339523
9524 // Iterate from false to true, just so that we do the opposite of the
9525 // previous test in order to increase test coverage.
9526 bool err_allowed = false;
9527 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9528 TestDelegate d;
9529 {
9530 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369531 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169532 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9533 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339534
[email protected]f7022f32014-08-21 16:32:199535 r->Start();
9536 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339537
[email protected]255620da2013-08-19 13:14:299538 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:339539
9540 EXPECT_EQ(1, d.response_started_count());
9541 EXPECT_FALSE(d.received_data_before_response());
9542 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179543 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339544 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199545 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179546 } else {
[email protected]bacff652009-03-31 17:50:339547 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179548 }
[email protected]bacff652009-03-31 17:50:339549 }
9550 }
9551}
[email protected]73e0bba2009-02-19 22:57:099552
tommycli59a63432015-11-06 00:10:559553// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
9554// security state. (see http://crbug.com/550977).
9555#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:449556// This tests that a load of www.google.com with a certificate error sets
9557// the |certificate_errors_are_fatal| flag correctly. This flag will cause
9558// the interstitial to be fatal.
9559TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
xunjieli815ad5b2017-07-18 15:51:359560#if !BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
9561 SetTransportSecurityStateSourceForTesting(&test0::kHSTSSource);
9562#endif
tommycli59a63432015-11-06 00:10:559563 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9564 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9565 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449566 ASSERT_TRUE(test_server.Start());
9567
9568 // We require that the URL be www.google.com in order to pick up the
9569 // preloaded HSTS entries in the TransportSecurityState. This means that we
9570 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:249571 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449572
9573 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249574 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449575 TestURLRequestContext context(true);
9576 context.set_network_delegate(&network_delegate);
9577 context.set_host_resolver(&host_resolver);
9578 TransportSecurityState transport_security_state;
9579 context.set_transport_security_state(&transport_security_state);
9580 context.Init();
9581
9582 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369583 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199584 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:369585 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169586 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449587
[email protected]f7022f32014-08-21 16:32:199588 r->Start();
9589 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449590
[email protected]255620da2013-08-19 13:14:299591 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449592
9593 EXPECT_EQ(1, d.response_started_count());
9594 EXPECT_FALSE(d.received_data_before_response());
9595 EXPECT_TRUE(d.have_certificate_errors());
9596 EXPECT_TRUE(d.certificate_errors_are_fatal());
9597}
9598
9599// This tests that cached HTTPS page loads do not cause any updates to the
9600// TransportSecurityState.
9601TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
xunjieli815ad5b2017-07-18 15:51:359602#if !BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
9603 SetTransportSecurityStateSourceForTesting(&test0::kHSTSSource);
9604#endif
[email protected]316c1e5e2012-09-12 15:17:449605 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
9606 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:559607 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9608 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9609 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449610 ASSERT_TRUE(test_server.Start());
9611
[email protected]9e6968d2014-05-07 21:46:269612 // We require that the URL be www.google.com in order to pick up the static
9613 // and dynamic STS and PKP entries in the TransportSecurityState. This means
9614 // that we have to use a MockHostResolver in order to direct www.google.com to
9615 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449616
9617 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249618 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449619 TestURLRequestContext context(true);
9620 context.set_network_delegate(&network_delegate);
9621 context.set_host_resolver(&host_resolver);
9622 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:269623
martijnc0d6b622015-06-30 19:14:409624 TransportSecurityState::STSState static_sts_state;
9625 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269626 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:409627 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:449628 context.set_transport_security_state(&transport_security_state);
9629 context.Init();
9630
martijnc0d6b622015-06-30 19:14:409631 TransportSecurityState::STSState dynamic_sts_state;
9632 TransportSecurityState::PKPState dynamic_pkp_state;
9633 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
9634 &dynamic_sts_state));
9635 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
9636 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269637
[email protected]316c1e5e2012-09-12 15:17:449638 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369639 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199640 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:369641 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169642 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449643
[email protected]f7022f32014-08-21 16:32:199644 r->Start();
9645 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449646
[email protected]255620da2013-08-19 13:14:299647 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449648
9649 EXPECT_EQ(1, d.response_started_count());
9650 EXPECT_FALSE(d.received_data_before_response());
9651 EXPECT_TRUE(d.have_certificate_errors());
9652 EXPECT_TRUE(d.certificate_errors_are_fatal());
9653
[email protected]9e6968d2014-05-07 21:46:269654 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:409655 TransportSecurityState::STSState new_static_sts_state;
9656 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269657 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:409658 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
9659 TransportSecurityState::STSState new_dynamic_sts_state;
9660 TransportSecurityState::PKPState new_dynamic_pkp_state;
9661 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
9662 "www.google.com", &new_dynamic_sts_state));
9663 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
9664 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269665
martijnc0d6b622015-06-30 19:14:409666 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
9667 EXPECT_EQ(new_static_sts_state.include_subdomains,
9668 static_sts_state.include_subdomains);
9669 EXPECT_EQ(new_static_pkp_state.include_subdomains,
9670 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:489671 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
9672 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
9673 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:449674}
9675
[email protected]8ccc69f2012-11-28 19:52:149676// Make sure HSTS preserves a POST request's method and body.
9677TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
9678 static const char kData[] = "hello world";
9679
tommycli59a63432015-11-06 00:10:559680 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9681 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229682 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:149683 ASSERT_TRUE(test_server.Start());
9684
9685
9686 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9687 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:559688 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:229689 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:149690 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:149691
9692 // Force https for www.somewhere.com.
9693 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:209694 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
9695 bool include_subdomains = false;
9696 transport_security_state.AddHSTS("www.somewhere.com", expiry,
9697 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:149698
9699 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9700
9701 TestURLRequestContext context(true);
9702 context.set_host_resolver(&host_resolver);
9703 context.set_transport_security_state(&transport_security_state);
9704 context.set_network_delegate(&network_delegate);
9705 context.Init();
9706
9707 TestDelegate d;
9708 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
9709 // cause a certificate error. Ignore the error.
9710 d.set_allow_certificate_errors(true);
9711
danakj8522a25b2016-04-16 00:17:369712 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199713 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:369714 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169715 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199716 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079717 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:149718
[email protected]f7022f32014-08-21 16:32:199719 req->Start();
[email protected]255620da2013-08-19 13:14:299720 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:149721
[email protected]f7022f32014-08-21 16:32:199722 EXPECT_EQ("https", req->url().scheme());
9723 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:149724 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:409725
9726 LoadTimingInfo load_timing_info;
9727 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
9728 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
9729 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:149730}
9731
rob4e0be1f2014-09-11 23:40:229732// Make sure that the CORS headers are added to cross-origin HSTS redirects.
9733TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
9734 static const char kOriginHeaderValue[] = "http://www.example.com";
9735
tommycli59a63432015-11-06 00:10:559736 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9737 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:229738 ASSERT_TRUE(test_server.Start());
9739
9740 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9741 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:559742 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
9743 // default.
rob4e0be1f2014-09-11 23:40:229744 MockHostResolver host_resolver;
9745
9746 TransportSecurityState transport_security_state;
9747 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
9748 bool include_subdomains = false;
9749 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
9750
9751 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9752
9753 MockCertVerifier cert_verifier;
9754 cert_verifier.set_default_result(OK);
9755
9756 TestURLRequestContext context(true);
9757 context.set_host_resolver(&host_resolver);
9758 context.set_transport_security_state(&transport_security_state);
9759 context.set_network_delegate(&network_delegate);
9760 context.set_cert_verifier(&cert_verifier);
9761 context.Init();
9762
9763 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
9764 test_server.host_port_pair().port()));
9765 url::Replacements<char> replacements;
9766 const char kNewScheme[] = "https";
9767 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
9768 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
9769
9770 TestDelegate d;
9771 // Quit on redirect to allow response header inspection upon redirect.
9772 d.set_quit_on_redirect(true);
9773
rhalavatib7bd7c792017-04-27 05:25:169774 std::unique_ptr<URLRequest> req(context.CreateRequest(
9775 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:229776 // Set Origin header to simulate a cross-origin request.
9777 HttpRequestHeaders request_headers;
9778 request_headers.SetHeader("Origin", kOriginHeaderValue);
9779 req->SetExtraRequestHeaders(request_headers);
9780
9781 req->Start();
9782 base::RunLoop().Run();
9783
9784 EXPECT_EQ(1, d.received_redirect_count());
9785
9786 const HttpResponseHeaders* headers = req->response_headers();
9787 std::string redirect_location;
9788 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
9789 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
9790
9791 std::string received_cors_header;
9792 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
9793 &received_cors_header));
9794 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
9795}
9796
[email protected]316c1e5e2012-09-12 15:17:449797namespace {
9798
9799class SSLClientAuthTestDelegate : public TestDelegate {
9800 public:
9801 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
9802 }
dchengb03027d2014-10-21 12:00:209803 void OnCertificateRequested(URLRequest* request,
9804 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:449805 on_certificate_requested_count_++;
Gabriel Charette53a9ef812017-07-26 12:36:239806 base::RunLoop::QuitCurrentWhenIdleDeprecated();
[email protected]316c1e5e2012-09-12 15:17:449807 }
9808 int on_certificate_requested_count() {
9809 return on_certificate_requested_count_;
9810 }
9811 private:
9812 int on_certificate_requested_count_;
9813};
9814
9815} // namespace
9816
9817// TODO(davidben): Test the rest of the code. Specifically,
9818// - Filtering which certificates to select.
9819// - Sending a certificate back.
9820// - Getting a certificate request in an SSL renegotiation sending the
9821// HTTP request.
9822TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:559823 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9824 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:129825 ssl_config.client_cert_type =
9826 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
tommycli59a63432015-11-06 00:10:559827 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
9828 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229829 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449830 ASSERT_TRUE(test_server.Start());
9831
9832 SSLClientAuthTestDelegate d;
9833 {
danakj8522a25b2016-04-16 00:17:369834 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169835 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9836 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449837
[email protected]f7022f32014-08-21 16:32:199838 r->Start();
9839 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449840
[email protected]255620da2013-08-19 13:14:299841 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449842
9843 EXPECT_EQ(1, d.on_certificate_requested_count());
9844 EXPECT_FALSE(d.received_data_before_response());
9845 EXPECT_EQ(0, d.bytes_received());
9846
9847 // Send no certificate.
9848 // TODO(davidben): Get temporary client cert import (with keys) working on
9849 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:549850 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:449851
[email protected]255620da2013-08-19 13:14:299852 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449853
9854 EXPECT_EQ(1, d.response_started_count());
9855 EXPECT_FALSE(d.received_data_before_response());
9856 EXPECT_NE(0, d.bytes_received());
9857 }
9858}
9859
9860TEST_F(HTTPSRequestTest, ResumeTest) {
9861 // Test that we attempt a session resume when making two connections to the
9862 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:229863 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:449864 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:229865 SpawnedTestServer test_server(
9866 SpawnedTestServer::TYPE_HTTPS,
9867 ssl_options,
9868 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449869 ASSERT_TRUE(test_server.Start());
9870
9871 SSLClientSocket::ClearSessionCache();
9872
9873 {
9874 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369875 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169876 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9877 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449878
[email protected]f7022f32014-08-21 16:32:199879 r->Start();
9880 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449881
[email protected]255620da2013-08-19 13:14:299882 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449883
9884 EXPECT_EQ(1, d.response_started_count());
9885 }
9886
9887 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
9888 CloseAllConnections();
9889
9890 {
9891 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369892 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169893 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9894 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449895
[email protected]f7022f32014-08-21 16:32:199896 r->Start();
9897 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449898
[email protected]255620da2013-08-19 13:14:299899 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449900
9901 // The response will look like;
9902 // insert abc
9903 // lookup abc
9904 // insert xyz
9905 //
9906 // With a newline at the end which makes the split think that there are
9907 // four lines.
9908
9909 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:299910 std::vector<std::string> lines = base::SplitString(
9911 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:449912 ASSERT_EQ(4u, lines.size()) << d.data_received();
9913
9914 std::string session_id;
9915
9916 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:299917 std::vector<std::string> parts = base::SplitString(
9918 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:449919 ASSERT_EQ(2u, parts.size());
9920 if (i == 0) {
9921 EXPECT_EQ("insert", parts[0]);
9922 session_id = parts[1];
9923 } else {
9924 EXPECT_EQ("lookup", parts[0]);
9925 EXPECT_EQ(session_id, parts[1]);
9926 }
9927 }
9928 }
9929}
9930
Adam Langley32352ad2014-10-14 22:31:009931// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
9932// the result of fetching "ssl-session-cache" from the test server, indicates
9933// that exactly two different sessions were inserted, with no lookups etc.
9934static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:299935 std::vector<std::string> lines = base::SplitString(
9936 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:009937 ASSERT_EQ(3u, lines.size()) << session_info;
9938
9939 std::string session_id;
9940 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:299941 std::vector<std::string> parts = base::SplitString(
9942 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:009943 ASSERT_EQ(2u, parts.size());
9944 EXPECT_EQ("insert", parts[0]);
9945 if (i == 0) {
9946 session_id = parts[1];
9947 } else {
9948 EXPECT_NE(session_id, parts[1]);
9949 }
9950 }
9951}
9952
[email protected]316c1e5e2012-09-12 15:17:449953TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
9954 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
9955 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:229956 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:449957 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:229958 SpawnedTestServer test_server(
9959 SpawnedTestServer::TYPE_HTTPS,
9960 ssl_options,
9961 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449962 ASSERT_TRUE(test_server.Start());
9963
9964 SSLClientSocket::ClearSessionCache();
9965
9966 {
9967 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369968 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169969 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9970 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449971
[email protected]f7022f32014-08-21 16:32:199972 r->Start();
9973 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449974
[email protected]255620da2013-08-19 13:14:299975 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449976
9977 EXPECT_EQ(1, d.response_started_count());
9978 }
9979
9980 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:419981 HttpNetworkSession::Context session_context;
9982 session_context.host_resolver = default_context_.host_resolver();
9983 session_context.cert_verifier = default_context_.cert_verifier();
9984 session_context.transport_security_state =
9985 default_context_.transport_security_state();
9986 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:209987 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:419988 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
9989 session_context.proxy_service = default_context_.proxy_service();
9990 session_context.ssl_config_service = default_context_.ssl_config_service();
9991 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:449992 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:419993 session_context.http_server_properties =
9994 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:449995
mmenke6ddfbea2017-05-31 21:48:419996 HttpNetworkSession network_session(HttpNetworkSession::Params(),
9997 session_context);
zhongyi4928bd52017-02-08 02:16:279998 std::unique_ptr<HttpCache> cache(
9999 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
10000 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4410001
10002 default_context_.set_http_transaction_factory(cache.get());
10003
10004 {
10005 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610006 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610007 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10008 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410009
[email protected]f7022f32014-08-21 16:32:1910010 r->Start();
10011 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410012
[email protected]255620da2013-08-19 13:14:2910013 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410014
10015 // The response will look like;
10016 // insert abc
10017 // insert xyz
10018 //
10019 // With a newline at the end which makes the split think that there are
10020 // three lines.
10021
10022 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010023 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:4410024 }
10025}
10026
[email protected]48d2b7c52014-06-27 01:16:5510027class HTTPSFallbackTest : public testing::Test {
10028 public:
fdorayf33fede2017-05-11 21:18:1010029 HTTPSFallbackTest() : context_(true) {
davidben095ebb52017-04-12 22:23:3410030 ssl_config_service_ = new TestSSLConfigService(
10031 true /* check for EV */, false /* online revocation checking */,
10032 false /* require rev. checking for local anchors */,
10033 false /* token binding enabled */);
10034 context_.set_ssl_config_service(ssl_config_service_.get());
10035 }
dcheng67be2b1f2014-10-27 21:47:2910036 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:5510037
10038 protected:
davidben095ebb52017-04-12 22:23:3410039 TestSSLConfigService* ssl_config_service() {
10040 return ssl_config_service_.get();
10041 }
10042
[email protected]48d2b7c52014-06-27 01:16:5510043 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
10044 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0010045 context_.Init();
10046 delegate_.set_allow_certificate_errors(true);
10047
[email protected]48d2b7c52014-06-27 01:16:5510048 SpawnedTestServer test_server(
10049 SpawnedTestServer::TYPE_HTTPS,
10050 ssl_options,
10051 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10052 ASSERT_TRUE(test_server.Start());
10053
tommycli59a63432015-11-06 00:10:5510054 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1610055 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5510056 request_->Start();
10057
10058 base::RunLoop().Run();
10059 }
10060
davidben095ebb52017-04-12 22:23:3410061 void ExpectConnection(int version) {
10062 EXPECT_EQ(1, delegate_.response_started_count());
10063 EXPECT_NE(0, delegate_.bytes_received());
10064 EXPECT_EQ(version, SSLConnectionStatusToVersion(
10065 request_->ssl_info().connection_status));
10066 }
10067
[email protected]48d2b7c52014-06-27 01:16:5510068 void ExpectFailure(int error) {
10069 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5010070 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5510071 }
10072
10073 private:
10074 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4710075 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610076 std::unique_ptr<URLRequest> request_;
davidben095ebb52017-04-12 22:23:3410077 scoped_refptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5510078};
10079
davidbenb127ca82015-06-15 19:05:4210080// Tests the TLS 1.0 fallback doesn't happen.
10081TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5510082 SpawnedTestServer::SSLOptions ssl_options(
10083 SpawnedTestServer::SSLOptions::CERT_OK);
10084 ssl_options.tls_intolerant =
10085 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
10086
10087 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5510088 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4210089}
10090
davidben5a312152016-06-27 22:11:4710091// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5510092TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4210093 SpawnedTestServer::SSLOptions ssl_options(
10094 SpawnedTestServer::SSLOptions::CERT_OK);
10095 ssl_options.tls_intolerant =
10096 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
10097
10098 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5510099 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
10100}
10101
davidben095ebb52017-04-12 22:23:3410102// Tests that TLS 1.3 interference results in a dedicated error code.
10103TEST_F(HTTPSFallbackTest, TLSv1_3Interference) {
10104 SpawnedTestServer::SSLOptions ssl_options(
10105 SpawnedTestServer::SSLOptions::CERT_OK);
10106 ssl_options.tls_intolerant =
10107 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10108 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
10109
10110 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10111 ExpectFailure(ERR_SSL_VERSION_INTERFERENCE);
10112}
10113
10114// Tests that disabling TLS 1.3 leaves TLS 1.3 interference unnoticed.
10115TEST_F(HTTPSFallbackTest, TLSv1_3InterferenceDisableVersion) {
10116 SpawnedTestServer::SSLOptions ssl_options(
10117 SpawnedTestServer::SSLOptions::CERT_OK);
10118 ssl_options.tls_intolerant =
10119 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10120 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_2);
10121
10122 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10123 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_2);
10124}
10125
[email protected]a8fed1742013-12-27 02:14:2410126class HTTPSSessionTest : public testing::Test {
10127 public:
fdorayf33fede2017-05-11 21:18:1010128 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5910129 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410130
10131 default_context_.set_network_delegate(&default_network_delegate_);
10132 default_context_.set_cert_verifier(&cert_verifier_);
10133 default_context_.Init();
10134 }
dcheng67be2b1f2014-10-27 21:47:2910135 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:2410136
10137 protected:
10138 MockCertVerifier cert_verifier_;
10139 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
10140 TestURLRequestContext default_context_;
10141};
10142
10143// Tests that session resumption is not attempted if an invalid certificate
10144// is presented.
10145TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
10146 SpawnedTestServer::SSLOptions ssl_options;
10147 ssl_options.record_resume = true;
10148 SpawnedTestServer test_server(
10149 SpawnedTestServer::TYPE_HTTPS,
10150 ssl_options,
10151 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10152 ASSERT_TRUE(test_server.Start());
10153
10154 SSLClientSocket::ClearSessionCache();
10155
10156 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5910157 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2410158 {
10159 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610160 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610161 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10162 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410163
[email protected]f7022f32014-08-21 16:32:1910164 r->Start();
10165 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410166
10167 base::RunLoop().Run();
10168
10169 EXPECT_EQ(1, d.response_started_count());
10170 }
10171
10172 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10173 CloseAllConnections();
10174
10175 // Now change the certificate to be acceptable (so that the response is
10176 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910177 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410178 {
10179 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610180 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610181 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10182 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410183
[email protected]f7022f32014-08-21 16:32:1910184 r->Start();
10185 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410186
10187 base::RunLoop().Run();
10188
10189 // The response will look like;
10190 // insert abc
10191 // insert xyz
10192 //
10193 // With a newline at the end which makes the split think that there are
10194 // three lines.
10195 //
10196 // If a session was presented (eg: a bug), then the response would look
10197 // like;
10198 // insert abc
10199 // lookup abc
10200 // insert xyz
10201
10202 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010203 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:2410204 }
10205}
10206
[email protected]dffe8242012-03-20 15:14:2710207// This the fingerprint of the "Testing CA" certificate used by the testserver.
10208// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5810209static const SHA256HashValue kOCSPTestCertFingerprint = {{
10210 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
10211 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
10212 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1510213}};
[email protected]dffe8242012-03-20 15:14:2710214
[email protected]51523f52013-07-31 21:57:2810215// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
10216// testserver.
mattm0b12a6f2016-11-29 19:57:1610217static const SHA256HashValue kOCSPTestCertSPKI = {{
10218 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
10219 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
10220 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
10221}};
[email protected]51523f52013-07-31 21:57:2810222
[email protected]dffe8242012-03-20 15:14:2710223// This is the policy OID contained in the certificates that testserver
10224// generates.
10225static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
10226
10227class HTTPSOCSPTest : public HTTPSRequestTest {
10228 public:
10229 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0910230 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0810231 ev_test_policy_(
10232 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
10233 kOCSPTestCertFingerprint,
10234 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0210235 }
10236
dcheng67be2b1f2014-10-27 21:47:2910237 void SetUp() override {
rsleevid6de8302016-06-21 01:33:2010238 context_.SetCTPolicyEnforcer(
Jeremy Roman0579ed62017-08-29 15:56:1910239 std::make_unique<AllowAnyCertCTPolicyEnforcer>());
rsleevid6de8302016-06-21 01:33:2010240 SetupContext();
[email protected]ef2bf422012-05-11 03:27:0910241 context_.Init();
[email protected]dffe8242012-03-20 15:14:2710242
[email protected]cba24642014-08-15 20:49:5910243 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2010244 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:4210245 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:5010246 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2710247
svaldez2135be52016-04-20 16:34:5310248#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0910249 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2710250 EnsureNSSHttpIOInit();
10251#endif
10252 }
10253
dadrian612337a2016-07-20 22:36:5810254 void DoConnectionWithDelegate(
10255 const SpawnedTestServer::SSLOptions& ssl_options,
10256 TestDelegate* delegate,
10257 SSLInfo* out_ssl_info) {
10258 // Always overwrite |out_ssl_info|.
10259 out_ssl_info->Reset();
10260
[email protected]ce7d0cbc2013-05-03 18:57:2210261 SpawnedTestServer test_server(
10262 SpawnedTestServer::TYPE_HTTPS,
10263 ssl_options,
10264 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2710265 ASSERT_TRUE(test_server.Start());
10266
dadrian612337a2016-07-20 22:36:5810267 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1610268 std::unique_ptr<URLRequest> r(
10269 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
10270 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910271 r->Start();
[email protected]dffe8242012-03-20 15:14:2710272
[email protected]255620da2013-08-19 13:14:2910273 base::RunLoop().Run();
dadrian612337a2016-07-20 22:36:5810274 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2710275
dadrian612337a2016-07-20 22:36:5810276 *out_ssl_info = r->ssl_info();
10277 }
10278
10279 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
10280 CertStatus* out_cert_status) {
10281 // Always overwrite |out_cert_status|.
10282 *out_cert_status = 0;
10283
10284 TestDelegate d;
10285 SSLInfo ssl_info;
10286 ASSERT_NO_FATAL_FAILURE(
10287 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
10288
10289 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2710290 }
10291
dcheng67be2b1f2014-10-27 21:47:2910292 ~HTTPSOCSPTest() override {
svaldez2135be52016-04-20 16:34:5310293#if defined(USE_NSS_CERTS)
[email protected]dffe8242012-03-20 15:14:2710294 ShutdownNSSHttpIO();
10295#endif
10296 }
10297
[email protected]a13234c2012-03-20 21:45:0210298 protected:
rsleevid6de8302016-06-21 01:33:2010299 class AllowAnyCertCTPolicyEnforcer : public CTPolicyEnforcer {
10300 public:
10301 AllowAnyCertCTPolicyEnforcer() = default;
10302 ~AllowAnyCertCTPolicyEnforcer() override = default;
10303
10304 ct::CertPolicyCompliance DoesConformToCertPolicy(
10305 X509Certificate* cert,
10306 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:2010307 const NetLogWithSource& net_log) override {
rsleevid6de8302016-06-21 01:33:2010308 return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS;
10309 }
rsleevid6de8302016-06-21 01:33:2010310 };
[email protected]a13234c2012-03-20 21:45:0210311 // SetupContext configures the URLRequestContext that will be used for making
10312 // connetions to testserver. This can be overridden in test subclasses for
10313 // different behaviour.
rsleevid6de8302016-06-21 01:33:2010314 virtual void SetupContext() {
10315 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1410316 true /* check for EV */, true /* online revocation checking */,
10317 false /* require rev. checking for local
10318 anchors */,
10319 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0210320 }
10321
danakj8522a25b2016-04-16 00:17:3610322 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:0910323 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610324 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2710325};
10326
[email protected]a13234c2012-03-20 21:45:0210327static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2010328#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0210329 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
10330 // have that ability on other platforms.
10331 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
10332#else
10333 return 0;
10334#endif
10335}
10336
[email protected]3a86a712013-07-30 07:16:2010337// SystemSupportsHardFailRevocationChecking returns true iff the current
10338// operating system supports revocation checking and can distinguish between
10339// situations where a given certificate lacks any revocation information (eg:
10340// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
10341// revocation information cannot be obtained (eg: the CRL was unreachable).
10342// If it does not, then tests which rely on 'hard fail' behaviour should be
10343// skipped.
10344static bool SystemSupportsHardFailRevocationChecking() {
svaldez2135be52016-04-20 16:34:5310345#if defined(OS_WIN) || defined(USE_NSS_CERTS)
[email protected]3a86a712013-07-30 07:16:2010346 return true;
10347#else
10348 return false;
10349#endif
10350}
10351
[email protected]a13234c2012-03-20 21:45:0210352// SystemUsesChromiumEVMetadata returns true iff the current operating system
10353// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
10354// several tests are effected because our testing EV certificate won't be
10355// recognised as EV.
10356static bool SystemUsesChromiumEVMetadata() {
davidben965721b2017-05-03 19:40:3110357#if defined(OS_ANDROID)
mattm1a282f52016-11-10 21:49:4210358 // On Android, we use the system to tell us whether a certificate is EV or not
10359 // and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:0110360 return false;
10361#else
10362 return true;
10363#endif
10364}
10365
mattmaf868e72016-09-23 23:25:2010366// Returns the expected CertStatus for tests that expect an online revocation
10367// check failure as a result of checking a test EV cert, which will not
10368// actually trigger an online revocation check on some platforms.
10369static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
10370 if (SystemUsesChromiumEVMetadata()) {
10371 return ExpectedCertStatusForFailedOnlineRevocationCheck();
10372 } else {
10373 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
10374 // be enabled, and thus there will not be a revocation check to fail.
10375 return 0u;
10376 }
10377}
10378
[email protected]b6f2de32012-08-17 04:35:0810379static bool SystemSupportsOCSP() {
Sergey Ulanov884169a02017-09-06 18:58:0210380#if defined(OS_ANDROID) || defined(OS_FUCHSIA)
[email protected]a13234c2012-03-20 21:45:0210381 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
Sergey Ulanov884169a02017-09-06 18:58:0210382 // TODO(crbug.com/762380): Enable on Fuchsia once it's implemented.
[email protected]a13234c2012-03-20 21:45:0210383 return false;
10384#else
10385 return true;
10386#endif
10387}
10388
davidbend1fb2f12014-11-08 02:51:0010389static bool SystemSupportsOCSPStapling() {
davidben7ee23542016-06-03 18:27:3310390#if defined(USE_NSS_CERTS) || defined(OS_WIN)
mathpc992e602015-10-21 20:34:0310391 return true;
mathpc992e602015-10-21 20:34:0310392#else
10393 return false;
10394#endif
davidbend1fb2f12014-11-08 02:51:0010395}
10396
[email protected]dffe8242012-03-20 15:14:2710397TEST_F(HTTPSOCSPTest, Valid) {
10398 if (!SystemSupportsOCSP()) {
10399 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10400 return;
10401 }
10402
[email protected]ce7d0cbc2013-05-03 18:57:2210403 SpawnedTestServer::SSLOptions ssl_options(
10404 SpawnedTestServer::SSLOptions::CERT_AUTO);
10405 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2710406
[email protected]924e9f92012-12-16 22:00:5310407 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210408 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710409
10410 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10411
[email protected]a13234c2012-03-20 21:45:0210412 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10413 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2710414
10415 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10416}
10417
10418TEST_F(HTTPSOCSPTest, Revoked) {
10419 if (!SystemSupportsOCSP()) {
10420 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10421 return;
10422 }
10423
[email protected]ce7d0cbc2013-05-03 18:57:2210424 SpawnedTestServer::SSLOptions ssl_options(
10425 SpawnedTestServer::SSLOptions::CERT_AUTO);
10426 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2710427
10428 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210429 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710430
[email protected]dffe8242012-03-20 15:14:2710431 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2710432 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10433 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10434}
10435
10436TEST_F(HTTPSOCSPTest, Invalid) {
10437 if (!SystemSupportsOCSP()) {
10438 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10439 return;
10440 }
10441
[email protected]ce7d0cbc2013-05-03 18:57:2210442 SpawnedTestServer::SSLOptions ssl_options(
10443 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810444 ssl_options.ocsp_status =
10445 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2710446
[email protected]924e9f92012-12-16 22:00:5310447 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210448 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710449
[email protected]a13234c2012-03-20 21:45:0210450 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2710451 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2710452
10453 // Without a positive OCSP response, we shouldn't show the EV status.
10454 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10455 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10456}
[email protected]a13234c2012-03-20 21:45:0210457
davidbend1fb2f12014-11-08 02:51:0010458TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0310459 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0010460 LOG(WARNING)
10461 << "Skipping test because system doesn't support OCSP stapling";
10462 return;
10463 }
10464
10465 SpawnedTestServer::SSLOptions ssl_options(
10466 SpawnedTestServer::SSLOptions::CERT_AUTO);
10467 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10468 ssl_options.staple_ocsp_response = true;
10469 ssl_options.ocsp_server_unavailable = true;
10470
10471 CertStatus cert_status;
10472 DoConnection(ssl_options, &cert_status);
10473
10474 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10475
10476 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10477 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10478
10479 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10480}
10481
davidben6c3191b2014-11-21 22:38:0410482// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4810483#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0410484#define MAYBE_RevokedStapled DISABLED_RevokedStapled
10485#else
10486#define MAYBE_RevokedStapled RevokedStapled
10487#endif
10488TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0310489 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0010490 LOG(WARNING)
10491 << "Skipping test because system doesn't support OCSP stapling";
10492 return;
10493 }
10494
10495 SpawnedTestServer::SSLOptions ssl_options(
10496 SpawnedTestServer::SSLOptions::CERT_AUTO);
10497 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
10498 ssl_options.staple_ocsp_response = true;
10499 ssl_options.ocsp_server_unavailable = true;
10500
10501 CertStatus cert_status;
10502 DoConnection(ssl_options, &cert_status);
10503
10504 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10505 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10506 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10507}
10508
dadriand476e652016-07-26 21:33:2410509TEST_F(HTTPSOCSPTest, ExpectStapleReportSentOnMissing) {
xunjieli815ad5b2017-07-18 15:51:3510510#if !BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
10511 SetTransportSecurityStateSourceForTesting(&test0::kHSTSSource);
10512#endif
dadriand476e652016-07-26 21:33:2410513 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10514 https_test_server.SetSSLConfig(
10515 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10516 https_test_server.ServeFilesFromSourceDirectory(
10517 base::FilePath(kTestFilePath));
10518 ASSERT_TRUE(https_test_server.Start());
10519
10520 // Set up a MockCertVerifier to accept the certificate that the server sends,
10521 // but not provide any OCSP information.
10522 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10523 ASSERT_TRUE(cert);
10524 MockCertVerifier cert_verifier;
10525 CertVerifyResult verify_result;
10526 verify_result.verified_cert = cert;
10527 verify_result.is_issued_by_known_root = true;
10528 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
10529 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
10530
10531 // Catch the Expect-Staple report.
10532 TransportSecurityState transport_security_state;
10533 MockCertificateReportSender mock_report_sender;
10534 transport_security_state.SetReportSender(&mock_report_sender);
10535
10536 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
10537 // that the request can be sent to a site on the Expect-Staple preload list.
10538 MockHostResolver host_resolver;
10539 TestNetworkDelegate network_delegate;
10540 TestURLRequestContext context(true);
10541 context.set_host_resolver(&host_resolver);
10542 context.set_transport_security_state(&transport_security_state);
10543 context.set_network_delegate(&network_delegate);
10544 context.set_cert_verifier(&cert_verifier);
10545 context.Init();
10546
10547 // Now send a request to trigger the violation.
10548 TestDelegate d;
10549 GURL url = https_test_server.GetURL("/");
10550 GURL::Replacements replace_host;
10551 replace_host.SetHostStr(kExpectStapleStaticHostname);
10552 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610553 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
10554 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2410555 violating_request->Start();
10556 base::RunLoop().Run();
10557
10558 // Confirm a report was sent.
10559 EXPECT_FALSE(mock_report_sender.latest_report().empty());
10560 EXPECT_EQ(GURL(kExpectStapleReportURI),
10561 mock_report_sender.latest_report_uri());
10562}
10563
estark13e0b312016-12-22 23:52:3210564// Tests that Expect-Staple reports are not sent for connections on which there
10565// is a certificate error.
10566TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnMissingWithCertError) {
10567 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10568 https_test_server.SetSSLConfig(
10569 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10570 https_test_server.ServeFilesFromSourceDirectory(
10571 base::FilePath(kTestFilePath));
10572 ASSERT_TRUE(https_test_server.Start());
10573
10574 // Set up a MockCertVerifier to report an error for the certificate
10575 // and indicate that there was no stapled OCSP response.
10576 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10577 ASSERT_TRUE(cert);
10578 MockCertVerifier cert_verifier;
10579 CertVerifyResult verify_result;
10580 verify_result.cert_status = CERT_STATUS_DATE_INVALID;
10581 verify_result.verified_cert = cert;
10582 verify_result.is_issued_by_known_root = true;
10583 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
10584 cert_verifier.AddResultForCert(cert.get(), verify_result,
10585 ERR_CERT_DATE_INVALID);
10586
10587 // Set up a mock report sender so that the test can check that an
10588 // Expect-Staple report is not sent.
10589 TransportSecurityState transport_security_state;
10590 MockCertificateReportSender mock_report_sender;
10591 transport_security_state.SetReportSender(&mock_report_sender);
10592
10593 TestNetworkDelegate network_delegate;
10594 TestURLRequestContext context(true);
10595
10596 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
10597 MockHostResolver host_resolver;
10598 context.set_host_resolver(&host_resolver);
10599
10600 context.set_transport_security_state(&transport_security_state);
10601 context.set_network_delegate(&network_delegate);
10602 context.set_cert_verifier(&cert_verifier);
10603 context.Init();
10604
10605 // Make a connection to |kExpectStapleStaticHostname|. Because the
10606 // |verify_result| used with the |cert_verifier| will indicate a certificate
10607 // error, an Expect-Staple report should not be sent.
10608 TestDelegate d;
10609 GURL url = https_test_server.GetURL("/");
10610 GURL::Replacements replace_host;
10611 replace_host.SetHostStr(kExpectStapleStaticHostname);
10612 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610613 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
10614 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3210615 violating_request->Start();
10616 base::RunLoop().Run();
10617
10618 // Confirm a report was not sent.
10619 EXPECT_TRUE(mock_report_sender.latest_report().empty());
10620 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
10621}
10622
dadriand476e652016-07-26 21:33:2410623TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnValid) {
10624 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10625 https_test_server.SetSSLConfig(
10626 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10627 https_test_server.ServeFilesFromSourceDirectory(
10628 base::FilePath(kTestFilePath));
10629 ASSERT_TRUE(https_test_server.Start());
10630
10631 // Set up a MockCertVerifier to accept the certificate that the server sends,
10632 // and provide GOOD revocation status.
10633 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10634 ASSERT_TRUE(cert);
10635 MockCertVerifier cert_verifier;
10636 CertVerifyResult verify_result;
10637 verify_result.verified_cert = cert;
10638 verify_result.is_issued_by_known_root = true;
10639 verify_result.ocsp_result.response_status = OCSPVerifyResult::PROVIDED;
10640 verify_result.ocsp_result.revocation_status = OCSPRevocationStatus::GOOD;
10641 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
10642
10643 // Catch the Expect-Staple report.
10644 TransportSecurityState transport_security_state;
10645 MockCertificateReportSender mock_report_sender;
10646 transport_security_state.SetReportSender(&mock_report_sender);
10647
10648 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
10649 // that the request can be sent to a site on the Expect-Staple preload list.
10650 MockHostResolver host_resolver;
10651 TestNetworkDelegate network_delegate;
10652 TestURLRequestContext context(true);
10653 context.set_host_resolver(&host_resolver);
10654 context.set_transport_security_state(&transport_security_state);
10655 context.set_network_delegate(&network_delegate);
10656 context.set_cert_verifier(&cert_verifier);
10657 context.Init();
10658
10659 // This request should not not trigger an Expect-Staple violation.
10660 TestDelegate d;
10661 GURL url = https_test_server.GetURL("/");
10662 GURL::Replacements replace_host;
10663 replace_host.SetHostStr(kExpectStapleStaticHostname);
10664 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610665 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
10666 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2410667 ok_request->Start();
10668 base::RunLoop().Run();
10669
10670 // Check that no report was sent.
10671 EXPECT_TRUE(mock_report_sender.latest_report().empty());
10672 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
10673}
10674
estark13e0b312016-12-22 23:52:3210675// Tests that an Expect-Staple report is not sent when OCSP details are not
10676// checked on the connection.
10677TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnNotChecked) {
10678 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10679 https_test_server.SetSSLConfig(
10680 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10681 https_test_server.ServeFilesFromSourceDirectory(
10682 base::FilePath(kTestFilePath));
10683 ASSERT_TRUE(https_test_server.Start());
10684
10685 // Set up a MockCertVerifier to accept the certificate that the server sends,
10686 // and set |ocsp_result| to indicate that OCSP stapling details were not
10687 // checked on the connection.
10688 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10689 ASSERT_TRUE(cert);
10690 MockCertVerifier cert_verifier;
10691 CertVerifyResult verify_result;
10692 verify_result.verified_cert = cert;
10693 verify_result.is_issued_by_known_root = true;
10694 verify_result.ocsp_result.response_status = OCSPVerifyResult::NOT_CHECKED;
10695 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
10696
10697 // Set up a mock report sender so that the test can check that an
10698 // Expect-Staple report is not sent.
10699 TransportSecurityState transport_security_state;
10700 MockCertificateReportSender mock_report_sender;
10701 transport_security_state.SetReportSender(&mock_report_sender);
10702
10703 TestNetworkDelegate network_delegate;
10704 TestURLRequestContext context(true);
10705
10706 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
10707 MockHostResolver host_resolver;
10708 context.set_host_resolver(&host_resolver);
10709
10710 context.set_transport_security_state(&transport_security_state);
10711 context.set_network_delegate(&network_delegate);
10712 context.set_cert_verifier(&cert_verifier);
10713 context.Init();
10714
10715 // Make a connection to |kExpectStapleStaticHostname|. Because the
10716 // |verify_result| used with the |cert_verifier| will indicate that OCSP
10717 // stapling details were not checked on the connection, an Expect-Staple
10718 // report should not be sent.
10719 TestDelegate d;
10720 GURL url = https_test_server.GetURL("/");
10721 GURL::Replacements replace_host;
10722 replace_host.SetHostStr(kExpectStapleStaticHostname);
10723 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610724 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
10725 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3210726 ok_request->Start();
10727 base::RunLoop().Run();
10728
10729 // Check that no report was sent.
10730 EXPECT_TRUE(mock_report_sender.latest_report().empty());
10731 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
10732}
10733
dadrian612337a2016-07-20 22:36:5810734static const struct OCSPVerifyTestData {
10735 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
10736 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
10737 OCSPVerifyResult::ResponseStatus response_status;
10738 bool has_revocation_status;
10739 OCSPRevocationStatus cert_status;
10740} kOCSPVerifyData[] = {
10741
10742 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10743 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10744 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10745 OCSPVerifyResult::PROVIDED,
10746 true,
10747 OCSPRevocationStatus::GOOD},
10748
10749 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10750 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10751 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10752 OCSPVerifyResult::INVALID_DATE,
10753 false,
10754 OCSPRevocationStatus::UNKNOWN},
10755
10756 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10757 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10758 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10759 OCSPVerifyResult::INVALID_DATE,
10760 false,
10761 OCSPRevocationStatus::UNKNOWN},
10762
10763 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10764 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10765 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10766 OCSPVerifyResult::INVALID_DATE,
10767 false,
10768 OCSPRevocationStatus::UNKNOWN},
10769
10770 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10771 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10772 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10773 OCSPVerifyResult::INVALID_DATE,
10774 false,
10775 OCSPRevocationStatus::UNKNOWN},
10776
10777 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
10778 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10779 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10780 OCSPVerifyResult::ERROR_RESPONSE,
10781 false,
10782 OCSPRevocationStatus::UNKNOWN},
10783
10784 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
10785 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10786 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10787 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
10788 false,
10789 OCSPRevocationStatus::UNKNOWN},
10790
10791 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
10792 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10793 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10794 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
10795 false,
10796 OCSPRevocationStatus::UNKNOWN},
10797
10798 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10799 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10800 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10801 OCSPVerifyResult::INVALID_DATE,
10802 false,
10803 OCSPRevocationStatus::UNKNOWN},
10804
10805 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10806 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10807 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10808 OCSPVerifyResult::PROVIDED,
10809 true,
10810 OCSPRevocationStatus::UNKNOWN},
10811
10812 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10813 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10814 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10815 OCSPVerifyResult::INVALID_DATE,
10816 false,
10817 OCSPRevocationStatus::UNKNOWN},
10818
10819 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10820 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10821 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10822 OCSPVerifyResult::INVALID_DATE,
10823 false,
10824 OCSPRevocationStatus::UNKNOWN},
10825
10826 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10827 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10828 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
10829 OCSPVerifyResult::BAD_PRODUCED_AT,
10830 false,
10831 OCSPRevocationStatus::UNKNOWN},
10832
10833 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10834 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10835 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
10836 OCSPVerifyResult::BAD_PRODUCED_AT,
10837 false,
10838 OCSPRevocationStatus::UNKNOWN},
10839
10840 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10841 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10842 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
10843 OCSPVerifyResult::BAD_PRODUCED_AT,
10844 false,
10845 OCSPRevocationStatus::UNKNOWN},
10846
10847 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10848 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10849 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10850 OCSPVerifyResult::PROVIDED,
10851 true,
10852 OCSPRevocationStatus::REVOKED},
10853
10854 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10855 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10856 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10857 OCSPVerifyResult::INVALID_DATE,
10858 false,
10859 OCSPRevocationStatus::UNKNOWN},
10860
10861 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10862 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10863 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10864 OCSPVerifyResult::INVALID_DATE,
10865 false,
10866 OCSPRevocationStatus::UNKNOWN},
10867
10868 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10869 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10870 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10871 OCSPVerifyResult::PROVIDED,
10872 true,
10873 OCSPRevocationStatus::GOOD},
10874
10875 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10876 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
10877 {SpawnedTestServer::SSLOptions::OCSP_OK,
10878 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10879 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10880 OCSPVerifyResult::PROVIDED,
10881 true,
10882 OCSPRevocationStatus::GOOD},
10883
10884 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10885 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
10886 {SpawnedTestServer::SSLOptions::OCSP_OK,
10887 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10888 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10889 OCSPVerifyResult::PROVIDED,
10890 true,
10891 OCSPRevocationStatus::GOOD},
10892
10893 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10894 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
10895 {SpawnedTestServer::SSLOptions::OCSP_OK,
10896 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10897 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10898 OCSPVerifyResult::PROVIDED,
10899 true,
10900 OCSPRevocationStatus::GOOD},
10901
10902 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10903 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
10904 {SpawnedTestServer::SSLOptions::OCSP_OK,
10905 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
10906 {SpawnedTestServer::SSLOptions::OCSP_OK,
10907 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10908 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10909 OCSPVerifyResult::INVALID_DATE,
10910 false,
10911 OCSPRevocationStatus::UNKNOWN},
10912
10913 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10914 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10915 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10916 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10917 {SpawnedTestServer::SSLOptions::OCSP_OK,
10918 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10919 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10920 OCSPVerifyResult::PROVIDED,
10921 true,
10922 OCSPRevocationStatus::REVOKED},
10923
10924 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10925 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10926 {SpawnedTestServer::SSLOptions::OCSP_OK,
10927 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10928 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10929 OCSPVerifyResult::PROVIDED,
10930 true,
10931 OCSPRevocationStatus::UNKNOWN},
10932
10933 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10934 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10935 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10936 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
10937 {SpawnedTestServer::SSLOptions::OCSP_OK,
10938 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10939 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10940 OCSPVerifyResult::PROVIDED,
10941 true,
10942 OCSPRevocationStatus::UNKNOWN},
10943
10944 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10945 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10946 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10947 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10948 false,
10949 OCSPRevocationStatus::UNKNOWN},
10950
10951 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10952 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10953 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10954 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10955 false,
10956 OCSPRevocationStatus::UNKNOWN},
10957
10958};
10959
10960class HTTPSOCSPVerifyTest
10961 : public HTTPSOCSPTest,
10962 public testing::WithParamInterface<OCSPVerifyTestData> {};
10963
10964TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
10965 SpawnedTestServer::SSLOptions ssl_options(
10966 SpawnedTestServer::SSLOptions::CERT_AUTO);
10967 OCSPVerifyTestData test = GetParam();
10968
10969 ssl_options.ocsp_responses = test.ocsp_responses;
10970 ssl_options.ocsp_produced = test.ocsp_produced;
10971 ssl_options.staple_ocsp_response = true;
10972
10973 SSLInfo ssl_info;
10974 OCSPErrorTestDelegate delegate;
10975 ASSERT_NO_FATAL_FAILURE(
10976 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
10977
10978 // The SSLInfo must be extracted from |delegate| on error, due to how
10979 // URLRequest caches certificate errors.
10980 if (delegate.have_certificate_errors()) {
10981 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
10982 ssl_info = delegate.ssl_info();
10983 }
10984
10985 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
10986
10987 if (test.has_revocation_status)
10988 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
10989}
10990
10991INSTANTIATE_TEST_CASE_P(OCSPVerify,
10992 HTTPSOCSPVerifyTest,
10993 testing::ValuesIn(kOCSPVerifyData));
10994
mattm0b12a6f2016-11-29 19:57:1610995static bool SystemSupportsAIA() {
Sergey Ulanov884169a02017-09-06 18:58:0210996#if defined(OS_ANDROID) || defined(OS_FUCHSIA)
10997 // TODO(crbug.com/762380): Enable on Fuchsia once it's implemented.
mattm0b12a6f2016-11-29 19:57:1610998 return false;
10999#else
11000 return true;
11001#endif
11002}
11003
11004class HTTPSAIATest : public HTTPSOCSPTest {
11005 public:
11006 void SetupContext() override {
11007 context_.set_ssl_config_service(new TestSSLConfigService(
11008 false /* check for EV */, false /* online revocation checking */,
11009 false /* require rev. checking for local anchors */,
11010 false /* token binding enabled */));
11011 }
11012};
11013
11014TEST_F(HTTPSAIATest, AIAFetching) {
11015 SpawnedTestServer::SSLOptions ssl_options(
11016 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
11017 SpawnedTestServer test_server(
11018 SpawnedTestServer::TYPE_HTTPS, ssl_options,
11019 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11020 ASSERT_TRUE(test_server.Start());
11021
11022 TestDelegate d;
11023 d.set_allow_certificate_errors(true);
11024 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611025 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11026 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611027
11028 r->Start();
11029 EXPECT_TRUE(r->is_pending());
11030
11031 base::RunLoop().Run();
11032
11033 EXPECT_EQ(1, d.response_started_count());
11034
11035 CertStatus cert_status = r->ssl_info().cert_status;
11036 if (SystemSupportsAIA()) {
11037 EXPECT_EQ(OK, d.request_status());
11038 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11039 ASSERT_TRUE(r->ssl_info().cert);
11040 EXPECT_EQ(2u, r->ssl_info().cert->GetIntermediateCertificates().size());
11041 } else {
11042 EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID,
11043 cert_status & CERT_STATUS_ALL_ERRORS);
11044 }
11045 ASSERT_TRUE(r->ssl_info().unverified_cert);
11046 EXPECT_EQ(
11047 0u, r->ssl_info().unverified_cert->GetIntermediateCertificates().size());
11048}
11049
[email protected]3a86a712013-07-30 07:16:2011050class HTTPSHardFailTest : public HTTPSOCSPTest {
11051 protected:
rsleevid6de8302016-06-21 01:33:2011052 void SetupContext() override {
11053 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1411054 false /* check for EV */, false /* online revocation checking */,
11055 true /* require rev. checking for local
11056 anchors */,
11057 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:2011058 }
11059};
11060
[email protected]3a86a712013-07-30 07:16:2011061TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
11062 if (!SystemSupportsOCSP()) {
11063 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11064 return;
11065 }
11066
11067 if (!SystemSupportsHardFailRevocationChecking()) {
11068 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
11069 << "revocation checking";
11070 return;
11071 }
11072
11073 SpawnedTestServer::SSLOptions ssl_options(
11074 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811075 ssl_options.ocsp_status =
11076 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2011077
11078 CertStatus cert_status;
11079 DoConnection(ssl_options, &cert_status);
11080
11081 EXPECT_EQ(CERT_STATUS_REVOKED,
11082 cert_status & CERT_STATUS_REVOKED);
11083
11084 // Without a positive OCSP response, we shouldn't show the EV status.
11085 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11086}
11087
[email protected]a13234c2012-03-20 21:45:0211088class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
11089 protected:
rsleevid6de8302016-06-21 01:33:2011090 void SetupContext() override {
11091 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1411092 true /* check for EV */, false /* online revocation checking */,
11093 false /* require rev. checking for local
11094 anchors */,
11095 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0211096 }
11097};
11098
11099TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
11100 if (!SystemSupportsOCSP()) {
11101 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11102 return;
11103 }
11104
[email protected]ce7d0cbc2013-05-03 18:57:2211105 SpawnedTestServer::SSLOptions ssl_options(
11106 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811107 ssl_options.ocsp_status =
11108 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211109 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
11110
[email protected]924e9f92012-12-16 22:00:5311111 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211112 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211113
mattmaf868e72016-09-23 23:25:2011114 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211115 cert_status & CERT_STATUS_ALL_ERRORS);
11116
11117 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811118 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11119 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211120}
11121
[email protected]be0fff62013-08-29 23:37:4811122TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
11123 if (!SystemSupportsOCSP()) {
11124 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11125 return;
11126 }
11127
11128 SpawnedTestServer::SSLOptions ssl_options(
11129 SpawnedTestServer::SSLOptions::CERT_AUTO);
11130 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11131 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
11132
11133 CertStatus cert_status;
11134 DoConnection(ssl_options, &cert_status);
11135
mattm1a282f52016-11-10 21:49:4211136// Currently only works for Windows and OS X. When using NSS, it's not
11137// possible to determine whether the check failed because of actual
11138// revocation or because there was an OCSP failure.
11139#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4811140 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11141#else
11142 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11143#endif
11144
11145 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11146 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11147 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11148}
11149
[email protected]a13234c2012-03-20 21:45:0211150TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
11151 if (!SystemSupportsOCSP()) {
11152 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11153 return;
11154 }
11155
[email protected]ce7d0cbc2013-05-03 18:57:2211156 SpawnedTestServer::SSLOptions ssl_options(
11157 SpawnedTestServer::SSLOptions::CERT_AUTO);
11158 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0211159 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
11160
11161 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211162 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211163
11164 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11165
11166 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11167 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0811168 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11169 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211170}
11171
11172TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
11173 if (!SystemSupportsOCSP()) {
11174 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11175 return;
11176 }
11177
[email protected]ce7d0cbc2013-05-03 18:57:2211178 SpawnedTestServer::SSLOptions ssl_options(
11179 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811180 ssl_options.ocsp_status =
11181 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211182 SSLConfigService::SetCRLSet(
11183 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
11184
11185 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211186 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211187
mattmaf868e72016-09-23 23:25:2011188 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211189 cert_status & CERT_STATUS_ALL_ERRORS);
11190
11191 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811192 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11193 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211194}
11195
[email protected]51523f52013-07-31 21:57:2811196TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
11197 if (!SystemSupportsOCSP()) {
11198 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11199 return;
11200 }
11201
11202 SpawnedTestServer::SSLOptions ssl_options(
11203 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811204 ssl_options.ocsp_status =
11205 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]51523f52013-07-31 21:57:2811206 SSLConfigService::SetCRLSet(
11207 scoped_refptr<CRLSet>(CRLSet::ForTesting(
11208 false, &kOCSPTestCertSPKI, "")));
11209
11210 CertStatus cert_status;
11211 DoConnection(ssl_options, &cert_status);
11212
11213 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
11214 // revocation check for EV.
11215 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11216 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11217 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11218 EXPECT_FALSE(
11219 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11220}
11221
11222TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
11223 if (!SystemSupportsOCSP()) {
11224 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11225 return;
11226 }
11227
[email protected]ce7d0cbc2013-05-03 18:57:2211228 SpawnedTestServer::SSLOptions ssl_options(
11229 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811230 ssl_options.ocsp_status =
11231 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211232 SSLConfigService::SetCRLSet(
11233 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
11234
[email protected]51523f52013-07-31 21:57:2811235 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1211236 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211237
[email protected]51523f52013-07-31 21:57:2811238 // Even with a fresh CRLSet, we should still do online revocation checks when
11239 // the certificate chain isn't covered by the CRLSet, which it isn't in this
11240 // test.
mattmaf868e72016-09-23 23:25:2011241 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2811242 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0211243
[email protected]51523f52013-07-31 21:57:2811244 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0211245 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2811246 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211247}
11248
[email protected]b6f2de32012-08-17 04:35:0811249TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
11250 // Test that when EV verification is requested, but online revocation
11251 // checking is disabled, and the leaf certificate is not in fact EV, that
11252 // no revocation checking actually happens.
11253 if (!SystemSupportsOCSP()) {
11254 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11255 return;
11256 }
11257
11258 // Unmark the certificate's OID as EV, which should disable revocation
11259 // checking (as per the user preference)
11260 ev_test_policy_.reset();
11261
[email protected]ce7d0cbc2013-05-03 18:57:2211262 SpawnedTestServer::SSLOptions ssl_options(
11263 SpawnedTestServer::SSLOptions::CERT_AUTO);
11264 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:0811265 SSLConfigService::SetCRLSet(
11266 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
11267
11268 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211269 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:0811270
11271 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11272
11273 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11274 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11275}
11276
[email protected]a13234c2012-03-20 21:45:0211277class HTTPSCRLSetTest : public HTTPSOCSPTest {
11278 protected:
rsleevid6de8302016-06-21 01:33:2011279 void SetupContext() override {
11280 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1411281 false /* check for EV */, false /* online revocation checking */,
11282 false /* require rev. checking for local
11283 anchors */,
11284 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0211285 }
11286};
11287
11288TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2211289 SpawnedTestServer::SSLOptions ssl_options(
11290 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811291 ssl_options.ocsp_status =
11292 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211293 SSLConfigService::SetCRLSet(
11294 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
11295
[email protected]924e9f92012-12-16 22:00:5311296 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211297 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211298
11299 // If we're not trying EV verification then, even if the CRLSet has expired,
11300 // we don't fall back to online revocation checks.
11301 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11302 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11303 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11304}
[email protected]51523f52013-07-31 21:57:2811305
11306TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Sergey Ulanov884169a02017-09-06 18:58:0211307#if defined(OS_ANDROID) || defined(OS_FUCHSIA)
11308 // TODO(crbug.com/762380): Enable on Fuchsia once it's implemented.
[email protected]51523f52013-07-31 21:57:2811309 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11310 return;
11311#endif
11312
11313 SpawnedTestServer::SSLOptions ssl_options(
11314 SpawnedTestServer::SSLOptions::CERT_AUTO);
11315 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11316 ssl_options.cert_serial = 10;
11317 SSLConfigService::SetCRLSet(
11318 scoped_refptr<CRLSet>(CRLSet::ForTesting(
11319 false, &kOCSPTestCertSPKI, "\x0a")));
11320
11321 CertStatus cert_status = 0;
11322 DoConnection(ssl_options, &cert_status);
11323
11324 // If the certificate is recorded as revoked in the CRLSet, that should be
11325 // reflected without online revocation checking.
11326 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11327 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11328 EXPECT_FALSE(
11329 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11330}
[email protected]316c1e5e2012-09-12 15:17:4411331#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2711332
Sergey Ulanovc4580e72017-09-13 23:30:1111333#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
11334 !defined(OS_FUCHSIA)
11335// FTP uses a second TCP connection with the port number allocated dynamically
11336// on the server side, so it would be hard to make RemoteTestServer proxy FTP
11337// connections reliably. FTP tests are disabled on platforms that use
11338// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3111339class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1111340 public:
[email protected]d9fca99a2012-02-24 16:16:2011341 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0511342 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5511343 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4711344 // Can't use |default_context_|'s HostResolver to set up the
11345 // FTPTransactionFactory because it hasn't been created yet.
11346 default_context_.set_host_resolver(&host_resolver_);
11347 }
11348
11349 // URLRequestTest interface:
11350 void SetUpFactory() override {
11351 // Add FTP support to the default URLRequestContext.
11352 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0511353 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4711354 }
11355
11356 std::string GetTestFileContents() {
11357 base::FilePath path;
11358 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
11359 path = path.Append(kTestFilePath);
11360 path = path.AppendASCII(kFtpTestFile);
11361 std::string contents;
11362 EXPECT_TRUE(base::ReadFileToString(path, &contents));
11363 return contents;
[email protected]95409e12010-08-17 20:07:1111364 }
11365
[email protected]b89ca032009-08-31 21:41:3111366 protected:
mmenkecd4c7532016-10-19 18:36:0511367 // Note that this is destroyed before the FtpProtocolHandler that references
11368 // it, which is owned by the parent class. Since no requests are made during
11369 // teardown, this works, though it's not great.
mmenke9f2ec60c2015-06-01 20:59:4711370 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4711371
tommycli59a63432015-11-06 00:10:5511372 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3111373};
11374
[email protected]d2a133182012-08-05 16:44:0811375// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0911376TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0811377 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0811378
11379 TestDelegate d;
11380 {
rhalavatib7bd7c792017-04-27 05:25:1611381 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11382 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911383 r->Start();
11384 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0811385
[email protected]255620da2013-08-19 13:14:2911386 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:0811387
[email protected]f7022f32014-08-21 16:32:1911388 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5011389 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0811390 }
11391}
11392
mmenke9f2ec60c2015-06-01 20:59:4711393TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5511394 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111395
[email protected]a25e90e2009-09-09 17:05:3711396 TestDelegate d;
11397 {
danakj8522a25b2016-04-16 00:17:3611398 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611399 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
11400 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911401 r->Start();
11402 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711403
[email protected]255620da2013-08-19 13:14:2911404 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:3711405
[email protected]f7022f32014-08-21 16:32:1911406 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711407 EXPECT_EQ(1, d.response_started_count());
11408 EXPECT_FALSE(d.received_data_before_response());
11409 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5511410 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911411 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511412 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911413 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:3711414 }
11415}
11416
mmenke9f2ec60c2015-06-01 20:59:4711417TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5511418 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111419
[email protected]dd265012009-01-08 20:45:2711420 TestDelegate d;
11421 {
danakj8522a25b2016-04-16 00:17:3611422 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611423 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
11424 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911425 r->Start();
11426 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711427
[email protected]255620da2013-08-19 13:14:2911428 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711429
[email protected]f7022f32014-08-21 16:32:1911430 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711431 EXPECT_EQ(1, d.response_started_count());
11432 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711433 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511434 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911435 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511436 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911437 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:2711438 }
11439}
11440
mmenke9f2ec60c2015-06-01 20:59:4711441TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5511442 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111443
[email protected]dd265012009-01-08 20:45:2711444 TestDelegate d;
11445 {
danakj8522a25b2016-04-16 00:17:3611446 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511447 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11448 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611449 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911450 r->Start();
11451 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711452
[email protected]255620da2013-08-19 13:14:2911453 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711454
[email protected]f7022f32014-08-21 16:32:1911455 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4711456 EXPECT_EQ(1, d.response_started_count());
11457 EXPECT_FALSE(d.received_data_before_response());
11458 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511459 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911460 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511461 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911462 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2511463
11464 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1911465 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2511466 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2711467 }
11468}
11469
mmenke9f2ec60c2015-06-01 20:59:4711470TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5511471 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111472
[email protected]dd265012009-01-08 20:45:2711473 TestDelegate d;
11474 {
danakj8522a25b2016-04-16 00:17:3611475 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511476 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11477 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611478 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911479 r->Start();
11480 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711481
[email protected]255620da2013-08-19 13:14:2911482 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711483
[email protected]f7022f32014-08-21 16:32:1911484 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711485 EXPECT_EQ(1, d.response_started_count());
11486 EXPECT_FALSE(d.received_data_before_response());
11487 EXPECT_EQ(d.bytes_received(), 0);
11488 }
11489}
11490
mmenke9f2ec60c2015-06-01 20:59:4711491TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5511492 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111493
[email protected]8b8a197d2009-08-26 15:57:5811494 TestDelegate d;
11495 // Set correct login credentials. The delegate will be asked for them when
11496 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811497 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811498 {
danakj8522a25b2016-04-16 00:17:3611499 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511500 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11501 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611502 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911503 r->Start();
11504 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811505
[email protected]255620da2013-08-19 13:14:2911506 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5811507
[email protected]f7022f32014-08-21 16:32:1911508 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811509 EXPECT_EQ(1, d.response_started_count());
11510 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711511 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811512 }
11513}
11514
mmenke9f2ec60c2015-06-01 20:59:4711515TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5511516 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111517
[email protected]dd265012009-01-08 20:45:2711518 TestDelegate d;
11519 {
danakj8522a25b2016-04-16 00:17:3611520 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511521 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
11522 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611523 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911524 r->Start();
11525 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711526
[email protected]255620da2013-08-19 13:14:2911527 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711528
[email protected]f7022f32014-08-21 16:32:1911529 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711530 EXPECT_EQ(1, d.response_started_count());
11531 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711532 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2711533 }
11534}
[email protected]8b8a197d2009-08-26 15:57:5811535
mmenke9f2ec60c2015-06-01 20:59:4711536TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5511537 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111538
[email protected]8b8a197d2009-08-26 15:57:5811539 TestDelegate d;
11540 // Set correct login credentials. The delegate will be asked for them when
11541 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811542 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811543 {
danakj8522a25b2016-04-16 00:17:3611544 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511545 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
11546 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611547 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911548 r->Start();
11549 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811550
[email protected]255620da2013-08-19 13:14:2911551 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5811552
[email protected]f7022f32014-08-21 16:32:1911553 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811554 EXPECT_EQ(1, d.response_started_count());
11555 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711556 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811557 }
11558}
[email protected]60a3df52009-09-22 16:13:2411559
mmenke9f2ec60c2015-06-01 20:59:4711560TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5511561 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111562
danakj8522a25b2016-04-16 00:17:3611563 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2411564 {
11565 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3611566 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511567 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11568 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611569 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911570 r->Start();
11571 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411572
[email protected]255620da2013-08-19 13:14:2911573 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411574
[email protected]f7022f32014-08-21 16:32:1911575 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411576 EXPECT_EQ(1, d->response_started_count());
11577 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711578 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411579 }
11580
11581 d.reset(new TestDelegate);
11582 {
11583 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3611584 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611585 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
11586 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911587 r->Start();
11588 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411589
[email protected]255620da2013-08-19 13:14:2911590 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411591
[email protected]f7022f32014-08-21 16:32:1911592 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411593 EXPECT_EQ(1, d->response_started_count());
11594 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711595 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411596 }
11597}
11598
mmenke9f2ec60c2015-06-01 20:59:4711599TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5511600 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111601
danakj8522a25b2016-04-16 00:17:3611602 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2411603 // Set correct login credentials. The delegate will be asked for them when
11604 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811605 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2411606 {
danakj8522a25b2016-04-16 00:17:3611607 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511608 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11609 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611610 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911611 r->Start();
11612 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411613
[email protected]255620da2013-08-19 13:14:2911614 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411615
[email protected]f7022f32014-08-21 16:32:1911616 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411617 EXPECT_EQ(1, d->response_started_count());
11618 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711619 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411620 }
11621
11622 // Use a new delegate without explicit credentials. The cached ones should be
11623 // used.
11624 d.reset(new TestDelegate);
11625 {
11626 // Don't pass wrong credentials in the URL, they would override valid cached
11627 // ones.
danakj8522a25b2016-04-16 00:17:3611628 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611629 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
11630 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911631 r->Start();
11632 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411633
[email protected]255620da2013-08-19 13:14:2911634 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411635
[email protected]f7022f32014-08-21 16:32:1911636 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411637 EXPECT_EQ(1, d->response_started_count());
11638 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711639 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411640 }
11641}
ricea3a1c71f2016-06-17 10:05:2611642
11643TEST_F(URLRequestTestFTP, RawBodyBytes) {
11644 ASSERT_TRUE(ftp_test_server_.Start());
11645
11646 TestDelegate d;
11647 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611648 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
11649 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2611650 req->Start();
11651 base::RunLoop().Run();
11652
11653 EXPECT_EQ(6, req->GetRawBodyBytes());
11654}
11655
brettwa1228ebb2016-10-28 03:51:3411656#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5111657
ttuttlec0c828492015-05-15 01:25:5511658TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
11659 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1611660 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
11661 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5511662
11663 EXPECT_FALSE(req->response_info().network_accessed);
11664
11665 req->Start();
11666 base::RunLoop().Run();
11667
11668 EXPECT_EQ(1, default_network_delegate_.completed_requests());
11669 EXPECT_FALSE(req->response_info().network_accessed);
11670}
11671
11672TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
11673 MockHostResolver host_resolver;
11674 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
11675 TestURLRequestContext context(true);
11676 context.set_network_delegate(&network_delegate);
11677 context.set_host_resolver(&host_resolver);
11678 host_resolver.rules()->AddSimulatedFailure("*");
11679 context.Init();
11680
11681 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1611682 std::unique_ptr<URLRequest> req(
11683 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
11684 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5511685
11686 EXPECT_FALSE(req->response_info().network_accessed);
11687
11688 req->Start();
11689 base::RunLoop().Run();
11690 EXPECT_TRUE(req->response_info().network_accessed);
11691}
11692
mmenkeed0498b2015-12-08 23:20:4211693// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2211694// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4211695TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2211696 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611697 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611698 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
11699 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2211700
danakj8522a25b2016-04-16 00:17:3611701 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2211702 req.get(), &default_network_delegate_,
11703 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4211704 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
11705 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2211706
11707 req->Start();
11708 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2211709 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5011710 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2211711 EXPECT_EQ(0, d.received_redirect_count());
11712}
11713
Andrey Kosyakov2e893e62017-08-31 17:00:5211714TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411715 ASSERT_TRUE(http_test_server()->Start());
11716 TestURLRequestContext context;
11717 GURL url(http_test_server()->GetURL("/cachetime"));
11718 TestDelegate delegate;
11719 HttpRequestHeaders extra_headers;
11720 extra_headers.SetHeader("X-Foo", "bar");
11721
11722 {
Andrey Kosyakov2e893e62017-08-31 17:00:5211723 HttpRawRequestHeaders raw_req_headers;
11724 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
11725
Andrey Kosyakov83a6eee2017-08-14 19:20:0411726 std::unique_ptr<URLRequest> r(context.CreateRequest(
11727 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11728 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5211729 r->SetRequestHeadersCallback(base::Bind(
11730 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
11731 r->SetResponseHeadersCallback(base::Bind(
11732 [](scoped_refptr<const HttpResponseHeaders>* left,
11733 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
11734 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411735 r->Start();
11736 while (!delegate.response_started_count())
11737 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5211738 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411739 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5211740 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411741 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211742 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411743 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211744 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
11745 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
11746 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
11747 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411748 }
11749 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411750 std::unique_ptr<URLRequest> r(context.CreateRequest(
11751 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11752 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5211753 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411754 FAIL() << "Callback should not be called unless request is sent";
11755 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5211756 r->SetResponseHeadersCallback(
11757 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
11758 FAIL() << "Callback should not be called unless request is sent";
11759 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411760 r->Start();
11761 base::RunLoop().Run();
11762 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411763 }
11764}
11765
Andrey Kosyakov2e893e62017-08-31 17:00:5211766TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411767 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5211768 HttpRawRequestHeaders raw_req_headers;
11769 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
11770
Andrey Kosyakov83a6eee2017-08-14 19:20:0411771 TestURLRequestContext context;
11772 TestDelegate delegate;
11773 HttpRequestHeaders extra_headers;
11774 extra_headers.SetHeader("X-Foo", "bar");
11775 delegate.set_quit_on_redirect(true);
11776 GURL url(http_test_server()->GetURL("/redirect-test.html"));
11777 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11778 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11779 r->SetExtraRequestHeaders(extra_headers);
11780 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5211781 base::Unretained(&raw_req_headers)));
11782 r->SetResponseHeadersCallback(base::Bind(
11783 [](scoped_refptr<const HttpResponseHeaders>* left,
11784 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
11785 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411786 r->Start();
11787 base::RunLoop().Run();
11788
11789 ASSERT_EQ(1, delegate.received_redirect_count());
11790 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5211791 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411792 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211793 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411794 EXPECT_EQ("gzip, deflate", value);
11795 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5211796 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
11797 raw_req_headers.request_line());
11798 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
11799 EXPECT_EQ(302, raw_resp_headers->response_code());
11800 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411801
Andrey Kosyakov2e893e62017-08-31 17:00:5211802 raw_req_headers = HttpRawRequestHeaders();
11803 raw_resp_headers = nullptr;
Andrey Kosyakov83a6eee2017-08-14 19:20:0411804 r->FollowDeferredRedirect();
11805 base::RunLoop().Run();
Andrey Kosyakov2e893e62017-08-31 17:00:5211806 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411807 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211808 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411809 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211810 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
11811 raw_req_headers.request_line());
11812 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411813}
11814
Andrey Kosyakov2e893e62017-08-31 17:00:5211815TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411816 TestDelegate request_delegate;
11817
11818 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11819 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
11820 TRAFFIC_ANNOTATION_FOR_TESTS));
11821 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
11822 FAIL() << "Callback should not be called unless request is sent";
11823 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5211824 r->SetResponseHeadersCallback(
11825 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
11826 FAIL() << "Callback should not be called unless request is sent";
11827 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411828 r->Start();
11829 base::RunLoop().Run();
11830 EXPECT_FALSE(r->is_pending());
11831}
11832
Andrey Kosyakov2e893e62017-08-31 17:00:5211833TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411834 ASSERT_TRUE(http_test_server()->Start());
11835 GURL url(http_test_server()->GetURL("/auth-basic"));
11836
11837 TestURLRequestContext context;
11838 TestDelegate delegate;
11839
11840 delegate.set_credentials(AuthCredentials(kUser, kSecret));
11841 HttpRequestHeaders extra_headers;
11842 extra_headers.SetHeader("X-Foo", "bar");
11843
Andrey Kosyakov2e893e62017-08-31 17:00:5211844 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
11845 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0411846
Andrey Kosyakov2e893e62017-08-31 17:00:5211847 using RespHeadersVector =
11848 std::vector<scoped_refptr<const HttpResponseHeaders>>;
11849 RespHeadersVector raw_resp_headers;
11850
11851 auto req_headers_callback = base::Bind(
11852 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
11853 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
11854 },
11855 &raw_req_headers);
11856 auto resp_headers_callback = base::Bind(
11857 [](RespHeadersVector* vec,
11858 scoped_refptr<const HttpResponseHeaders> headers) {
11859 vec->push_back(headers);
11860 },
11861 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0411862 std::unique_ptr<URLRequest> r(context.CreateRequest(
11863 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11864 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5211865 r->SetRequestHeadersCallback(req_headers_callback);
11866 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0411867 r->Start();
11868 base::RunLoop().Run();
11869 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5211870 ASSERT_EQ(raw_req_headers.size(), 2u);
11871 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0411872 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5211873 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
11874 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411875 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211876 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
11877 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411878 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211879 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
11880 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
11881 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
11882 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
11883
11884 std::unique_ptr<URLRequest> r2(context.CreateRequest(
11885 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11886 r2->SetExtraRequestHeaders(extra_headers);
11887 r2->SetRequestHeadersCallback(req_headers_callback);
11888 r2->SetResponseHeadersCallback(resp_headers_callback);
11889 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
11890 r2->Start();
11891 base::RunLoop().Run();
11892 EXPECT_FALSE(r2->is_pending());
11893 ASSERT_EQ(raw_req_headers.size(), 3u);
11894 ASSERT_EQ(raw_resp_headers.size(), 3u);
11895 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
11896 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
11897 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
11898 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411899}
11900
Andrey Kosyakov2e893e62017-08-31 17:00:5211901TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411902 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
11903 TestDelegate d;
11904 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11905 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11906 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5211907 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0411908 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5211909 r->SetResponseHeadersCallback(
11910 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
11911 FAIL() << "Callback should not be called for non-HTTP schemes";
11912 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411913 r->Start();
11914 base::RunLoop().Run();
11915 EXPECT_FALSE(r->is_pending());
11916}
11917
[email protected]7461a402011-03-24 23:19:5111918} // namespace net