blob: be31d12efb9601673ee4f724bb203f9b4f6e9853 [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
Douglas Creager4d1ef842018-07-16 23:42:255#include <algorithm>
dchengc7eeda422015-12-26 03:56:486#include <utility>
7
mmenkefd9d15c2017-06-29 13:45:548// This must be before Windows headers
Sebastien Marchand17fa2782019-01-25 19:28:109#include "base/bind_helpers.h"
[email protected]ea224582008-12-07 20:25:4610#include "build/build_config.h"
11
[email protected]9396b252008-09-29 17:29:3812#if defined(OS_WIN)
robliaoeb9bfd642017-05-18 17:35:1613#include <objbase.h>
[email protected]aa84a7e2012-03-15 21:29:0614#include <shlobj.h>
Fan Yang5a88d5d2017-10-24 01:14:2915#include <windows.h>
Robert Liaoc88f99d12017-10-17 21:48:3316#include <wrl/client.h>
[email protected]9396b252008-09-29 17:29:3817#endif
18
tbansalea2fb8c2015-05-22 22:23:0019#include <stdint.h>
20
initial.commit586acc5fe2008-07-26 22:42:5221#include <algorithm>
avibf0746c2015-12-09 19:53:1422#include <limits>
Devlin Cronine4bcb40e2018-06-05 18:02:4723#include <memory>
initial.commit586acc5fe2008-07-26 22:42:5224
nharperb7441ef2016-01-25 23:54:1425#include "base/base64url.h"
[email protected]218aa6a12011-09-13 17:38:3826#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5827#include "base/compiler_specific.h"
mmenke9f2ec60c2015-06-01 20:59:4728#include "base/files/file_path.h"
thestigd8df0332014-09-04 06:33:2929#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0730#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2831#include "base/format_macros.h"
estark06e0dac2015-08-07 21:56:0132#include "base/json/json_reader.h"
skyostil4891b25b2015-06-11 11:43:4533#include "base/location.h"
[email protected]084262c2011-12-01 21:12:4734#include "base/memory/weak_ptr.h"
Alexander Timin4f9c35c2018-11-01 20:15:2035#include "base/message_loop/message_loop.h"
initial.commit586acc5fe2008-07-26 22:42:5236#include "base/path_service.h"
mmenkefb18c772015-09-30 22:22:5037#include "base/power_monitor/power_monitor.h"
38#include "base/power_monitor/power_monitor_source.h"
[email protected]255620da2013-08-19 13:14:2939#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4540#include "base/single_thread_task_runner.h"
Avi Drissman4365a4782018-12-28 19:26:2441#include "base/stl_util.h"
[email protected]4dc3ad4f2013-06-11 07:15:5042#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5543#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2244#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2245#include "base/strings/string_util.h"
46#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0547#include "base/strings/utf_string_conversions.h"
Devlin Cronine4bcb40e2018-06-05 18:02:4748#include "base/test/metrics/histogram_tester.h"
Emily Stark4cfecf072017-08-08 01:05:5149#include "base/test/scoped_feature_list.h"
gabf767595f2016-05-11 18:50:3550#include "base/threading/thread_task_runner_handle.h"
estark06e0dac2015-08-07 21:56:0151#include "base/values.h"
mmenkefd9d15c2017-06-29 13:45:5452#include "build/buildflag.h"
mmenkecbc2b712014-10-09 20:29:0753#include "net/base/chunked_upload_data_stream.h"
tfarina43a416b2016-01-06 21:48:0754#include "net/base/directory_listing.h"
mmenkecbc2b712014-10-09 20:29:0755#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5256#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2557#include "net/base/load_timing_info.h"
58#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0659#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5260#include "net/base/net_module.h"
Lily Houghton582d4622018-01-22 22:43:4061#include "net/base/proxy_server.h"
[email protected]2ca01e52013-10-31 22:05:1962#include "net/base/request_priority.h"
zhongyi18ddddd2017-02-03 19:06:3663#include "net/base/test_completion_callback.h"
[email protected]f288ef02012-12-15 20:28:2864#include "net/base/upload_bytes_element_reader.h"
65#include "net/base/upload_data_stream.h"
66#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4467#include "net/base/url_util.h"
Ryan Sleevib369d712018-08-20 16:43:2268#include "net/cert/crl_set.h"
rsleevid6de8302016-06-21 01:33:2069#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4770#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3671#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1172#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2473#include "net/cert/mock_cert_verifier.h"
zhongyi18ddddd2017-02-03 19:06:3674#include "net/cert/multi_log_ct_verifier.h"
eranmdcec9632016-10-10 14:16:1075#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1176#include "net/cert/test_root_certs.h"
[email protected]aa84a7e2012-03-15 21:29:0677#include "net/cookies/cookie_monster.h"
78#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5279#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5380#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3881#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5282#include "net/http/http_cache.h"
83#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1984#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2585#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2186#include "net/http/http_response_headers.h"
zhongyi18ddddd2017-02-03 19:06:3687#include "net/http/http_server_properties_impl.h"
[email protected]e50efea2014-03-24 18:41:0088#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0089#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1990#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5191#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4692#include "net/log/test_net_log_entry.h"
93#include "net/log/test_net_log_util.h"
Scott Violet0caaaf432018-03-24 00:43:5994#include "net/net_buildflags.h"
Lily Houghtonffe89daa02018-03-09 18:30:0395#include "net/proxy_resolution/proxy_resolution_service.h"
Ryan Hamiltona3ee93a72018-08-01 22:03:0896#include "net/quic/mock_crypto_client_stream_factory.h"
97#include "net/quic/quic_server_info.h"
zhongyi18ddddd2017-02-03 19:06:3698#include "net/socket/socket_test_util.h"
[email protected]c3456bb2011-12-12 22:22:1999#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:14100#include "net/ssl/channel_id_service.h"
David Benjamin76a40ad2018-02-24 22:22:08101#include "net/ssl/client_cert_identity_test_util.h"
nharperb7441ef2016-01-25 23:54:14102#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:57103#include "net/ssl/ssl_connection_status_flags.h"
David Benjamin76a40ad2018-02-24 22:22:08104#include "net/ssl/ssl_private_key.h"
tommycli59a63432015-11-06 00:10:55105#include "net/ssl/ssl_server_config.h"
[email protected]6e7845ae2013-03-29 21:48:11106#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:36107#include "net/test/embedded_test_server/embedded_test_server.h"
108#include "net/test/embedded_test_server/http_request.h"
109#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:01110#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21111#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43112#include "net/test/test_data_directory.h"
Bence Béky98447b12018-05-08 03:14:01113#include "net/test/test_with_scoped_task_environment.h"
mmenkefb18c772015-09-30 22:22:50114#include "net/test/url_request/url_request_failed_job.h"
Carlos ILaef65d62018-06-04 21:24:13115#include "net/test/url_request/url_request_mock_http_job.h"
rhalavatib7bd7c792017-04-27 05:25:16116#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34117#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43118#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52119#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50120#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14121#include "net/url_request/url_request_http_job.h"
Thiemo Nagel0793b9c532018-04-18 16:57:58122#include "net/url_request/url_request_http_job_histogram.h"
bengr1bf8e942014-11-07 01:36:50123#include "net/url_request/url_request_intercepting_job_factory.h"
124#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49125#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51126#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47127#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44128#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01129#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52130#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15131#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52132
Eric Romanefddd0a2017-10-10 02:14:25133#if defined(OS_FUCHSIA)
134#define USE_BUILTIN_CERT_VERIFIER
135#endif
136
brettwa1228ebb2016-10-28 03:51:34137#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55138#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29139#include "net/url_request/file_protocol_handler.h"
140#include "net/url_request/url_request_file_dir_job.h"
141#endif
142
brettwa1228ebb2016-10-28 03:51:34143#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47144#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29145#include "net/url_request/ftp_protocol_handler.h"
146#endif
147
[email protected]dffe8242012-03-20 15:14:27148#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48149#include "base/win/scoped_com_initializer.h"
[email protected]dffe8242012-03-20 15:14:27150#endif
151
mmenkefd9d15c2017-06-29 13:45:54152#if BUILDFLAG(ENABLE_REPORTING)
Julia Tuttlecba7d222018-02-23 19:37:27153#include "net/network_error_logging/network_error_logging_service.h"
Lily Chenfec60d92019-01-24 01:16:42154#include "net/network_error_logging/network_error_logging_test_util.h"
mmenkefd9d15c2017-06-29 13:45:54155#endif // BUILDFLAG(ENABLE_REPORTING)
156
Matt Muellerfb271992018-01-30 18:10:48157#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:25158#include "net/cert/cert_net_fetcher.h"
159#include "net/cert_net/cert_net_fetcher_impl.h"
160#endif
161
162#if defined(USE_NSS_CERTS)
163#include "net/cert_net/nss_ocsp.h"
164#endif
165
robpercival214763f2016-07-01 23:27:01166using net::test::IsError;
167using net::test::IsOk;
168
[email protected]ad65a3e2013-12-25 18:18:01169using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33170using base::Time;
halton.huoe4e45742014-12-08 07:55:46171using std::string;
[email protected]e1acf6f2008-10-27 20:43:33172
[email protected]7461a402011-03-24 23:19:51173namespace net {
174
initial.commit586acc5fe2008-07-26 22:42:52175namespace {
176
Martijn Croonenb1383da2017-10-11 11:56:35177namespace test_default {
178#include "net/http/transport_security_state_static_unittest_default.h"
xunjieli815ad5b2017-07-18 15:51:35179}
180
[email protected]42cba2fb2013-03-29 19:58:57181const base::string16 kChrome(ASCIIToUTF16("chrome"));
182const base::string16 kSecret(ASCIIToUTF16("secret"));
183const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44184
mmenke9f2ec60c2015-06-01 20:59:47185const base::FilePath::CharType kTestFilePath[] =
186 FILE_PATH_LITERAL("net/data/url_request_unittest");
187
Sergey Ulanovc4580e72017-09-13 23:30:11188#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
189 !defined(OS_FUCHSIA)
mmenke9f2ec60c2015-06-01 20:59:47190// Test file used in most FTP tests.
191const char kFtpTestFile[] = "BullRunSpeech.txt";
192#endif
193
[email protected]2bba3252013-04-08 19:50:59194// Tests load timing information in the case a fresh connection was used, with
195// no proxy.
[email protected]cba24642014-08-15 20:49:59196void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25197 int connect_timing_flags) {
198 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19199 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25200
201 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
202 EXPECT_FALSE(load_timing_info.request_start.is_null());
203
204 EXPECT_LE(load_timing_info.request_start,
205 load_timing_info.connect_timing.connect_start);
206 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
207 connect_timing_flags);
208 EXPECT_LE(load_timing_info.connect_timing.connect_end,
209 load_timing_info.send_start);
210 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38211 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
212 EXPECT_LE(load_timing_info.receive_headers_start,
213 load_timing_info.receive_headers_end);
[email protected]58e32bb2013-01-21 18:23:25214
[email protected]58e32bb2013-01-21 18:23:25215 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
216 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
217}
218
[email protected]2bba3252013-04-08 19:50:59219// Same as above, but with proxy times.
220void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59221 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59222 int connect_timing_flags) {
223 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19224 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59225
226 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
227 EXPECT_FALSE(load_timing_info.request_start.is_null());
228
229 EXPECT_LE(load_timing_info.request_start,
230 load_timing_info.proxy_resolve_start);
231 EXPECT_LE(load_timing_info.proxy_resolve_start,
232 load_timing_info.proxy_resolve_end);
233 EXPECT_LE(load_timing_info.proxy_resolve_end,
234 load_timing_info.connect_timing.connect_start);
235 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
236 connect_timing_flags);
237 EXPECT_LE(load_timing_info.connect_timing.connect_end,
238 load_timing_info.send_start);
239 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38240 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
241 EXPECT_LE(load_timing_info.receive_headers_start,
242 load_timing_info.receive_headers_end);
[email protected]2bba3252013-04-08 19:50:59243}
244
245// Same as above, but with a reused socket and proxy times.
246void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59247 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59248 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19249 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59250
251 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
252 EXPECT_FALSE(load_timing_info.request_start.is_null());
253
254 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
255
256 EXPECT_LE(load_timing_info.request_start,
257 load_timing_info.proxy_resolve_start);
258 EXPECT_LE(load_timing_info.proxy_resolve_start,
259 load_timing_info.proxy_resolve_end);
260 EXPECT_LE(load_timing_info.proxy_resolve_end,
261 load_timing_info.send_start);
262 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38263 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
264 EXPECT_LE(load_timing_info.receive_headers_start,
265 load_timing_info.receive_headers_end);
[email protected]2bba3252013-04-08 19:50:59266}
267
brettwa1228ebb2016-10-28 03:51:34268#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25269// Tests load timing information in the case of a cache hit, when no cache
270// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17271base::StringPiece TestNetResourceProvider(int key) {
272 return "header";
273}
274
275void FillBuffer(char* buffer, size_t len) {
276 static bool called = false;
277 if (!called) {
278 called = true;
279 int seed = static_cast<int>(Time::Now().ToInternalValue());
280 srand(seed);
281 }
282
283 for (size_t i = 0; i < len; i++) {
284 buffer[i] = static_cast<char>(rand());
285 if (!buffer[i])
286 buffer[i] = 'g';
287 }
288}
xunjielia6888202015-04-14 21:34:25289#endif
[email protected]e3a85452013-11-14 01:46:17290
[email protected]3b23a222013-05-15 21:33:25291void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59292 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25293 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19294 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25295
296 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
297 EXPECT_FALSE(load_timing_info.request_start.is_null());
298
299 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
300 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
301 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38302 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
303 EXPECT_LE(load_timing_info.receive_headers_start,
304 load_timing_info.receive_headers_end);
[email protected]3b23a222013-05-15 21:33:25305
306 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
307 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
308}
309
Sergey Ulanovc4580e72017-09-13 23:30:11310#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
311 !defined(OS_FUCHSIA)
[email protected]3b23a222013-05-15 21:33:25312// Tests load timing in the case that there is no HTTP response. This can be
313// used to test in the case of errors or non-HTTP requests.
314void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59315 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25316 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19317 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25318
319 // Only the request times should be non-null.
320 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
321 EXPECT_FALSE(load_timing_info.request_start.is_null());
322
323 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
324
325 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
326 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
327 EXPECT_TRUE(load_timing_info.send_start.is_null());
328 EXPECT_TRUE(load_timing_info.send_end.is_null());
Andrew Comminos1f2ff1cc2018-12-14 05:22:38329 EXPECT_TRUE(load_timing_info.receive_headers_start.is_null());
[email protected]58e32bb2013-01-21 18:23:25330 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
331}
xunjielia6888202015-04-14 21:34:25332#endif
[email protected]58e32bb2013-01-21 18:23:25333
mmenkefb18c772015-09-30 22:22:50334// Test power monitor source that can simulate entering suspend mode. Can't use
335// the one in base/ because it insists on bringing its own MessageLoop.
336class TestPowerMonitorSource : public base::PowerMonitorSource {
337 public:
Chris Watkins7a41d3552017-12-01 02:13:27338 TestPowerMonitorSource() = default;
339 ~TestPowerMonitorSource() override = default;
mmenkefb18c772015-09-30 22:22:50340
Colin Blundellc46597f2018-06-14 16:43:10341 void Shutdown() override {}
342
mmenkefb18c772015-09-30 22:22:50343 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
344
345 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
346
347 bool IsOnBatteryPowerImpl() override { return false; }
348
349 private:
350 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
351};
352
mmenkeed0498b2015-12-08 23:20:42353// Job that allows monitoring of its priority.
354class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
355 public:
356 // The latest priority of the job is always written to |request_priority_|.
357 PriorityMonitoringURLRequestJob(URLRequest* request,
358 NetworkDelegate* network_delegate,
359 RequestPriority* request_priority)
360 : URLRequestTestJob(request, network_delegate),
361 request_priority_(request_priority) {
362 *request_priority_ = DEFAULT_PRIORITY;
363 }
364
365 void SetPriority(RequestPriority priority) override {
366 *request_priority_ = priority;
367 URLRequestTestJob::SetPriority(priority);
368 }
369
370 private:
371 RequestPriority* const request_priority_;
372};
373
[email protected]71c64f62008-11-15 04:36:51374// Do a case-insensitive search through |haystack| for |needle|.
375bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50376 std::string::const_iterator it = std::search(
377 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
378 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51379 return it != haystack.end();
380}
381
danakj8522a25b2016-04-16 00:17:36382std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
383 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28384 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48385 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23386}
387
[email protected]96adadb2010-08-28 01:16:17388// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51389void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17390 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14391 uint16_t cipher_suite =
392 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29393 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17394}
395
[email protected]79e1fd62013-06-20 06:50:04396void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
397 const GURL& host_url) {
398 std::string sent_value;
399
400 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
401 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
402
403 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
404 EXPECT_EQ("keep-alive", sent_value);
405}
406
[email protected]dc5a5cf2012-09-26 02:49:30407// A network delegate that allows the user to choose a subset of request stages
408// to block in. When blocking, the delegate can do one of the following:
409// * synchronously return a pre-specified error code, or
410// * asynchronously return that value via an automatically called callback,
411// or
412// * block and wait for the user to do a callback.
413// Additionally, the user may also specify a redirect URL -- then each request
414// with the current URL different from the redirect target will be redirected
415// to that target, in the on-before-URL-request stage, independent of whether
416// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12417class BlockingNetworkDelegate : public TestNetworkDelegate {
418 public:
[email protected]dc5a5cf2012-09-26 02:49:30419 // Stages in which the delegate can block.
420 enum Stage {
[email protected]9045b8822012-01-13 20:35:35421 NOT_BLOCKED = 0,
422 ON_BEFORE_URL_REQUEST = 1 << 0,
423 ON_BEFORE_SEND_HEADERS = 1 << 1,
424 ON_HEADERS_RECEIVED = 1 << 2,
425 ON_AUTH_REQUIRED = 1 << 3
426 };
427
[email protected]dc5a5cf2012-09-26 02:49:30428 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59429 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30430 enum BlockMode {
431 SYNCHRONOUS, // No callback, returns specified return values.
432 AUTO_CALLBACK, // |this| posts a task to run the callback using the
433 // specified return codes.
434 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
435 // |auth_retval_| are ignored. In every blocking stage the
436 // message loop is quit.
437 };
438
439 // Creates a delegate which does not block at all.
440 explicit BlockingNetworkDelegate(BlockMode block_mode);
441
Wez2a31b222018-06-07 22:07:15442 // Runs the message loop until the delegate blocks.
443 void RunUntilBlocked();
444
[email protected]dc5a5cf2012-09-26 02:49:30445 // For users to trigger a callback returning |response|.
446 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
447 // Only call if |block_mode_| == USER_CALLBACK.
448 void DoCallback(int response);
449 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
450
451 // Setters.
452 void set_retval(int retval) {
453 ASSERT_NE(USER_CALLBACK, block_mode_);
454 ASSERT_NE(ERR_IO_PENDING, retval);
455 ASSERT_NE(OK, retval);
456 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35457 }
458
[email protected]dc5a5cf2012-09-26 02:49:30459 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
460 // |auth_credentials_| will be passed with the response.
461 void set_auth_retval(AuthRequiredResponse auth_retval) {
462 ASSERT_NE(USER_CALLBACK, block_mode_);
463 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
464 auth_retval_ = auth_retval;
465 }
466 void set_auth_credentials(const AuthCredentials& auth_credentials) {
467 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35468 }
469
[email protected]dc5a5cf2012-09-26 02:49:30470 void set_redirect_url(const GURL& url) {
471 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35472 }
473
[email protected]dc5a5cf2012-09-26 02:49:30474 void set_block_on(int block_on) {
475 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35476 }
477
[email protected]dc5a5cf2012-09-26 02:49:30478 // Allows the user to check in which state did we block.
479 Stage stage_blocked_for_callback() const {
480 EXPECT_EQ(USER_CALLBACK, block_mode_);
481 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35482 }
483
484 private:
Wez2a31b222018-06-07 22:07:15485 void OnBlocked();
486
David Benjamind1f287bf2018-06-12 01:57:20487 void RunCallback(int response, CompletionOnceCallback callback);
488 void RunAuthCallback(AuthRequiredResponse response, AuthCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30489
[email protected]9045b8822012-01-13 20:35:35490 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20491 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20492 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:20493 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35494
ryansturm2343cb62016-06-15 01:09:00495 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20496 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:00497 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35498
dchengb03027d2014-10-21 12:00:20499 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35500 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20501 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32502 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16503 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13504 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35505
dchengb03027d2014-10-21 12:00:20506 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35507 URLRequest* request,
508 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20509 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:13510 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35511
[email protected]dc5a5cf2012-09-26 02:49:30512 // Resets the callbacks and |stage_blocked_for_callback_|.
513 void Reset();
[email protected]9045b8822012-01-13 20:35:35514
[email protected]dc5a5cf2012-09-26 02:49:30515 // Checks whether we should block in |stage|. If yes, returns an error code
516 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
David Benjamind1f287bf2018-06-12 01:57:20517 int MaybeBlockStage(Stage stage, CompletionOnceCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30518
519 // Configuration parameters, can be adjusted by public methods:
520 const BlockMode block_mode_;
521
522 // Values returned on blocking stages when mode is SYNCHRONOUS or
523 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
524 int retval_; // To be returned in non-auth stages.
525 AuthRequiredResponse auth_retval_;
526
[email protected]5f714132014-03-26 10:41:16527 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30528 int block_on_; // Bit mask: in which stages to block.
529
530 // |auth_credentials_| will be copied to |*target_auth_credential_| on
531 // callback.
532 AuthCredentials auth_credentials_;
533 AuthCredentials* target_auth_credentials_;
534
535 // Internal variables, not set by not the user:
536 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
537 // USER_CALLBACK).
538 Stage stage_blocked_for_callback_;
539
540 // Callback objects stored during blocking stages.
David Benjamind1f287bf2018-06-12 01:57:20541 CompletionOnceCallback callback_;
[email protected]9045b8822012-01-13 20:35:35542 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30543
Wez2a31b222018-06-07 22:07:15544 // Closure to run to exit RunUntilBlocked().
545 base::OnceClosure on_blocked_;
546
[email protected]dc5a5cf2012-09-26 02:49:30547 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
548
549 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35550};
551
[email protected]dc5a5cf2012-09-26 02:49:30552BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
553 : block_mode_(block_mode),
554 retval_(OK),
555 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
556 block_on_(0),
557 target_auth_credentials_(NULL),
558 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32559 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30560}
561
Wez2a31b222018-06-07 22:07:15562void BlockingNetworkDelegate::RunUntilBlocked() {
563 base::RunLoop run_loop;
564 on_blocked_ = run_loop.QuitClosure();
565 run_loop.Run();
566}
567
[email protected]dc5a5cf2012-09-26 02:49:30568void BlockingNetworkDelegate::DoCallback(int response) {
569 ASSERT_EQ(USER_CALLBACK, block_mode_);
570 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
571 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20572 CompletionOnceCallback callback = std::move(callback_);
[email protected]dc5a5cf2012-09-26 02:49:30573 Reset();
Wez2a31b222018-06-07 22:07:15574
575 // |callback| may trigger completion of a request, so post it as a task, so
576 // it will run under a subsequent TestDelegate::RunUntilComplete() loop.
577 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20578 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
579 weak_factory_.GetWeakPtr(), response,
580 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30581}
582
583void BlockingNetworkDelegate::DoAuthCallback(
584 NetworkDelegate::AuthRequiredResponse response) {
585 ASSERT_EQ(USER_CALLBACK, block_mode_);
586 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20587 AuthCallback auth_callback = std::move(auth_callback_);
[email protected]dc5a5cf2012-09-26 02:49:30588 Reset();
David Benjamind1f287bf2018-06-12 01:57:20589 RunAuthCallback(response, std::move(auth_callback));
[email protected]dc5a5cf2012-09-26 02:49:30590}
591
Wez2a31b222018-06-07 22:07:15592void BlockingNetworkDelegate::OnBlocked() {
593 // If this fails due to |on_blocked_| being null then OnBlocked() was run by
594 // a RunLoop other than RunUntilBlocked(), indicating a bug in the calling
595 // test.
596 std::move(on_blocked_).Run();
597}
598
[email protected]dc5a5cf2012-09-26 02:49:30599void BlockingNetworkDelegate::RunCallback(int response,
David Benjamind1f287bf2018-06-12 01:57:20600 CompletionOnceCallback callback) {
601 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30602}
603
604void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
David Benjamind1f287bf2018-06-12 01:57:20605 AuthCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30606 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
607 ASSERT_TRUE(target_auth_credentials_ != NULL);
608 *target_auth_credentials_ = auth_credentials_;
609 }
David Benjamind1f287bf2018-06-12 01:57:20610 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30611}
612
David Benjamind1f287bf2018-06-12 01:57:20613int BlockingNetworkDelegate::OnBeforeURLRequest(URLRequest* request,
614 CompletionOnceCallback callback,
615 GURL* new_url) {
[email protected]dc5a5cf2012-09-26 02:49:30616 if (redirect_url_ == request->url())
617 return OK; // We've already seen this request and redirected elsewhere.
618
David Benjamind1f287bf2018-06-12 01:57:20619 // TestNetworkDelegate always completes synchronously.
620 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
621 request, base::NullCallback(), new_url));
[email protected]dc5a5cf2012-09-26 02:49:30622
623 if (!redirect_url_.is_empty())
624 *new_url = redirect_url_;
625
David Benjamind1f287bf2018-06-12 01:57:20626 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30627}
628
ryansturm2343cb62016-06-15 01:09:00629int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30630 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20631 CompletionOnceCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30632 HttpRequestHeaders* headers) {
David Benjamind1f287bf2018-06-12 01:57:20633 // TestNetworkDelegate always completes synchronously.
634 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
635 request, base::NullCallback(), headers));
[email protected]dc5a5cf2012-09-26 02:49:30636
David Benjamind1f287bf2018-06-12 01:57:20637 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30638}
639
640int BlockingNetworkDelegate::OnHeadersReceived(
641 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20642 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32643 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16644 scoped_refptr<HttpResponseHeaders>* override_response_headers,
645 GURL* allowed_unsafe_redirect_url) {
David Benjamind1f287bf2018-06-12 01:57:20646 // TestNetworkDelegate always completes synchronously.
647 CHECK_NE(ERR_IO_PENDING,
648 TestNetworkDelegate::OnHeadersReceived(
649 request, base::NullCallback(), original_response_headers,
650 override_response_headers, allowed_unsafe_redirect_url));
[email protected]dc5a5cf2012-09-26 02:49:30651
David Benjamind1f287bf2018-06-12 01:57:20652 return MaybeBlockStage(ON_HEADERS_RECEIVED, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30653}
654
655NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
656 URLRequest* request,
657 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20658 AuthCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30659 AuthCredentials* credentials) {
David Benjamind1f287bf2018-06-12 01:57:20660 // TestNetworkDelegate always completes synchronously.
661 CHECK_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING,
662 TestNetworkDelegate::OnAuthRequired(
663 request, auth_info, base::NullCallback(), credentials));
[email protected]dc5a5cf2012-09-26 02:49:30664 // Check that the user has provided callback for the previous blocked stage.
665 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
666
667 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
668 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
669 }
670
671 target_auth_credentials_ = credentials;
672
673 switch (block_mode_) {
674 case SYNCHRONOUS:
675 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
676 *target_auth_credentials_ = auth_credentials_;
677 return auth_retval_;
678
679 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45680 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20681 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunAuthCallback,
682 weak_factory_.GetWeakPtr(), auth_retval_,
683 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30684 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
685
686 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20687 auth_callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30688 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
Wez2a31b222018-06-07 22:07:15689 // We may reach here via a callback prior to RunUntilBlocked(), so post
690 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45691 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15692 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
693 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30694 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
695 }
696 NOTREACHED();
697 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
698}
699
700void BlockingNetworkDelegate::Reset() {
701 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
702 stage_blocked_for_callback_ = NOT_BLOCKED;
703 callback_.Reset();
704 auth_callback_.Reset();
705}
706
707int BlockingNetworkDelegate::MaybeBlockStage(
708 BlockingNetworkDelegate::Stage stage,
David Benjamind1f287bf2018-06-12 01:57:20709 CompletionOnceCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30710 // Check that the user has provided callback for the previous blocked stage.
711 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
712
713 if ((block_on_ & stage) == 0) {
714 return OK;
715 }
716
717 switch (block_mode_) {
718 case SYNCHRONOUS:
719 EXPECT_NE(OK, retval_);
720 return retval_;
721
722 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45723 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20724 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
725 weak_factory_.GetWeakPtr(), retval_,
726 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30727 return ERR_IO_PENDING;
728
729 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20730 callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30731 stage_blocked_for_callback_ = stage;
Wez2a31b222018-06-07 22:07:15732 // We may reach here via a callback prior to RunUntilBlocked(), so post
733 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45734 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15735 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
736 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30737 return ERR_IO_PENDING;
738 }
739 NOTREACHED();
740 return 0;
741}
742
[email protected]d5a4dd62012-05-23 01:41:04743class TestURLRequestContextWithProxy : public TestURLRequestContext {
744 public:
745 // Does not own |delegate|.
746 TestURLRequestContextWithProxy(const std::string& proxy,
747 NetworkDelegate* delegate)
748 : TestURLRequestContext(true) {
Lily Houghton8c2f97d2018-01-22 05:06:59749 context_storage_.set_proxy_resolution_service(
Ramin Halavatica8d5252018-03-12 05:33:49750 ProxyResolutionService::CreateFixed(proxy,
751 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]d5a4dd62012-05-23 01:41:04752 set_network_delegate(delegate);
753 Init();
754 }
Chris Watkins7a41d3552017-12-01 02:13:27755 ~TestURLRequestContextWithProxy() override = default;
[email protected]d5a4dd62012-05-23 01:41:04756};
757
stefanocsbd5be5202016-06-10 03:37:55758// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01759// URI and report to be sent.
760class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55761 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01762 public:
Chris Watkins7a41d3552017-12-01 02:13:27763 MockCertificateReportSender() = default;
764 ~MockCertificateReportSender() override = default;
estark06e0dac2015-08-07 21:56:01765
meacer5d4dc5a2017-04-27 20:37:48766 void Send(const GURL& report_uri,
767 base::StringPiece content_type,
768 base::StringPiece report,
769 const base::Callback<void()>& success_callback,
770 const base::Callback<void(const GURL&, int, int)>& error_callback)
771 override {
estark06e0dac2015-08-07 21:56:01772 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44773 report.CopyToString(&latest_report_);
774 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01775 }
estark06e0dac2015-08-07 21:56:01776 const GURL& latest_report_uri() { return latest_report_uri_; }
777 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44778 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01779
780 private:
781 GURL latest_report_uri_;
782 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44783 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01784};
785
dadrian612337a2016-07-20 22:36:58786// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
787// This is needed because after the certificate failure, the URLRequest will
788// retry the connection, and return a partial SSLInfo with a cached cert status.
789// The partial SSLInfo does not have the OCSP information filled out.
790class OCSPErrorTestDelegate : public TestDelegate {
791 public:
792 void OnSSLCertificateError(URLRequest* request,
793 const SSLInfo& ssl_info,
794 bool fatal) override {
795 ssl_info_ = ssl_info;
796 on_ssl_certificate_error_called_ = true;
797 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
798 }
799
800 bool on_ssl_certificate_error_called() {
801 return on_ssl_certificate_error_called_;
802 }
803
804 SSLInfo ssl_info() { return ssl_info_; }
805
806 private:
807 bool on_ssl_certificate_error_called_ = false;
808 SSLInfo ssl_info_;
809};
810
[email protected]d5a4dd62012-05-23 01:41:04811} // namespace
812
[email protected]a592c0432012-12-01 18:10:29813// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
Bence Béky98447b12018-05-08 03:14:01814class URLRequestTest : public PlatformTest, public WithScopedTaskEnvironment {
[email protected]abb26092010-11-11 22:19:00815 public:
Ryan Sleevib8449e02018-07-15 04:31:07816 URLRequestTest()
817 : default_context_(std::make_unique<TestURLRequestContext>(true)) {
818 default_context_->set_network_delegate(&default_network_delegate_);
819 default_context_->set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50820 job_factory_impl_ = new URLRequestJobFactoryImpl();
821 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50822 }
bengr1bf8e942014-11-07 01:36:50823
dcheng67be2b1f2014-10-27 21:47:29824 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18825 // URLRequestJobs may post clean-up tasks on destruction.
826 base::RunLoop().RunUntilIdle();
Martijn Croonenb1383da2017-10-11 11:56:35827
828 SetTransportSecurityStateSourceForTesting(nullptr);
[email protected]e4034ad2013-09-20 08:36:18829 }
[email protected]87a09a92011-07-14 15:50:50830
dcheng2339883c2014-12-23 00:23:05831 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50832 SetUpFactory();
Ryan Sleevib8449e02018-07-15 04:31:07833 default_context_->set_job_factory(job_factory_.get());
834 default_context_->Init();
bengr1bf8e942014-11-07 01:36:50835 PlatformTest::SetUp();
836 }
837
Ryan Sleevib8449e02018-07-15 04:31:07838 void TearDown() override { default_context_.reset(); }
839
bengr1bf8e942014-11-07 01:36:50840 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20841 job_factory_impl_->SetProtocolHandler(
Bence Béky8f9d7d3952017-10-09 19:58:04842 "data", std::make_unique<DataProtocolHandler>());
brettwa1228ebb2016-10-28 03:51:34843#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50844 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19845 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07846 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50847#endif
848 }
849
850 TestNetworkDelegate* default_network_delegate() {
851 return &default_network_delegate_;
852 }
853
Ryan Sleevib8449e02018-07-15 04:31:07854 TestURLRequestContext& default_context() const { return *default_context_; }
bengr1bf8e942014-11-07 01:36:50855
[email protected]3c5ca8c2011-09-29 01:14:51856 // Adds the TestJobInterceptor to the default context.
857 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23858 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20859 job_factory_impl_->SetProtocolHandler("http", nullptr);
860 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36861 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23862 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51863 }
864
Sergey Ulanov2e49f492017-09-14 19:37:51865 // Creates a temp test file and writes |data| to the file. The file will be
866 // deleted after the test completes.
867 void CreateTestFile(const char* data,
868 size_t data_size,
869 base::FilePath* test_file) {
870 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
871 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
872 // now, Mac and Android bots return a path with a symbolic link.
873 base::FilePath absolute_temp_dir =
874 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
875
876 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
877 ASSERT_EQ(static_cast<int>(data_size),
878 base::WriteFile(*test_file, data, data_size));
879 }
880
[email protected]87a09a92011-07-14 15:50:50881 protected:
vishal.b62985ca92015-04-17 08:45:51882 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24883 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50884 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36885 std::unique_ptr<URLRequestJobFactory> job_factory_;
Ryan Sleevib8449e02018-07-15 04:31:07886 std::unique_ptr<TestURLRequestContext> default_context_;
Sergey Ulanov2e49f492017-09-14 19:37:51887 base::ScopedTempDir temp_dir_;
[email protected]7a0bb4bf2008-11-19 21:41:48888};
889
satoruxddac0442017-05-29 06:06:18890// This NetworkDelegate is picky about what files are accessible. Only
891// whitelisted files are allowed.
892class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
893 public:
Chris Watkins7a41d3552017-12-01 02:13:27894 CookieBlockingNetworkDelegate() = default;
895 ;
satoruxddac0442017-05-29 06:06:18896
897 // Adds |directory| to the access white list.
898 void AddToWhitelist(const base::FilePath& directory) {
899 whitelist_.insert(directory);
900 }
901
902 private:
903 // Returns true if |path| matches the white list.
904 bool OnCanAccessFileInternal(const base::FilePath& path) const {
905 for (const auto& directory : whitelist_) {
906 if (directory == path || directory.IsParent(path))
907 return true;
908 }
909 return false;
910 }
911
912 // Returns true only if both |original_path| and |absolute_path| match the
913 // white list.
914 bool OnCanAccessFile(const URLRequest& request,
915 const base::FilePath& original_path,
916 const base::FilePath& absolute_path) const override {
917 return (OnCanAccessFileInternal(original_path) &&
918 OnCanAccessFileInternal(absolute_path));
919 }
920
921 std::set<base::FilePath> whitelist_;
922
923 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
924};
925
[email protected]316c1e5e2012-09-12 15:17:44926TEST_F(URLRequestTest, AboutBlankTest) {
927 TestDelegate d;
928 {
rhalavatib7bd7c792017-04-27 05:25:16929 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:07930 default_context().CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
931 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44932
[email protected]f7022f32014-08-21 16:32:19933 r->Start();
934 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44935
Wez2a31b222018-06-07 22:07:15936 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44937
[email protected]f7022f32014-08-21 16:32:19938 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44939 EXPECT_FALSE(d.received_data_before_response());
940 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19941 EXPECT_EQ("", r->GetSocketAddress().host());
942 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04943
944 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19945 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44946 }
947}
948
949TEST_F(URLRequestTest, DataURLImageTest) {
950 TestDelegate d;
951 {
952 // Use our nice little Chrome logo.
Ryan Sleevib8449e02018-07-15 04:31:07953 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
danakj8522a25b2016-04-16 00:17:36954 GURL("data:image/png;base64,"
955 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
956 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
957 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
958 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
959 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
960 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
961 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
962 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
963 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
964 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
965 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
966 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
967 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
968 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
969 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
970 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
971 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
972 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
973 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16974 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44975
[email protected]f7022f32014-08-21 16:32:19976 r->Start();
977 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44978
Wez2a31b222018-06-07 22:07:15979 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44980
[email protected]f7022f32014-08-21 16:32:19981 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44982 EXPECT_FALSE(d.received_data_before_response());
983 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19984 EXPECT_EQ("", r->GetSocketAddress().host());
985 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04986
987 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19988 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44989 }
990}
991
brettwa1228ebb2016-10-28 03:51:34992#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44993TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51994 const char kTestFileContent[] = "Hello";
995 base::FilePath test_file;
996 ASSERT_NO_FATAL_FAILURE(
997 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04998
Sergey Ulanov2e49f492017-09-14 19:37:51999 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441000
1001 TestDelegate d;
1002 {
Ryan Sleevib8449e02018-07-15 04:31:071003 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511004 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441005
[email protected]f7022f32014-08-21 16:32:191006 r->Start();
1007 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441008
Wez2a31b222018-06-07 22:07:151009 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441010
[email protected]f7022f32014-08-21 16:32:191011 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441012 EXPECT_EQ(1, d.response_started_count());
1013 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:511014 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
[email protected]f7022f32014-08-21 16:32:191015 EXPECT_EQ("", r->GetSocketAddress().host());
1016 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:041017
1018 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:191019 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:441020 }
1021}
1022
[email protected]ba40bb762012-12-17 07:11:041023TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:511024 const char kTestFileContent[] = "Hello";
1025 base::FilePath test_file;
1026 ASSERT_NO_FATAL_FAILURE(
1027 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
1028
1029 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:041030
1031 TestDelegate d;
1032 {
Ryan Sleevib8449e02018-07-15 04:31:071033 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511034 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:041035
[email protected]f7022f32014-08-21 16:32:191036 r->Start();
1037 EXPECT_TRUE(r->is_pending());
1038 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:041039 }
[email protected]79e1fd62013-06-20 06:50:041040 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:041041 // destroyed.
[email protected]255620da2013-08-19 13:14:291042 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041043}
1044
[email protected]316c1e5e2012-09-12 15:17:441045TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1046 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361047 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441048 FillBuffer(buffer.get(), buffer_size);
1049
Sergey Ulanov2e49f492017-09-14 19:37:511050 base::FilePath test_file;
1051 ASSERT_NO_FATAL_FAILURE(
1052 CreateTestFile(buffer.get(), buffer_size, &test_file));
1053 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441054
1055 const size_t first_byte_position = 500;
1056 const size_t last_byte_position = buffer_size - first_byte_position;
1057 const size_t content_length = last_byte_position - first_byte_position + 1;
1058 std::string partial_buffer_string(buffer.get() + first_byte_position,
1059 buffer.get() + last_byte_position + 1);
1060
1061 TestDelegate d;
1062 {
Ryan Sleevib8449e02018-07-15 04:31:071063 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161064 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441065
1066 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381067 headers.SetHeader(
1068 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591069 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381070 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191071 r->SetExtraRequestHeaders(headers);
1072 r->Start();
1073 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441074
Wez2a31b222018-06-07 22:07:151075 d.RunUntilComplete();
1076
[email protected]f7022f32014-08-21 16:32:191077 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441078 EXPECT_EQ(1, d.response_started_count());
1079 EXPECT_FALSE(d.received_data_before_response());
1080 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1081 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1082 EXPECT_TRUE(partial_buffer_string == d.data_received());
1083 }
[email protected]316c1e5e2012-09-12 15:17:441084}
1085
1086TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1087 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361088 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441089 FillBuffer(buffer.get(), buffer_size);
1090
Sergey Ulanov2e49f492017-09-14 19:37:511091 base::FilePath test_file;
1092 ASSERT_NO_FATAL_FAILURE(
1093 CreateTestFile(buffer.get(), buffer_size, &test_file));
1094 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441095
1096 const size_t first_byte_position = 500;
1097 const size_t last_byte_position = buffer_size - 1;
1098 const size_t content_length = last_byte_position - first_byte_position + 1;
1099 std::string partial_buffer_string(buffer.get() + first_byte_position,
1100 buffer.get() + last_byte_position + 1);
1101
1102 TestDelegate d;
1103 {
Ryan Sleevib8449e02018-07-15 04:31:071104 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161105 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441106
1107 HttpRequestHeaders headers;
1108 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591109 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381110 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191111 r->SetExtraRequestHeaders(headers);
1112 r->Start();
1113 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441114
[email protected]255620da2013-08-19 13:14:291115 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191116 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441117 EXPECT_EQ(1, d.response_started_count());
1118 EXPECT_FALSE(d.received_data_before_response());
1119 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1120 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1121 EXPECT_TRUE(partial_buffer_string == d.data_received());
1122 }
[email protected]316c1e5e2012-09-12 15:17:441123}
1124
1125TEST_F(URLRequestTest, FileTestMultipleRanges) {
1126 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361127 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441128 FillBuffer(buffer.get(), buffer_size);
1129
Sergey Ulanov2e49f492017-09-14 19:37:511130 base::FilePath test_file;
1131 ASSERT_NO_FATAL_FAILURE(
1132 CreateTestFile(buffer.get(), buffer_size, &test_file));
1133 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441134
1135 TestDelegate d;
1136 {
Ryan Sleevib8449e02018-07-15 04:31:071137 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161138 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441139
1140 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381141 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191142 r->SetExtraRequestHeaders(headers);
1143 r->Start();
1144 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441145
Wez2a31b222018-06-07 22:07:151146 d.RunUntilComplete();
1147
[email protected]316c1e5e2012-09-12 15:17:441148 EXPECT_TRUE(d.request_failed());
1149 }
[email protected]316c1e5e2012-09-12 15:17:441150}
1151
[email protected]3ca8b362013-11-11 22:18:071152TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511153 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071154 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511155 ASSERT_NO_FATAL_FAILURE(
1156 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1157
satoruxddac0442017-05-29 06:06:181158 // The directory part of the path returned from CreateTemporaryFileInDir()
1159 // can be slightly different from |absolute_temp_dir| on Windows.
1160 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1161 // Hence the test should use the directory name of |test_file|, rather than
1162 // |absolute_temp_dir|, for whitelisting.
1163 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591164 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071165 {
1166 TestDelegate d;
satoruxddac0442017-05-29 06:06:181167 CookieBlockingNetworkDelegate network_delegate;
1168 network_delegate.AddToWhitelist(real_temp_dir);
Ryan Sleevib8449e02018-07-15 04:31:071169 default_context().set_network_delegate(&network_delegate);
1170 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161171 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191172 r->Start();
Wez2a31b222018-06-07 22:07:151173 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181174 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071175 EXPECT_FALSE(d.request_failed());
1176 EXPECT_EQ(test_data, d.data_received());
1177 }
1178
1179 {
1180 TestDelegate d;
satoruxddac0442017-05-29 06:06:181181 CookieBlockingNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:071182 default_context().set_network_delegate(&network_delegate);
1183 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161184 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191185 r->Start();
Wez2a31b222018-06-07 22:07:151186 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181187 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071188 EXPECT_TRUE(d.request_failed());
1189 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181190 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071191 }
1192}
1193
Wez35539132018-07-17 11:26:051194#if defined(OS_POSIX) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181195
1196TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511197 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181198 // Get an absolute path since temp_dir can contain a symbolic link.
1199 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511200 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181201
1202 // Create a good directory (will be whitelisted) and a good file.
1203 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1204 ASSERT_TRUE(base::CreateDirectory(good_dir));
1205 base::FilePath good_file;
1206 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1207 std::string good_data("good");
1208 base::WriteFile(good_file, good_data.data(), good_data.size());
1209 // See the comment in AllowFileURLs() for why this is done.
1210 base::FilePath real_good_dir = good_file.DirName();
1211
1212 // Create a bad directory (will not be whitelisted) and a bad file.
1213 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1214 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1215 base::FilePath bad_file;
1216 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1217 std::string bad_data("bad");
1218 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1219
1220 // This symlink will point to the good file. Access to the symlink will be
1221 // allowed as both the symlink and the destination file are in the same
1222 // good directory.
1223 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1224 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1225 GURL good_file_url = FilePathToFileURL(good_symlink);
1226 // This symlink will point to the bad file. Even though the symlink is in
1227 // the good directory, access to the symlink will be rejected since it
1228 // points to the bad file.
1229 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1230 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1231 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1232
1233 CookieBlockingNetworkDelegate network_delegate;
1234 network_delegate.AddToWhitelist(real_good_dir);
1235 {
1236 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071237 default_context().set_network_delegate(&network_delegate);
1238 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371239 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181240 r->Start();
Wez2a31b222018-06-07 22:07:151241 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181242 // good_file_url should be allowed.
1243 EXPECT_FALSE(d.request_failed());
1244 EXPECT_EQ(good_data, d.data_received());
1245 }
1246
1247 {
1248 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071249 default_context().set_network_delegate(&network_delegate);
1250 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371251 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181252 r->Start();
Wez2a31b222018-06-07 22:07:151253 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181254 // bad_file_url should be rejected.
1255 EXPECT_TRUE(d.request_failed());
1256 EXPECT_EQ("", d.data_received());
1257 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1258 }
1259}
1260
1261TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511262 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181263 // Get an absolute path since temp_dir can contain a symbolic link.
1264 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511265 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181266
1267 // Create a good directory (will be whitelisted).
1268 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1269 ASSERT_TRUE(base::CreateDirectory(good_dir));
1270
1271 // Create a bad directory (will not be whitelisted).
1272 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1273 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1274
1275 // This symlink will point to the good directory. Access to the symlink
1276 // will be allowed as the symlink is in the good dir that'll be white
1277 // listed.
1278 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1279 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1280 GURL good_file_url = FilePathToFileURL(good_symlink);
1281 // This symlink will point to the bad directory. Even though the symlink is
1282 // in the good directory, access to the symlink will be rejected since it
1283 // points to the bad directory.
1284 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1285 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1286 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1287
1288 CookieBlockingNetworkDelegate network_delegate;
1289 network_delegate.AddToWhitelist(good_dir);
1290 {
1291 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071292 default_context().set_network_delegate(&network_delegate);
1293 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371294 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181295 r->Start();
Wez2a31b222018-06-07 22:07:151296 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181297 // good_file_url should be allowed.
1298 EXPECT_FALSE(d.request_failed());
1299 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1300 }
1301
1302 {
1303 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071304 default_context().set_network_delegate(&network_delegate);
1305 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371306 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181307 r->Start();
Wez2a31b222018-06-07 22:07:151308 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181309 // bad_file_url should be rejected.
1310 EXPECT_TRUE(d.request_failed());
1311 EXPECT_EQ("", d.data_received());
1312 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1313 }
1314}
1315
Wez35539132018-07-17 11:26:051316#endif // defined(OS_POSIX)
[email protected]316c1e5e2012-09-12 15:17:441317
1318TEST_F(URLRequestTest, FileDirCancelTest) {
1319 // Put in mock resource provider.
1320 NetModule::SetResourceProvider(TestNetResourceProvider);
1321
1322 TestDelegate d;
1323 {
[email protected]6cdfd7f2013-02-08 20:40:151324 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:191325 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
[email protected]316c1e5e2012-09-12 15:17:441326 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1327 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1328
Ryan Sleevib8449e02018-07-15 04:31:071329 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161330 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1331 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191332 req->Start();
1333 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441334
1335 d.set_cancel_in_received_data_pending(true);
1336
Wez2a31b222018-06-07 22:07:151337 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441338 }
1339
1340 // Take out mock resource provider.
1341 NetModule::SetResourceProvider(NULL);
1342}
1343
[email protected]5f9581402013-10-30 13:08:321344TEST_F(URLRequestTest, FileDirOutputSanity) {
1345 // Verify the general sanity of the the output of the file:
1346 // directory lister by checking for the output of a known existing
1347 // file.
1348 const char sentinel_name[] = "filedir-sentinel";
1349
1350 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191351 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471352 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321353
1354 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161355 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071356 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1357 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191358 req->Start();
Wez2a31b222018-06-07 22:07:151359 d.RunUntilComplete();
[email protected]5f9581402013-10-30 13:08:321360
1361 // Generate entry for the sentinel file.
1362 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581363 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491364 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321365 EXPECT_GT(info.size, 0);
1366 std::string sentinel_output = GetDirectoryListingEntry(
1367 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181368 std::string(sentinel_name), false /* is_dir */, info.size,
1369
[email protected]5f9581402013-10-30 13:08:321370 info.last_modified);
1371
1372 ASSERT_LT(0, d.bytes_received());
1373 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501374 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321375 // Check for the entry generated for the "sentinel" file.
1376 const std::string& data = d.data_received();
1377 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1378}
1379
[email protected]316c1e5e2012-09-12 15:17:441380TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1381 // There is an implicit redirect when loading a file path that matches a
1382 // directory and does not end with a slash. Ensure that following such
1383 // redirects does not crash. See http://crbug.com/18686.
1384
[email protected]6cdfd7f2013-02-08 20:40:151385 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191386 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471387 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441388
1389 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161390 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071391 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1392 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191393 req->Start();
Wez2a31b222018-06-07 22:07:151394 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441395
1396 ASSERT_EQ(1, d.received_redirect_count());
1397 ASSERT_LT(0, d.bytes_received());
1398 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501399 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441400}
1401
1402#if defined(OS_WIN)
1403// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1404TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1405 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071406 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161407 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191408 req->Start();
Wez2a31b222018-06-07 22:07:151409 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441410
1411 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501412 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441413}
[email protected]5ecf7cb282014-05-11 01:49:551414#endif // defined(OS_WIN)
1415
brettwa1228ebb2016-10-28 03:51:341416#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551417
1418TEST_F(URLRequestTest, InvalidUrlTest) {
1419 TestDelegate d;
1420 {
rhalavatib7bd7c792017-04-27 05:25:161421 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:071422 default_context().CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1423 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551424
[email protected]f7022f32014-08-21 16:32:191425 r->Start();
1426 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551427
Wez2a31b222018-06-07 22:07:151428 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551429 EXPECT_TRUE(d.request_failed());
1430 }
1431}
1432
jochen0e3b3a62014-09-16 18:31:231433TEST_F(URLRequestTest, InvalidReferrerTest) {
1434 TestURLRequestContext context;
1435 TestNetworkDelegate network_delegate;
1436 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1437 context.set_network_delegate(&network_delegate);
1438 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361439 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161440 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1441 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231442 req->SetReferrer("https://somewhere.com/");
1443
1444 req->Start();
Wez2a31b222018-06-07 22:07:151445 d.RunUntilComplete();
jochen0e3b3a62014-09-16 18:31:231446 EXPECT_TRUE(d.request_failed());
1447}
1448
[email protected]5ecf7cb282014-05-11 01:49:551449#if defined(OS_WIN)
1450TEST_F(URLRequestTest, ResolveShortcutTest) {
1451 base::FilePath app_path;
Avi Drissman5c80d832018-05-01 17:01:191452 base::PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471453 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551454 app_path = app_path.AppendASCII("with-headers.html");
1455
1456 std::wstring lnk_path = app_path.value() + L".lnk";
1457
1458 base::win::ScopedCOMInitializer com_initializer;
1459
1460 // Temporarily create a shortcut for test
1461 {
Robert Liaoc88f99d12017-10-17 21:48:331462 Microsoft::WRL::ComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161463 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
1464 CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
Robert Liaoc88f99d12017-10-17 21:48:331465 Microsoft::WRL::ComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001466 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
[email protected]5ecf7cb282014-05-11 01:49:551467 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1468 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1469 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1470 }
1471
1472 TestDelegate d;
1473 {
Ryan Sleevib8449e02018-07-15 04:31:071474 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161475 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1476 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551477
[email protected]f7022f32014-08-21 16:32:191478 r->Start();
1479 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551480
Wez2a31b222018-06-07 22:07:151481 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551482
1483 WIN32_FILE_ATTRIBUTE_DATA data;
1484 GetFileAttributesEx(app_path.value().c_str(),
1485 GetFileExInfoStandard, &data);
1486 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1487 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1488 FILE_ATTRIBUTE_NORMAL, NULL);
1489 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361490 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551491 DWORD read_size;
1492 BOOL result;
1493 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1494 &read_size, NULL);
1495 std::string content(buffer.get(), read_size);
1496 CloseHandle(file);
1497
[email protected]f7022f32014-08-21 16:32:191498 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551499 EXPECT_EQ(1, d.received_redirect_count());
1500 EXPECT_EQ(content, d.data_received());
1501 }
1502
1503 // Clean the shortcut
1504 DeleteFile(lnk_path.c_str());
1505}
1506#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441507
1508// Custom URLRequestJobs for use with interceptor tests
1509class RestartTestJob : public URLRequestTestJob {
1510 public:
1511 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1512 : URLRequestTestJob(request, network_delegate, true) {}
1513 protected:
dchengb03027d2014-10-21 12:00:201514 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441515 private:
Chris Watkins7a41d3552017-12-01 02:13:271516 ~RestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441517};
1518
1519class CancelTestJob : public URLRequestTestJob {
1520 public:
1521 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1522 : URLRequestTestJob(request, network_delegate, true) {}
1523 protected:
dchengb03027d2014-10-21 12:00:201524 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441525 private:
Chris Watkins7a41d3552017-12-01 02:13:271526 ~CancelTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441527};
1528
1529class CancelThenRestartTestJob : public URLRequestTestJob {
1530 public:
1531 explicit CancelThenRestartTestJob(URLRequest* request,
1532 NetworkDelegate* network_delegate)
1533 : URLRequestTestJob(request, network_delegate, true) {
1534 }
1535 protected:
dchengb03027d2014-10-21 12:00:201536 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441537 request_->Cancel();
1538 this->NotifyRestartRequired();
1539 }
1540 private:
Chris Watkins7a41d3552017-12-01 02:13:271541 ~CancelThenRestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441542};
1543
bengr1bf8e942014-11-07 01:36:501544// An Interceptor for use with interceptor tests.
1545class MockURLRequestInterceptor : public URLRequestInterceptor {
1546 public:
1547 // Static getters for canned response header and data strings.
1548 static std::string ok_data() {
1549 return URLRequestTestJob::test_data_1();
1550 }
1551
1552 static std::string ok_headers() {
1553 return URLRequestTestJob::test_headers();
1554 }
1555
1556 static std::string redirect_data() {
1557 return std::string();
1558 }
1559
1560 static std::string redirect_headers() {
1561 return URLRequestTestJob::test_redirect_headers();
1562 }
1563
1564 static std::string error_data() {
1565 return std::string("ohhh nooooo mr. bill!");
1566 }
1567
1568 static std::string error_headers() {
1569 return URLRequestTestJob::test_error_headers();
1570 }
1571
1572 MockURLRequestInterceptor()
1573 : intercept_main_request_(false), restart_main_request_(false),
1574 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1575 simulate_main_network_error_(false),
1576 intercept_redirect_(false), cancel_redirect_request_(false),
1577 intercept_final_response_(false), cancel_final_request_(false),
1578 use_url_request_http_job_(false),
1579 did_intercept_main_(false), did_restart_main_(false),
1580 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1581 did_simulate_error_main_(false),
1582 did_intercept_redirect_(false), did_cancel_redirect_(false),
1583 did_intercept_final_(false), did_cancel_final_(false) {
1584 }
1585
Chris Watkins7a41d3552017-12-01 02:13:271586 ~MockURLRequestInterceptor() override = default;
bengr1bf8e942014-11-07 01:36:501587
1588 // URLRequestInterceptor implementation:
1589 URLRequestJob* MaybeInterceptRequest(
1590 URLRequest* request,
1591 NetworkDelegate* network_delegate) const override {
1592 if (restart_main_request_) {
1593 restart_main_request_ = false;
1594 did_restart_main_ = true;
1595 return new RestartTestJob(request, network_delegate);
1596 }
1597 if (cancel_main_request_) {
1598 cancel_main_request_ = false;
1599 did_cancel_main_ = true;
1600 return new CancelTestJob(request, network_delegate);
1601 }
1602 if (cancel_then_restart_main_request_) {
1603 cancel_then_restart_main_request_ = false;
1604 did_cancel_then_restart_main_ = true;
1605 return new CancelThenRestartTestJob(request, network_delegate);
1606 }
1607 if (simulate_main_network_error_) {
1608 simulate_main_network_error_ = false;
1609 did_simulate_error_main_ = true;
1610 if (use_url_request_http_job_) {
1611 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1612 }
1613 // This job will result in error since the requested URL is not one of the
1614 // URLs supported by these tests.
1615 return new URLRequestTestJob(request, network_delegate, true);
1616 }
1617 if (!intercept_main_request_)
1618 return nullptr;
1619 intercept_main_request_ = false;
1620 did_intercept_main_ = true;
1621 URLRequestTestJob* job = new URLRequestTestJob(request,
1622 network_delegate,
1623 main_headers_,
1624 main_data_,
1625 true);
1626 job->set_load_timing_info(main_request_load_timing_info_);
1627 return job;
1628 }
1629
1630 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1631 NetworkDelegate* network_delegate,
1632 const GURL& location) const override {
1633 if (cancel_redirect_request_) {
1634 cancel_redirect_request_ = false;
1635 did_cancel_redirect_ = true;
1636 return new CancelTestJob(request, network_delegate);
1637 }
1638 if (!intercept_redirect_)
1639 return nullptr;
1640 intercept_redirect_ = false;
1641 did_intercept_redirect_ = true;
1642 if (use_url_request_http_job_) {
1643 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1644 }
1645 return new URLRequestTestJob(request,
1646 network_delegate,
1647 redirect_headers_,
1648 redirect_data_,
1649 true);
1650 }
1651
1652 URLRequestJob* MaybeInterceptResponse(
1653 URLRequest* request,
1654 NetworkDelegate* network_delegate) const override {
1655 if (cancel_final_request_) {
1656 cancel_final_request_ = false;
1657 did_cancel_final_ = true;
1658 return new CancelTestJob(request, network_delegate);
1659 }
1660 if (!intercept_final_response_)
1661 return nullptr;
1662 intercept_final_response_ = false;
1663 did_intercept_final_ = true;
1664 if (use_url_request_http_job_) {
1665 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1666 }
1667 return new URLRequestTestJob(request,
1668 network_delegate,
1669 final_headers_,
1670 final_data_,
1671 true);
1672 }
1673
1674 void set_intercept_main_request(bool intercept_main_request) {
1675 intercept_main_request_ = intercept_main_request;
1676 }
1677
1678 void set_main_headers(const std::string& main_headers) {
1679 main_headers_ = main_headers;
1680 }
1681
1682 void set_main_data(const std::string& main_data) {
1683 main_data_ = main_data;
1684 }
1685
1686 void set_main_request_load_timing_info(
1687 const LoadTimingInfo& main_request_load_timing_info) {
1688 main_request_load_timing_info_ = main_request_load_timing_info;
1689 }
1690
1691 void set_restart_main_request(bool restart_main_request) {
1692 restart_main_request_ = restart_main_request;
1693 }
1694
1695 void set_cancel_main_request(bool cancel_main_request) {
1696 cancel_main_request_ = cancel_main_request;
1697 }
1698
1699 void set_cancel_then_restart_main_request(
1700 bool cancel_then_restart_main_request) {
1701 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1702 }
1703
1704 void set_simulate_main_network_error(bool simulate_main_network_error) {
1705 simulate_main_network_error_ = simulate_main_network_error;
1706 }
1707
1708 void set_intercept_redirect(bool intercept_redirect) {
1709 intercept_redirect_ = intercept_redirect;
1710 }
1711
1712 void set_redirect_headers(const std::string& redirect_headers) {
1713 redirect_headers_ = redirect_headers;
1714 }
1715
1716 void set_redirect_data(const std::string& redirect_data) {
1717 redirect_data_ = redirect_data;
1718 }
1719
1720 void set_cancel_redirect_request(bool cancel_redirect_request) {
1721 cancel_redirect_request_ = cancel_redirect_request;
1722 }
1723
1724 void set_intercept_final_response(bool intercept_final_response) {
1725 intercept_final_response_ = intercept_final_response;
1726 }
1727
1728 void set_final_headers(const std::string& final_headers) {
1729 final_headers_ = final_headers;
1730 }
1731
1732 void set_final_data(const std::string& final_data) {
1733 final_data_ = final_data;
1734 }
1735
1736 void set_cancel_final_request(bool cancel_final_request) {
1737 cancel_final_request_ = cancel_final_request;
1738 }
1739
1740 void set_use_url_request_http_job(bool use_url_request_http_job) {
1741 use_url_request_http_job_ = use_url_request_http_job;
1742 }
1743
1744 bool did_intercept_main() const {
1745 return did_intercept_main_;
1746 }
1747
1748 bool did_restart_main() const {
1749 return did_restart_main_;
1750 }
1751
1752 bool did_cancel_main() const {
1753 return did_cancel_main_;
1754 }
1755
1756 bool did_cancel_then_restart_main() const {
1757 return did_cancel_then_restart_main_;
1758 }
1759
1760 bool did_simulate_error_main() const {
1761 return did_simulate_error_main_;
1762 }
1763
1764 bool did_intercept_redirect() const {
1765 return did_intercept_redirect_;
1766 }
1767
1768 bool did_cancel_redirect() const {
1769 return did_cancel_redirect_;
1770 }
1771
1772 bool did_intercept_final() const {
1773 return did_intercept_final_;
1774 }
1775
1776 bool did_cancel_final() const {
1777 return did_cancel_final_;
1778 }
1779
1780 private:
1781 // Indicate whether to intercept the main request, and if so specify the
1782 // response to return and the LoadTimingInfo to use.
1783 mutable bool intercept_main_request_;
1784 mutable std::string main_headers_;
1785 mutable std::string main_data_;
1786 mutable LoadTimingInfo main_request_load_timing_info_;
1787
1788 // These indicate actions that can be taken within MaybeInterceptRequest.
1789 mutable bool restart_main_request_;
1790 mutable bool cancel_main_request_;
1791 mutable bool cancel_then_restart_main_request_;
1792 mutable bool simulate_main_network_error_;
1793
1794 // Indicate whether to intercept redirects, and if so specify the response to
1795 // return.
1796 mutable bool intercept_redirect_;
1797 mutable std::string redirect_headers_;
1798 mutable std::string redirect_data_;
1799
1800 // Cancel the request within MaybeInterceptRedirect.
1801 mutable bool cancel_redirect_request_;
1802
1803 // Indicate whether to intercept the final response, and if so specify the
1804 // response to return.
1805 mutable bool intercept_final_response_;
1806 mutable std::string final_headers_;
1807 mutable std::string final_data_;
1808
1809 // Cancel the final request within MaybeInterceptResponse.
1810 mutable bool cancel_final_request_;
1811
1812 // Instruct the interceptor to use a real URLRequestHTTPJob.
1813 mutable bool use_url_request_http_job_;
1814
1815 // These indicate if the interceptor did something or not.
1816 mutable bool did_intercept_main_;
1817 mutable bool did_restart_main_;
1818 mutable bool did_cancel_main_;
1819 mutable bool did_cancel_then_restart_main_;
1820 mutable bool did_simulate_error_main_;
1821 mutable bool did_intercept_redirect_;
1822 mutable bool did_cancel_redirect_;
1823 mutable bool did_intercept_final_;
1824 mutable bool did_cancel_final_;
1825};
1826
1827// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1828class URLRequestInterceptorTest : public URLRequestTest {
1829 public:
1830 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1831 }
1832
1833 ~URLRequestInterceptorTest() override {
1834 // URLRequestJobs may post clean-up tasks on destruction.
1835 base::RunLoop().RunUntilIdle();
1836 }
1837
1838 void SetUpFactory() override {
1839 interceptor_ = new MockURLRequestInterceptor();
1840 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361841 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501842 }
1843
1844 MockURLRequestInterceptor* interceptor() const {
1845 return interceptor_;
1846 }
1847
1848 private:
1849 MockURLRequestInterceptor* interceptor_;
1850};
1851
1852TEST_F(URLRequestInterceptorTest, Intercept) {
1853 // Intercept the main request and respond with a simple response.
1854 interceptor()->set_intercept_main_request(true);
1855 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1856 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591857 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361858 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161859 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1860 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501861 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1862 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1863 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091864 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041865 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1866 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501867 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191868 req->Start();
Wez2a31b222018-06-07 22:07:151869 d.RunUntilComplete();
[email protected]2bba3252013-04-08 19:50:591870
bengr1bf8e942014-11-07 01:36:501871 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091872 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501873 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1874 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591875
bengr1bf8e942014-11-07 01:36:501876 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501877 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501878 EXPECT_EQ(200, req->response_headers()->response_code());
1879 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1880 EXPECT_EQ(1, d.response_started_count());
1881 EXPECT_EQ(0, d.received_redirect_count());
1882}
[email protected]2bba3252013-04-08 19:50:591883
bengr1bf8e942014-11-07 01:36:501884TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1885 // Intercept the main request and respond with a redirect.
1886 interceptor()->set_intercept_main_request(true);
1887 interceptor()->set_main_headers(
1888 MockURLRequestInterceptor::redirect_headers());
1889 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1890
1891 // Intercept that redirect and respond with a final OK response.
1892 interceptor()->set_intercept_redirect(true);
1893 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1894 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1895
1896 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361897 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161898 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1899 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501900 req->set_method("GET");
1901 req->Start();
Wez2a31b222018-06-07 22:07:151902 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501903
1904 // Check that the interceptor got called as expected.
1905 EXPECT_TRUE(interceptor()->did_intercept_main());
1906 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1907
1908 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501909 int status = d.request_status();
1910 EXPECT_EQ(OK, status);
1911 if (status == OK)
bengr1bf8e942014-11-07 01:36:501912 EXPECT_EQ(200, req->response_headers()->response_code());
1913
1914 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1915 EXPECT_EQ(1, d.response_started_count());
1916 EXPECT_EQ(0, d.received_redirect_count());
1917}
1918
1919TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1920 // Intercept the main request to generate a server error response.
1921 interceptor()->set_intercept_main_request(true);
1922 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1923 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1924
1925 // Intercept that error and respond with an OK response.
1926 interceptor()->set_intercept_final_response(true);
1927 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1928 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1929
1930 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361931 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161932 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1933 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501934 req->set_method("GET");
1935 req->Start();
Wez2a31b222018-06-07 22:07:151936 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501937
1938 // Check that the interceptor got called as expected.
1939 EXPECT_TRUE(interceptor()->did_intercept_main());
1940 EXPECT_TRUE(interceptor()->did_intercept_final());
1941
1942 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501943 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501944 EXPECT_EQ(200, req->response_headers()->response_code());
1945 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1946 EXPECT_EQ(1, d.response_started_count());
1947 EXPECT_EQ(0, d.received_redirect_count());
1948}
1949
1950TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1951 // Intercept the main request to simulate a network error.
1952 interceptor()->set_simulate_main_network_error(true);
1953
1954 // Intercept that error and respond with an OK response.
1955 interceptor()->set_intercept_final_response(true);
1956 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1957 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1958
1959 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361960 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161961 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1962 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501963 req->set_method("GET");
1964 req->Start();
Wez2a31b222018-06-07 22:07:151965 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501966
1967 // Check that the interceptor got called as expected.
1968 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1969 EXPECT_TRUE(interceptor()->did_intercept_final());
1970
1971 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501972 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501973 EXPECT_EQ(200, req->response_headers()->response_code());
1974 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1975 EXPECT_EQ(1, d.response_started_count());
1976 EXPECT_EQ(0, d.received_redirect_count());
1977}
1978
1979TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1980 // Restart the main request.
1981 interceptor()->set_restart_main_request(true);
1982
1983 // then intercept the new main request and respond with an OK response
1984 interceptor()->set_intercept_main_request(true);
1985 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1986 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1987
1988 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361989 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161990 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1991 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501992 req->set_method("GET");
1993 req->Start();
Wez2a31b222018-06-07 22:07:151994 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501995
1996 // Check that the interceptor got called as expected.
1997 EXPECT_TRUE(interceptor()->did_restart_main());
1998 EXPECT_TRUE(interceptor()->did_intercept_main());
1999
2000 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:502001 int status = d.request_status();
2002 EXPECT_EQ(OK, status);
2003 if (status == OK)
bengr1bf8e942014-11-07 01:36:502004 EXPECT_EQ(200, req->response_headers()->response_code());
2005
2006 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2007 EXPECT_EQ(1, d.response_started_count());
2008 EXPECT_EQ(0, d.received_redirect_count());
2009}
2010
2011TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
2012 // Intercept the main request and cancel from within the restarted job.
2013 interceptor()->set_cancel_main_request(true);
2014
2015 // Set up to intercept the final response and override it with an OK response.
2016 interceptor()->set_intercept_final_response(true);
2017 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2018 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2019
2020 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362021 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162022 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2023 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502024 req->set_method("GET");
2025 req->Start();
Wez2a31b222018-06-07 22:07:152026 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502027
2028 // Check that the interceptor got called as expected.
2029 EXPECT_TRUE(interceptor()->did_cancel_main());
2030 EXPECT_FALSE(interceptor()->did_intercept_final());
2031
2032 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502033 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502034}
2035
2036TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2037 // Intercept the main request and respond with a redirect.
2038 interceptor()->set_intercept_main_request(true);
2039 interceptor()->set_main_headers(
2040 MockURLRequestInterceptor::redirect_headers());
2041 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2042
2043 // Intercept the redirect and cancel from within that job.
2044 interceptor()->set_cancel_redirect_request(true);
2045
2046 // Set up to intercept the final response and override it with an OK response.
2047 interceptor()->set_intercept_final_response(true);
2048 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2049 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2050
2051 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362052 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162053 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2054 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502055 req->set_method("GET");
2056 req->Start();
Wez2a31b222018-06-07 22:07:152057 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502058
2059 // Check that the interceptor got called as expected.
2060 EXPECT_TRUE(interceptor()->did_intercept_main());
2061 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2062 EXPECT_FALSE(interceptor()->did_intercept_final());
2063
2064 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502065 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502066}
2067
2068TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2069 // Intercept the main request to simulate a network error.
2070 interceptor()->set_simulate_main_network_error(true);
2071
2072 // Set up to intercept final the response and cancel from within that job.
2073 interceptor()->set_cancel_final_request(true);
2074
2075 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362076 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162077 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2078 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502079 req->set_method("GET");
2080 req->Start();
Wez2a31b222018-06-07 22:07:152081 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502082
2083 // Check that the interceptor got called as expected.
2084 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2085 EXPECT_TRUE(interceptor()->did_cancel_final());
2086
2087 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502088 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502089}
2090
2091TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2092 // Intercept the main request and cancel then restart from within that job.
2093 interceptor()->set_cancel_then_restart_main_request(true);
2094
2095 // Set up to intercept the final response and override it with an OK response.
2096 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502097 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2098 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502099
2100 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362101 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162102 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2103 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502104 req->set_method("GET");
2105 req->Start();
Wez2a31b222018-06-07 22:07:152106 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502107
2108 // Check that the interceptor got called as expected.
2109 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2110 EXPECT_FALSE(interceptor()->did_intercept_final());
2111
2112 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502113 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592114}
2115
2116// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2117// reused. |connect_time_flags| is used to indicate if there should be dns
2118// or SSL times, and |used_proxy| is used for proxy times.
2119LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2120 int connect_time_flags,
2121 bool used_proxy) {
2122 LoadTimingInfo load_timing;
2123 load_timing.socket_log_id = 1;
2124
2125 if (used_proxy) {
2126 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2127 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2128 }
2129
2130 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2131 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2132 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2133 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2134 }
2135 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2136 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2137 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2138 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2139 }
2140 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2141
2142 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2143 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382144 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2145 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592146 return load_timing;
2147}
2148
2149// Same as above, but in the case of a reused socket.
2150LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2151 bool used_proxy) {
2152 LoadTimingInfo load_timing;
2153 load_timing.socket_log_id = 1;
2154 load_timing.socket_reused = true;
2155
2156 if (used_proxy) {
2157 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2158 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2159 }
2160
2161 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2162 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382163 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2164 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592165 return load_timing;
2166}
2167
bengr1bf8e942014-11-07 01:36:502168LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2169 const LoadTimingInfo& job_load_timing,
2170 const URLRequestContext& context,
2171 MockURLRequestInterceptor* interceptor) {
2172 interceptor->set_intercept_main_request(true);
2173 interceptor->set_main_request_load_timing_info(job_load_timing);
2174 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162175 std::unique_ptr<URLRequest> req(
2176 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2177 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502178 req->Start();
Wez2a31b222018-06-07 22:07:152179 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502180
2181 LoadTimingInfo resulting_load_timing;
2182 req->GetLoadTimingInfo(&resulting_load_timing);
2183
2184 // None of these should be modified by the URLRequest.
2185 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2186 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2187 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2188 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382189 EXPECT_EQ(job_load_timing.receive_headers_start,
2190 resulting_load_timing.receive_headers_start);
bengr1bf8e942014-11-07 01:36:502191 EXPECT_EQ(job_load_timing.receive_headers_end,
2192 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572193 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2194 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502195
2196 return resulting_load_timing;
2197}
2198
[email protected]2bba3252013-04-08 19:50:592199// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502200TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592201 base::TimeTicks now = base::TimeTicks::Now();
2202 LoadTimingInfo job_load_timing =
2203 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2204
[email protected]2ca01e52013-10-31 22:05:192205 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502206 RunURLRequestInterceptorLoadTimingTest(
2207 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592208
2209 // Nothing should have been changed by the URLRequest.
2210 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2211 load_timing_result.proxy_resolve_start);
2212 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2213 load_timing_result.proxy_resolve_end);
2214 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2215 load_timing_result.connect_timing.dns_start);
2216 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2217 load_timing_result.connect_timing.dns_end);
2218 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2219 load_timing_result.connect_timing.connect_start);
2220 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2221 load_timing_result.connect_timing.connect_end);
2222 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2223 load_timing_result.connect_timing.ssl_start);
2224 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2225 load_timing_result.connect_timing.ssl_end);
2226
2227 // Redundant sanity check.
2228 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2229}
2230
2231// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502232TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592233 base::TimeTicks now = base::TimeTicks::Now();
2234 LoadTimingInfo job_load_timing =
2235 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2236
[email protected]2ca01e52013-10-31 22:05:192237 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502238 RunURLRequestInterceptorLoadTimingTest(
2239 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592240
2241 // Nothing should have been changed by the URLRequest.
2242 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2243 load_timing_result.proxy_resolve_start);
2244 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2245 load_timing_result.proxy_resolve_end);
2246 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2247 load_timing_result.connect_timing.dns_start);
2248 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2249 load_timing_result.connect_timing.dns_end);
2250 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2251 load_timing_result.connect_timing.connect_start);
2252 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2253 load_timing_result.connect_timing.connect_end);
2254 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2255 load_timing_result.connect_timing.ssl_start);
2256 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2257 load_timing_result.connect_timing.ssl_end);
2258
2259 // Redundant sanity check.
2260 TestLoadTimingNotReusedWithProxy(load_timing_result,
2261 CONNECT_TIMING_HAS_SSL_TIMES);
2262}
2263
2264// Make sure that URLRequest correctly adjusts proxy times when they're before
2265// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102266// the case of reusing a SPDY session. The connected socket is not considered
2267// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592268//
2269// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502270TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592271 base::TimeTicks now = base::TimeTicks::Now();
2272 LoadTimingInfo job_load_timing =
2273 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2274 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2275 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2276 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2277 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2278 job_load_timing.connect_timing.connect_start =
2279 now - base::TimeDelta::FromDays(2);
2280 job_load_timing.connect_timing.connect_end =
2281 now - base::TimeDelta::FromDays(1);
2282
[email protected]2ca01e52013-10-31 22:05:192283 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502284 RunURLRequestInterceptorLoadTimingTest(
2285 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592286
2287 // Proxy times, connect times, and DNS times should all be replaced with
2288 // request_start.
2289 EXPECT_EQ(load_timing_result.request_start,
2290 load_timing_result.proxy_resolve_start);
2291 EXPECT_EQ(load_timing_result.request_start,
2292 load_timing_result.proxy_resolve_end);
2293 EXPECT_EQ(load_timing_result.request_start,
2294 load_timing_result.connect_timing.dns_start);
2295 EXPECT_EQ(load_timing_result.request_start,
2296 load_timing_result.connect_timing.dns_end);
2297 EXPECT_EQ(load_timing_result.request_start,
2298 load_timing_result.connect_timing.connect_start);
2299 EXPECT_EQ(load_timing_result.request_start,
2300 load_timing_result.connect_timing.connect_end);
2301
2302 // Other times should have been left null.
2303 TestLoadTimingNotReusedWithProxy(load_timing_result,
2304 CONNECT_TIMING_HAS_DNS_TIMES);
2305}
2306
2307// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502308TEST_F(URLRequestInterceptorTest,
2309 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592310 base::TimeTicks now = base::TimeTicks::Now();
2311 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2312 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2313 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
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 // Proxy times and connect times should all be replaced with request_start.
2320 EXPECT_EQ(load_timing_result.request_start,
2321 load_timing_result.proxy_resolve_start);
2322 EXPECT_EQ(load_timing_result.request_start,
2323 load_timing_result.proxy_resolve_end);
2324
2325 // Other times should have been left null.
2326 TestLoadTimingReusedWithProxy(load_timing_result);
2327}
2328
2329// Make sure that URLRequest correctly adjusts connect times when they're before
2330// |request_start|, due to reusing a connected socket. The connected socket is
2331// not considered reused in this test (May be a preconnect).
2332//
2333// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502334TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592335 base::TimeTicks now = base::TimeTicks::Now();
2336 LoadTimingInfo job_load_timing =
2337 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2338 job_load_timing.connect_timing.connect_start =
2339 now - base::TimeDelta::FromDays(1);
2340 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2341 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2342 job_load_timing.connect_timing.connect_end =
2343 now - base::TimeDelta::FromDays(4);
2344
[email protected]2ca01e52013-10-31 22:05:192345 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502346 RunURLRequestInterceptorLoadTimingTest(
2347 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592348
2349 // Connect times, and SSL times should be replaced with request_start.
2350 EXPECT_EQ(load_timing_result.request_start,
2351 load_timing_result.connect_timing.connect_start);
2352 EXPECT_EQ(load_timing_result.request_start,
2353 load_timing_result.connect_timing.ssl_start);
2354 EXPECT_EQ(load_timing_result.request_start,
2355 load_timing_result.connect_timing.ssl_end);
2356 EXPECT_EQ(load_timing_result.request_start,
2357 load_timing_result.connect_timing.connect_end);
2358
2359 // Other times should have been left null.
2360 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2361}
2362
2363// Make sure that URLRequest correctly adjusts connect times when they're before
2364// |request_start|, due to reusing a connected socket in the case that there
2365// are also proxy times. The connected socket is not considered reused in this
2366// test (May be a preconnect).
2367//
2368// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502369TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592370 base::TimeTicks now = base::TimeTicks::Now();
2371 LoadTimingInfo job_load_timing =
2372 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2373 job_load_timing.connect_timing.connect_start =
2374 now - base::TimeDelta::FromDays(1);
2375 job_load_timing.connect_timing.connect_end =
2376 now - base::TimeDelta::FromDays(2);
2377
[email protected]2ca01e52013-10-31 22:05:192378 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502379 RunURLRequestInterceptorLoadTimingTest(
2380 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592381
2382 // Connect times should be replaced with proxy_resolve_end.
2383 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2384 load_timing_result.connect_timing.connect_start);
2385 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2386 load_timing_result.connect_timing.connect_end);
2387
2388 // Other times should have been left null.
2389 TestLoadTimingNotReusedWithProxy(load_timing_result,
2390 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2391}
2392
[email protected]316c1e5e2012-09-12 15:17:442393// Check that two different URL requests have different identifiers.
2394TEST_F(URLRequestTest, Identifiers) {
2395 TestDelegate d;
2396 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362397 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162398 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2399 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362400 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162401 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2402 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442403
mmenke19378d22014-09-09 04:12:592404 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442405}
2406
blundellb8163592f2015-12-16 14:22:422407#if defined(OS_IOS)
2408// TODO(droger): Check that a failure to connect to the proxy is reported to
2409// the network delegate. crbug.com/496743
2410#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2411#else
2412#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2413#endif
2414TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442415 MockHostResolver host_resolver;
2416 host_resolver.rules()->AddSimulatedFailure("*");
2417
[email protected]ceefd7fd2012-11-29 00:36:242418 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442419 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2420
2421 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362422 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162423 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2424 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192425 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442426
[email protected]f7022f32014-08-21 16:32:192427 req->Start();
Wez2a31b222018-06-07 22:07:152428 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442429
2430 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152431 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472432 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502433 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442434
2435 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012436 EXPECT_THAT(network_delegate.last_error(),
2437 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442438 EXPECT_EQ(1, network_delegate.completed_requests());
2439}
2440
[email protected]cba24642014-08-15 20:49:592441// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442442// content is empty.
2443TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2444 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072445 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162446 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192447 req->Start();
Wez2a31b222018-06-07 22:07:152448 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442449 EXPECT_EQ("", d.data_received());
2450 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2451}
2452
[email protected]5033ab82013-03-22 20:17:462453// Make sure that SetPriority actually sets the URLRequest's priority
2454// correctly, both before and after start.
2455TEST_F(URLRequestTest, SetPriorityBasic) {
2456 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072457 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162458 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2459 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192460 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462461
[email protected]f7022f32014-08-21 16:32:192462 req->SetPriority(LOW);
2463 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462464
[email protected]f7022f32014-08-21 16:32:192465 req->Start();
2466 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462467
[email protected]f7022f32014-08-21 16:32:192468 req->SetPriority(MEDIUM);
2469 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462470}
2471
2472// Make sure that URLRequest calls SetPriority on a job before calling
2473// Start on it.
2474TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2475 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072476 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162477 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2478 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192479 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462480
mmenkeed0498b2015-12-08 23:20:422481 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362482 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422483 req.get(), &default_network_delegate_, &job_priority));
2484 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2485 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462486
[email protected]f7022f32014-08-21 16:32:192487 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462488
[email protected]f7022f32014-08-21 16:32:192489 req->Start();
mmenkeed0498b2015-12-08 23:20:422490 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462491}
2492
2493// Make sure that URLRequest passes on its priority updates to its
2494// job.
2495TEST_F(URLRequestTest, SetJobPriority) {
2496 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072497 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162498 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2499 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462500
mmenkeed0498b2015-12-08 23:20:422501 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362502 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422503 req.get(), &default_network_delegate_, &job_priority));
2504 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462505
[email protected]f7022f32014-08-21 16:32:192506 req->SetPriority(LOW);
2507 req->Start();
mmenkeed0498b2015-12-08 23:20:422508 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462509
[email protected]f7022f32014-08-21 16:32:192510 req->SetPriority(MEDIUM);
2511 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422512 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462513}
2514
[email protected]bb1c4662013-11-14 00:00:072515// Setting the IGNORE_LIMITS load flag should be okay if the priority
2516// is MAXIMUM_PRIORITY.
2517TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2518 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072519 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162520 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2521 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192522 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072523
mmenkeed0498b2015-12-08 23:20:422524 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362525 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422526 req.get(), &default_network_delegate_, &job_priority));
2527 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072528
[email protected]f7022f32014-08-21 16:32:192529 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2530 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072531
[email protected]f7022f32014-08-21 16:32:192532 req->SetPriority(MAXIMUM_PRIORITY);
2533 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072534
[email protected]f7022f32014-08-21 16:32:192535 req->Start();
2536 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422537 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072538}
2539
nick5d570de92015-05-04 20:16:162540namespace {
2541
2542// Less verbose way of running a simple testserver for the tests below.
David Benjamin42116f62017-11-20 21:45:392543class HttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442544 public:
David Benjamin42116f62017-11-20 21:45:392545 explicit HttpTestServer(const base::FilePath& document_root) {
tommycli59a63432015-11-06 00:10:552546 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272547 }
tommycli59a63432015-11-06 00:10:552548
David Benjamin42116f62017-11-20 21:45:392549 HttpTestServer() { AddDefaultHandlers(base::FilePath()); }
tommycli59a63432015-11-06 00:10:552550};
tommyclieae5f75f2015-11-05 19:07:272551
nick5d570de92015-05-04 20:16:162552} // namespace
2553
[email protected]f2f31b32013-01-16 23:24:092554TEST_F(URLRequestTest, DelayedCookieCallback) {
David Benjamin42116f62017-11-20 21:45:392555 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442556 ASSERT_TRUE(test_server.Start());
2557
2558 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362559 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502560 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442561
2562 // Set up a cookie.
2563 {
2564 TestNetworkDelegate network_delegate;
2565 context.set_network_delegate(&network_delegate);
2566 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362567 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552568 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162569 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192570 req->Start();
Wez2a31b222018-06-07 22:07:152571 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442572 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2573 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2574 EXPECT_EQ(1, network_delegate.set_cookie_count());
2575 }
2576
2577 // Verify that the cookie is set.
2578 {
2579 TestNetworkDelegate network_delegate;
2580 context.set_network_delegate(&network_delegate);
2581 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362582 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162583 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2584 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192585 req->Start();
Wez2a31b222018-06-07 22:07:152586 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442587
2588 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2589 != std::string::npos);
2590 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2591 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2592 }
2593}
2594
[email protected]f2f31b32013-01-16 23:24:092595TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392596 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442597 ASSERT_TRUE(test_server.Start());
2598
2599 // Set up a cookie.
2600 {
2601 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072602 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442603 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072604 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552605 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162606 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192607 req->Start();
Wez2a31b222018-06-07 22:07:152608 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442609 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2610 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2611 }
2612
2613 // Verify that the cookie is set.
2614 {
2615 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072616 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442617 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072618 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162619 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2620 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192621 req->Start();
Wez2a31b222018-06-07 22:07:152622 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442623
2624 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2625 != std::string::npos);
2626 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2627 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2628 }
2629
2630 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2631 {
2632 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072633 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442634 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072635 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162636 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2637 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192638 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2639 req->Start();
Wez2a31b222018-06-07 22:07:152640 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442641
2642 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2643 == std::string::npos);
2644
2645 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2646 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2647 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2648 }
2649}
2650
2651TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392652 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442653 ASSERT_TRUE(test_server.Start());
2654
2655 // Set up a cookie.
2656 {
2657 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072658 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442659 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072660 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552661 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162662 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192663 req->Start();
Wez2a31b222018-06-07 22:07:152664 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442665
2666 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2667 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2668 EXPECT_EQ(1, network_delegate.set_cookie_count());
2669 }
2670
2671 // Try to set-up another cookie and update the previous cookie.
2672 {
2673 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072674 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442675 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072676 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552677 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162678 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192679 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2680 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442681
Wez2a31b222018-06-07 22:07:152682 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442683
2684 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2685 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2686 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2687 EXPECT_EQ(0, network_delegate.set_cookie_count());
2688 }
2689
2690 // Verify the cookies weren't saved or updated.
2691 {
2692 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072693 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442694 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072695 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162696 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2697 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192698 req->Start();
Wez2a31b222018-06-07 22:07:152699 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442700
2701 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2702 == std::string::npos);
2703 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2704 != std::string::npos);
2705
2706 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2707 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2708 EXPECT_EQ(0, network_delegate.set_cookie_count());
2709 }
2710}
2711
2712TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392713 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442714 ASSERT_TRUE(test_server.Start());
2715
2716 // Set up a cookie.
2717 {
2718 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072719 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442720 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072721 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552722 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162723 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192724 req->Start();
Wez2a31b222018-06-07 22:07:152725 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442726
2727 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2728 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2729 }
2730
2731 // Verify that the cookie is set.
2732 {
2733 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072734 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442735 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072736 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162737 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2738 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192739 req->Start();
Wez2a31b222018-06-07 22:07:152740 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442741
2742 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2743 != std::string::npos);
2744
2745 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2746 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182747 TestNetLogEntry::List entries;
2748 net_log_.GetEntries(&entries);
2749 for (const auto& entry : entries) {
2750 EXPECT_NE(entry.type,
2751 NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE);
2752 }
[email protected]316c1e5e2012-09-12 15:17:442753 }
2754
2755 // Verify that the cookie isn't sent.
2756 {
2757 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072758 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442759 TestDelegate d;
2760 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:072761 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162762 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2763 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192764 req->Start();
Wez2a31b222018-06-07 22:07:152765 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442766
2767 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2768 == std::string::npos);
2769
[email protected]22e045f2013-09-20 03:54:032770 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442771 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182772 TestNetLogEntry::List entries;
2773 net_log_.GetEntries(&entries);
2774 ExpectLogContainsSomewhereAfter(
2775 entries, 0, NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE,
2776 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442777 }
2778}
2779
marqf14fff8d2015-12-02 15:52:292780// TODO(crbug.com/564656) This test is flaky on iOS.
2781#if defined(OS_IOS)
2782#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2783#else
2784#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2785#endif
[email protected]316c1e5e2012-09-12 15:17:442786TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392787 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442788 ASSERT_TRUE(test_server.Start());
2789
2790 // Set up a cookie.
2791 {
2792 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072793 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442794 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072795 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552796 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162797 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192798 req->Start();
Wez2a31b222018-06-07 22:07:152799 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442800
2801 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2802 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182803 TestNetLogEntry::List entries;
2804 net_log_.GetEntries(&entries);
2805 for (const auto& entry : entries) {
2806 EXPECT_NE(entry.type,
2807 NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE);
2808 }
[email protected]316c1e5e2012-09-12 15:17:442809 }
2810
2811 // Try to set-up another cookie and update the previous cookie.
2812 {
2813 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072814 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442815 TestDelegate d;
2816 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:072817 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552818 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162819 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192820 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442821
Wez2a31b222018-06-07 22:07:152822 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442823
2824 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2825 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182826 TestNetLogEntry::List entries;
2827 net_log_.GetEntries(&entries);
2828 ExpectLogContainsSomewhereAfter(
2829 entries, 0, NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE,
2830 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442831 }
2832
2833 // Verify the cookies weren't saved or updated.
2834 {
2835 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072836 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442837 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072838 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162839 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2840 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192841 req->Start();
Wez2a31b222018-06-07 22:07:152842 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442843
2844 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2845 == std::string::npos);
2846 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2847 != std::string::npos);
2848
2849 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2850 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2851 }
2852}
2853
2854TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:392855 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442856 ASSERT_TRUE(test_server.Start());
2857
2858 // Set up an empty cookie.
2859 {
2860 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072861 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442862 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072863 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162864 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
2865 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192866 req->Start();
Wez2a31b222018-06-07 22:07:152867 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442868
2869 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2870 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2871 EXPECT_EQ(0, network_delegate.set_cookie_count());
2872 }
2873}
2874
2875TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:392876 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442877 ASSERT_TRUE(test_server.Start());
2878
2879 // Set up a cookie.
2880 {
2881 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072882 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442883 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072884 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552885 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162886 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192887 req->Start();
Wez2a31b222018-06-07 22:07:152888 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442889
2890 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2891 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2892 }
2893
2894 // Verify that the cookie is set.
2895 {
2896 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072897 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442898 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072899 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162900 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2901 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192902 req->Start();
Wez2a31b222018-06-07 22:07:152903 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442904
2905 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2906 != std::string::npos);
2907
2908 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2909 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2910 }
2911
2912 // Verify that the cookie isn't sent.
2913 {
2914 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072915 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442916 TestDelegate d;
2917 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:072918 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162919 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2920 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192921 req->Start();
Wez2a31b222018-06-07 22:07:152922 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442923
2924 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2925 == std::string::npos);
2926
[email protected]22e045f2013-09-20 03:54:032927 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442928 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2929 }
2930}
2931
2932TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:392933 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442934 ASSERT_TRUE(test_server.Start());
2935
2936 // Set up a cookie.
2937 {
2938 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072939 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442940 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072941 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552942 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162943 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192944 req->Start();
Wez2a31b222018-06-07 22:07:152945 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442946
2947 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2948 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2949 }
2950
2951 // Try to set-up another cookie and update the previous cookie.
2952 {
2953 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072954 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442955 TestDelegate d;
2956 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:072957 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552958 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162959 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192960 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442961
Wez2a31b222018-06-07 22:07:152962 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442963
2964 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2965 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2966 }
2967
2968 // Verify the cookies weren't saved or updated.
2969 {
2970 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072971 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442972 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072973 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162974 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2975 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192976 req->Start();
Wez2a31b222018-06-07 22:07:152977 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442978
2979 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2980 == std::string::npos);
2981 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2982 != std::string::npos);
2983
2984 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2985 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2986 }
2987}
2988
mkwstc5fa7762016-03-28 09:28:232989TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:392990 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:262991 ASSERT_TRUE(test_server.Start());
2992
mkwst202534e32016-01-15 16:07:152993 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072994 default_context().set_network_delegate(&network_delegate);
mkwst202534e32016-01-15 16:07:152995
mkwstf71d0bd2016-03-21 14:15:242996 const std::string kHost = "example.test";
2997 const std::string kSubHost = "subdomain.example.test";
2998 const std::string kCrossHost = "cross-origin.test";
2999
3000 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:263001 {
mkwst3f3daac2015-02-26 20:15:263002 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073003 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
mkwstf71d0bd2016-03-21 14:15:243004 test_server.GetURL(kHost,
3005 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3006 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:163007 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst3f3daac2015-02-26 20:15:263008 req->Start();
Wez2a31b222018-06-07 22:07:153009 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263010 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3011 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:243012 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:263013 }
3014
mkwstf71d0bd2016-03-21 14:15:243015 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:263016 {
mkwst3f3daac2015-02-26 20:15:263017 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073018 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163019 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3020 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463021 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463022 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263023 req->Start();
Wez2a31b222018-06-07 22:07:153024 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263025
mkwstf71d0bd2016-03-21 14:15:243026 EXPECT_NE(std::string::npos,
3027 d.data_received().find("StrictSameSiteCookie=1"));
3028 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263029 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3030 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3031 }
3032
clamyfd58ca072016-12-21 17:18:323033 // Verify that both cookies are sent when the request has no initiator (can
3034 // happen for main frame browser-initiated navigations).
3035 {
3036 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073037 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163038 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3039 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463040 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:323041 req->Start();
Wez2a31b222018-06-07 22:07:153042 d.RunUntilComplete();
clamyfd58ca072016-12-21 17:18:323043
3044 EXPECT_NE(std::string::npos,
3045 d.data_received().find("StrictSameSiteCookie=1"));
3046 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3047 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3048 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3049 }
3050
mkwstf71d0bd2016-03-21 14:15:243051 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263052 {
mkwst3f3daac2015-02-26 20:15:263053 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073054 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163055 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3056 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463057 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463058 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153059 req->Start();
Wez2a31b222018-06-07 22:07:153060 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153061
mkwstf71d0bd2016-03-21 14:15:243062 EXPECT_NE(std::string::npos,
3063 d.data_received().find("StrictSameSiteCookie=1"));
3064 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153065 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3066 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3067 }
3068
mkwstf71d0bd2016-03-21 14:15:243069 // Verify that neither cookie is not sent for cross-site requests.
3070 {
3071 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073072 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163073 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3074 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463075 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463076 req->set_initiator(
3077 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243078 req->Start();
Wez2a31b222018-06-07 22:07:153079 d.RunUntilComplete();
mkwstf71d0bd2016-03-21 14:15:243080
3081 EXPECT_EQ(std::string::npos,
3082 d.data_received().find("StrictSameSiteCookie=1"));
3083 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3084 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3085 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3086 }
3087
3088 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153089 // method is "safe".
3090 {
3091 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073092 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163093 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3094 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463095 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463096 req->set_initiator(
3097 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243098 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153099 req->Start();
Wez2a31b222018-06-07 22:07:153100 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153101
mkwstf71d0bd2016-03-21 14:15:243102 EXPECT_EQ(std::string::npos,
3103 d.data_received().find("StrictSameSiteCookie=1"));
3104 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153105 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3106 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3107 }
3108
mkwstf71d0bd2016-03-21 14:15:243109 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153110 // method is unsafe (e.g. POST).
3111 {
3112 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073113 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163114 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3115 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463116 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463117 req->set_initiator(
3118 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153119 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263120 req->Start();
Wez2a31b222018-06-07 22:07:153121 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263122
mkwstf71d0bd2016-03-21 14:15:243123 EXPECT_EQ(std::string::npos,
3124 d.data_received().find("StrictSameSiteCookie=1"));
3125 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263126 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3127 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3128 }
3129}
3130
estark557a5eb82015-12-01 22:57:103131// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363132TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553133 EmbeddedTestServer http_server;
3134 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363135 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553136 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3137 https_server.AddDefaultHandlers(
3138 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3139 ASSERT_TRUE(http_server.Start());
3140 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363141
estarkb15166b2015-12-18 16:56:383142 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363143 TestURLRequestContext context(true);
3144 context.set_network_delegate(&network_delegate);
3145 context.Init();
3146
estarkb15166b2015-12-18 16:56:383147 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363148 {
3149 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363150 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103151 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163152 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363153 req->Start();
Wez2a31b222018-06-07 22:07:153154 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363155 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3156 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3157 }
3158
3159 // Verify that the cookie is not set.
3160 {
3161 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363162 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163163 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3164 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363165 req->Start();
Wez2a31b222018-06-07 22:07:153166 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363167
jww79aceda2015-12-07 01:56:343168 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3169 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363170 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3171 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3172 }
3173}
3174
estarkb15166b2015-12-18 16:56:383175TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553176 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3177 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363178 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553179 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363180
3181 TestNetworkDelegate network_delegate;
3182 TestURLRequestContext context(true);
3183 context.set_network_delegate(&network_delegate);
3184 context.Init();
3185
estarkb15166b2015-12-18 16:56:383186 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363187 {
3188 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163189 std::unique_ptr<URLRequest> req(context.CreateRequest(
3190 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3191 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363192 req->Start();
Wez2a31b222018-06-07 22:07:153193 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583194 EXPECT_EQ(0, network_delegate.set_cookie_count());
estarkcd39c11f2015-10-19 19:46:363195 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3196 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3197 }
3198
3199 // Verify that the cookie is not set.
3200 {
3201 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363202 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163203 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3204 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363205 req->Start();
Wez2a31b222018-06-07 22:07:153206 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363207
jww79aceda2015-12-07 01:56:343208 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363209 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3210 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3211 }
3212}
3213
estarkb15166b2015-12-18 16:56:383214TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553215 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3216 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363217 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553218 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363219
estarkb15166b2015-12-18 16:56:383220 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363221 TestURLRequestContext context(true);
3222 context.set_network_delegate(&network_delegate);
3223 context.Init();
3224
estarkb15166b2015-12-18 16:56:383225 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363226 {
3227 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363228 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103229 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163230 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363231 req->Start();
Wez2a31b222018-06-07 22:07:153232 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363233 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3234 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3235 }
3236
3237 // Verify that the cookie is set.
3238 {
3239 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363240 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163241 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3242 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363243 req->Start();
Wez2a31b222018-06-07 22:07:153244 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363245
jww79aceda2015-12-07 01:56:343246 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3247 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3248 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3249 }
3250}
3251
3252// Tests that secure cookies can't be set on non-secure origins if strict secure
3253// cookies are enabled.
3254TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3255 EmbeddedTestServer http_server;
3256 http_server.AddDefaultHandlers(
3257 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3258 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3259 https_server.AddDefaultHandlers(
3260 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3261 ASSERT_TRUE(http_server.Start());
3262 ASSERT_TRUE(https_server.Start());
3263
Matt Menkebe9b6eb2018-10-18 12:11:443264 TestNetworkDelegate network_delegate;
jww79aceda2015-12-07 01:56:343265 TestURLRequestContext context(true);
3266 context.set_network_delegate(&network_delegate);
3267 context.Init();
3268
3269 // Try to set a Secure cookie, with experimental features enabled.
3270 {
3271 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363272 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343273 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163274 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343275 req->Start();
Wez2a31b222018-06-07 22:07:153276 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343277 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3278 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3279 }
3280
3281 // Verify that the cookie is not set.
3282 {
3283 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363284 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163285 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3286 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343287 req->Start();
Wez2a31b222018-06-07 22:07:153288 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343289
3290 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3291 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3292 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3293 }
3294}
3295
Thiemo Nagel0793b9c532018-04-18 16:57:583296// The parameter is true for same-site and false for cross-site requests.
3297class URLRequestTestParameterizedSameSite
3298 : public URLRequestTest,
3299 public ::testing::WithParamInterface<bool> {
3300 protected:
3301 URLRequestTestParameterizedSameSite() {
3302 auto params = std::make_unique<HttpNetworkSession::Params>();
3303 params->ignore_certificate_errors = true;
3304 context_.set_http_network_session_params(std::move(params));
3305 context_.set_network_delegate(&network_delegate_);
3306 https_server_.AddDefaultHandlers(
3307 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3308 EXPECT_TRUE(https_server_.Start());
3309 }
3310
3311 // To be called after configuration of |context_| has been finalized.
3312 void InitContext() { context_.Init(); }
3313
3314 const std::string kHost_ = "example.test";
3315 const std::string kCrossHost_ = "cross-site.test";
3316 TestURLRequestContext context_{true};
3317 TestNetworkDelegate network_delegate_;
3318 base::HistogramTester histograms_;
3319 EmbeddedTestServer https_server_{EmbeddedTestServer::TYPE_HTTPS};
3320};
3321
Victor Costan8fb98f6f2019-02-01 17:08:293322INSTANTIATE_TEST_SUITE_P(URLRequestTest,
3323 URLRequestTestParameterizedSameSite,
3324 ::testing::Bool());
Thiemo Nagel0793b9c532018-04-18 16:57:583325
3326TEST_P(URLRequestTestParameterizedSameSite, CookieAgeMetrics) {
3327 const bool same_site = GetParam();
3328 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3329 InitContext();
3330
Mike West86149882017-07-28 10:41:493331 EmbeddedTestServer http_server;
3332 http_server.AddDefaultHandlers(
3333 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
Thiemo Nagel23e0b322018-04-18 12:46:543334 ASSERT_TRUE(http_server.Start());
3335
Thiemo Nagel0793b9c532018-04-18 16:57:583336 // Set two test cookies.
Thiemo Nagel23e0b322018-04-18 12:46:543337 {
3338 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583339 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3340 http_server.GetURL(kHost_, "/set-cookie?cookie=value&cookie2=value2"),
Thiemo Nagel23e0b322018-04-18 12:46:543341 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3342 req->Start();
Wez2a31b222018-06-07 22:07:153343 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583344 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3345 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3346 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3347 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3348 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 0);
3349 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3350 0);
3351 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3352 0);
3353 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3354 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 0);
Thiemo Nagel23e0b322018-04-18 12:46:543355 }
3356
Thiemo Nagel0793b9c532018-04-18 16:57:583357 // Make a secure request.
Thiemo Nagel23e0b322018-04-18 12:46:543358 {
3359 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583360 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3361 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3362 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3363 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103364 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583365 url::Origin::Create(https_server_.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103366 req->Start();
Wez2a31b222018-06-07 22:07:153367 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583368 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3369 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3370 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3371 !same_site);
3372 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3373 same_site);
3374 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3375 0);
3376 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3377 0);
3378 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3379 same_site ? 0 : 2);
3380 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3381 same_site ? 2 : 0);
3382 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3383 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
Mohsen Izadiad6f7592018-04-18 15:57:103384 }
3385
Thiemo Nagel0793b9c532018-04-18 16:57:583386 // Make a non-secure request.
Mohsen Izadiad6f7592018-04-18 15:57:103387 {
3388 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583389 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3390 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
Mohsen Izadiad6f7592018-04-18 15:57:103391 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel0793b9c532018-04-18 16:57:583392 req->set_site_for_cookies(http_server.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103393 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583394 url::Origin::Create(http_server.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103395 req->Start();
Wez2a31b222018-06-07 22:07:153396 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583397 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest",
3398 !same_site);
3399 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest",
3400 same_site);
3401 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3402 !same_site);
3403 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3404 same_site);
3405 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3406 same_site ? 0 : 2);
3407 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3408 same_site ? 2 : 0);
3409 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3410 same_site ? 0 : 2);
3411 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3412 same_site ? 2 : 0);
3413 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3414 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
3415 }
3416}
3417
3418// Cookies with secure attribute (no HSTS) --> k1pSecureAttribute
3419TEST_P(URLRequestTestParameterizedSameSite,
3420 CookieNetworkSecurityMetricSecureAttribute) {
3421 const bool same_site = GetParam();
3422 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3423 InitContext();
3424
3425 // Set cookies.
3426 {
3427 TestDelegate d;
3428 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3429 https_server_.GetURL(kHost_,
3430 "/set-cookie?session-cookie=value;Secure&"
3431 "longlived-cookie=value;Secure;domain=" +
3432 kHost_ + ";Max-Age=360000"),
3433 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3434 req->Start();
Wez2a31b222018-06-07 22:07:153435 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583436 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3437 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3438 }
3439
3440 // Verify that the cookies fall into the correct metrics bucket.
3441 {
3442 TestDelegate d;
3443 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3444 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3445 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3446 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3447 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3448 req->Start();
Wez2a31b222018-06-07 22:07:153449 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583450 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3451 // Static cast of boolean required for MSVC 1911.
3452 histograms_.ExpectBucketCount(
3453 "Cookie.NetworkSecurity",
3454 static_cast<int>(CookieNetworkSecurity::k1pSecureAttribute) |
3455 static_cast<int>(!same_site),
3456 2);
3457 }
3458}
3459
3460// Short-lived host cookie --> k1pHSTSHostCookie
3461TEST_P(URLRequestTestParameterizedSameSite,
3462 CookieNetworkSecurityMetricShortlivedHostCookie) {
3463 const bool same_site = GetParam();
3464 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3465
3466 TransportSecurityState transport_security_state;
3467 transport_security_state.AddHSTS(
3468 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3469 false /* include_subdomains */);
3470 context_.set_transport_security_state(&transport_security_state);
3471 InitContext();
3472
3473 // Set cookie.
3474 {
3475 TestDelegate d;
3476 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3477 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;Max-Age=3600"),
3478 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3479 req->Start();
Wez2a31b222018-06-07 22:07:153480 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583481 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3482 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3483 }
3484
3485 // Verify that the cookie falls into the correct metrics bucket.
3486 {
3487 TestDelegate d;
3488 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3489 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3490 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3491 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3492 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3493 req->Start();
Wez2a31b222018-06-07 22:07:153494 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583495 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3496 // Static cast of boolean required for MSVC 1911.
3497 histograms_.ExpectBucketCount(
3498 "Cookie.NetworkSecurity",
3499 static_cast<int>(CookieNetworkSecurity::k1pHSTSHostCookie) |
3500 static_cast<int>(!same_site),
3501 1);
3502 }
3503}
3504
3505// Long-lived (either due to expiry or due to being a session cookie) host
3506// cookies --> k1pExpiringHSTSHostCookie
3507TEST_P(URLRequestTestParameterizedSameSite,
3508 CookieNetworkSecurityMetricLonglivedHostCookie) {
3509 const bool same_site = GetParam();
3510 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3511
3512 TransportSecurityState transport_security_state;
3513 transport_security_state.AddHSTS(
3514 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3515 false /* include_subdomains */);
3516 context_.set_transport_security_state(&transport_security_state);
3517 InitContext();
3518
3519 // Set cookies.
3520 {
3521 TestDelegate d;
3522 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3523 https_server_.GetURL(kHost_,
3524 "/set-cookie?session-cookie=value&"
3525 "longlived-cookie=value;Max-Age=360000"),
3526 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3527 req->Start();
Wez2a31b222018-06-07 22:07:153528 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583529 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3530 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3531 }
3532
3533 // Verify that the cookies fall into the correct metrics bucket.
3534 {
3535 TestDelegate d;
3536 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3537 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3538 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3539 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3540 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3541 req->Start();
Wez2a31b222018-06-07 22:07:153542 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583543 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3544 // Static cast of boolean required for MSVC 1911.
3545 histograms_.ExpectBucketCount(
3546 "Cookie.NetworkSecurity",
3547 static_cast<int>(CookieNetworkSecurity::k1pExpiringHSTSHostCookie) |
3548 static_cast<int>(!same_site),
3549 2);
3550 }
3551}
3552
3553// Domain cookie with HSTS subdomains with cookie expiry before HSTS expiry -->
3554// k1pHSTSSubdomainsIncluded
3555TEST_P(URLRequestTestParameterizedSameSite,
3556 CookieNetworkSecurityMetricShortlivedDomainCookie) {
3557 const bool same_site = GetParam();
3558 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3559
3560 TransportSecurityState transport_security_state;
3561 transport_security_state.AddHSTS(
3562 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3563 true /* include_subdomains */);
3564 context_.set_transport_security_state(&transport_security_state);
3565 InitContext();
3566
3567 // Set cookie.
3568 {
3569 TestDelegate d;
3570 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3571 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3572 kHost_ + ";Max-Age=3600"),
3573 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3574 req->Start();
Wez2a31b222018-06-07 22:07:153575 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583576 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3577 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3578 }
3579
3580 // Verify that the cookie falls into the correct metrics bucket.
3581 {
3582 TestDelegate d;
3583 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3584 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3585 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3586 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3587 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3588 req->Start();
Wez2a31b222018-06-07 22:07:153589 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583590 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3591 // Static cast of boolean required for MSVC 1911.
3592 histograms_.ExpectBucketCount(
3593 "Cookie.NetworkSecurity",
3594 static_cast<int>(CookieNetworkSecurity::k1pHSTSSubdomainsIncluded) |
3595 static_cast<int>(!same_site),
3596 1);
3597 }
3598}
3599
3600// Long-lived (either due to expiry or due to being a session cookie) domain
3601// cookies with HSTS subdomains --> k1pExpiringHSTSSubdomainsIncluded
3602TEST_P(URLRequestTestParameterizedSameSite,
3603 CookieNetworkSecurityMetricLonglivedDomainCookie) {
3604 const bool same_site = GetParam();
3605 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3606
3607 TransportSecurityState transport_security_state;
3608 transport_security_state.AddHSTS(
3609 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3610 true /* include_subdomains */);
3611 context_.set_transport_security_state(&transport_security_state);
3612 InitContext();
3613
3614 // Set cookies.
3615 {
3616 TestDelegate d;
3617 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3618 https_server_.GetURL(
3619 kHost_, "/set-cookie?session-cookie=value;domain=" + kHost_ + "&" +
3620 "longlived-cookie=value;domain=" + kHost_ +
3621 ";Max-Age=360000"),
3622 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3623 req->Start();
Wez2a31b222018-06-07 22:07:153624 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583625 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3626 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3627 }
3628
3629 // Verify that the cookies fall into the correct metrics bucket.
3630 {
3631 TestDelegate d;
3632 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3633 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3634 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3635 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3636 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3637 req->Start();
Wez2a31b222018-06-07 22:07:153638 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583639 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3640 // Static cast of boolean required for MSVC 1911.
3641 histograms_.ExpectBucketCount(
3642 "Cookie.NetworkSecurity",
3643 static_cast<int>(
3644 CookieNetworkSecurity::k1pExpiringHSTSSubdomainsIncluded) |
3645 static_cast<int>(!same_site),
3646 2);
3647 }
3648}
3649
3650// Domain cookie with HSTS subdomains not included --> k1pHSTSSpoofable
3651TEST_P(URLRequestTestParameterizedSameSite,
3652 CookieNetworkSecurityMetricSpoofableDomainCookie) {
3653 const bool same_site = GetParam();
3654 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3655
3656 TransportSecurityState transport_security_state;
3657 transport_security_state.AddHSTS(
3658 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3659 false /* include_subdomains */);
3660 context_.set_transport_security_state(&transport_security_state);
3661 InitContext();
3662
3663 // Set cookie.
3664 {
3665 TestDelegate d;
3666 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3667 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3668 kHost_ + ";Max-Age=3600"),
3669 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3670 req->Start();
Wez2a31b222018-06-07 22:07:153671 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583672 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3673 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3674 }
3675
3676 // Verify that the cookie falls into the correct metrics bucket.
3677 {
3678 TestDelegate d;
3679 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3680 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3681 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3682 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3683 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3684 req->Start();
Wez2a31b222018-06-07 22:07:153685 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583686 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3687 // Static cast of boolean required for MSVC 1911.
3688 histograms_.ExpectBucketCount(
3689 "Cookie.NetworkSecurity",
3690 static_cast<int>(CookieNetworkSecurity::k1pHSTSSpoofable) |
3691 static_cast<int>(!same_site),
3692 1);
3693 }
3694}
3695
3696// Cookie without HSTS --> k1p(Non)SecureConnection
3697TEST_P(URLRequestTestParameterizedSameSite, CookieNetworkSecurityMetricNoHSTS) {
3698 const bool same_site = GetParam();
3699 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3700 InitContext();
3701
3702 EmbeddedTestServer http_server;
3703 http_server.AddDefaultHandlers(
3704 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3705 ASSERT_TRUE(http_server.Start());
3706
3707 // Set cookies.
3708 {
3709 TestDelegate d;
3710 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3711 https_server_.GetURL(kHost_,
3712 "/set-cookie?cookie=value;domain=" + kHost_ +
3713 ";Max-Age=3600&host-cookie=value"),
3714 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3715 req->Start();
Wez2a31b222018-06-07 22:07:153716 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583717 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3718 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3719 }
3720
3721 // Verify that the cookie falls into the correct metrics bucket.
3722 {
3723 TestDelegate d;
3724 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3725 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3726 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3727 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3728 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3729 req->Start();
Wez2a31b222018-06-07 22:07:153730 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583731 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3732 // Static cast of boolean required for MSVC 1911.
3733 histograms_.ExpectBucketCount(
3734 "Cookie.NetworkSecurity",
3735 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3736 static_cast<int>(!same_site),
3737 2);
3738 }
3739
3740 // Verify that the cookie falls into the correct metrics bucket.
3741 {
3742 TestDelegate d;
3743 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3744 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3745 TRAFFIC_ANNOTATION_FOR_TESTS));
3746 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3747 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3748 req->Start();
Wez2a31b222018-06-07 22:07:153749 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583750 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 4);
3751 // Static cast of boolean required for MSVC 1911.
3752 histograms_.ExpectBucketCount(
3753 "Cookie.NetworkSecurity",
3754 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3755 static_cast<int>(!same_site),
3756 2);
3757 // Static cast of boolean required for MSVC 1911.
3758 histograms_.ExpectBucketCount(
3759 "Cookie.NetworkSecurity",
3760 static_cast<int>(CookieNetworkSecurity::k1pNonsecureConnection) |
3761 static_cast<int>(!same_site),
3762 2);
Mike West86149882017-07-28 10:41:493763 }
3764}
3765
mmenkefb18c772015-09-30 22:22:503766// Tests that a request is cancelled while entering suspend mode. Uses mocks
3767// rather than a spawned test server because the connection used to talk to
3768// the test server is affected by entering suspend mode on Android.
3769TEST_F(URLRequestTest, CancelOnSuspend) {
3770 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363771 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503772
3773 URLRequestFailedJob::AddUrlHandler();
3774
3775 TestDelegate d;
3776 // Request that just hangs.
3777 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
Ryan Sleevib8449e02018-07-15 04:31:073778 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163779 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mmenkefb18c772015-09-30 22:22:503780 r->Start();
3781
3782 power_monitor_source->Suspend();
3783 // Wait for the suspend notification to cause the request to fail.
Wez2a31b222018-06-07 22:07:153784 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:503785 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503786 EXPECT_TRUE(d.request_failed());
3787 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3788
3789 URLRequestFilter::GetInstance()->ClearHandlers();
3790
3791 // Shouldn't be needed, but just in case.
3792 power_monitor_source->Resume();
3793}
3794
[email protected]5095cd72012-11-01 10:29:163795// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3796// value for the |fixed_date| argument given to the constructor.
3797class FixedDateNetworkDelegate : public TestNetworkDelegate {
3798 public:
3799 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3800 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:273801 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:163802
[email protected]cba24642014-08-15 20:49:593803 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203804 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593805 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:203806 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:593807 const HttpResponseHeaders* original_response_headers,
3808 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133809 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163810
3811 private:
3812 std::string fixed_date_;
3813
3814 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3815};
3816
3817int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593818 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:203819 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:593820 const HttpResponseHeaders* original_response_headers,
3821 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163822 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593823 HttpResponseHeaders* new_response_headers =
3824 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163825
3826 new_response_headers->RemoveHeader("Date");
3827 new_response_headers->AddHeader("Date: " + fixed_date_);
3828
3829 *override_response_headers = new_response_headers;
David Benjamind1f287bf2018-06-12 01:57:203830 return TestNetworkDelegate::OnHeadersReceived(
3831 request, std::move(callback), original_response_headers,
3832 override_response_headers, allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163833}
3834
3835// Test that cookie expiration times are adjusted for server/client clock
3836// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3837// headers by defaulting to GMT. (crbug.com/135131)
3838TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:393839 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:163840 ASSERT_TRUE(test_server.Start());
3841
3842 // Set up an expired cookie.
3843 {
3844 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073845 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:163846 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073847 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193848 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553849 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163850 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193851 req->Start();
Wez2a31b222018-06-07 22:07:153852 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163853 }
3854 // Verify that the cookie is not set.
3855 {
3856 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073857 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:163858 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073859 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163860 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3861 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193862 req->Start();
Wez2a31b222018-06-07 22:07:153863 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163864
3865 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3866 }
3867 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3868 {
3869 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
Ryan Sleevib8449e02018-07-15 04:31:073870 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:163871 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073872 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193873 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553874 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163875 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193876 req->Start();
Wez2a31b222018-06-07 22:07:153877 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163878 }
3879 // Verify that the cookie is set.
3880 {
3881 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073882 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:163883 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073884 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163885 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3886 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193887 req->Start();
Wez2a31b222018-06-07 22:07:153888 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163889
3890 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3891 }
3892}
3893
3894
[email protected]316c1e5e2012-09-12 15:17:443895// Check that it is impossible to change the referrer in the extra headers of
3896// an URLRequest.
3897TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:393898 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443899 ASSERT_TRUE(test_server.Start());
3900
3901 // If extra headers contain referer and the request contains a referer,
3902 // only the latter shall be respected.
3903 {
3904 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073905 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163906 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3907 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193908 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443909
3910 HttpRequestHeaders headers;
3911 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193912 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443913
[email protected]f7022f32014-08-21 16:32:193914 req->Start();
Wez2a31b222018-06-07 22:07:153915 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443916
3917 EXPECT_EQ("http://foo.com/", d.data_received());
3918 }
3919
3920 // If extra headers contain a referer but the request does not, no referer
3921 // shall be sent in the header.
3922 {
3923 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073924 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163925 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3926 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:443927
3928 HttpRequestHeaders headers;
3929 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193930 req->SetExtraRequestHeaders(headers);
3931 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443932
[email protected]f7022f32014-08-21 16:32:193933 req->Start();
Wez2a31b222018-06-07 22:07:153934 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443935
3936 EXPECT_EQ("None", d.data_received());
3937 }
3938}
3939
[email protected]b89290212009-08-14 22:37:353940class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113941 public:
mmenke9f2ec60c2015-06-01 20:59:473942 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113943
[email protected]b89290212009-08-14 22:37:353944 protected:
[email protected]21184962011-10-26 00:50:303945 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3946 // |request_method| is the method to use for the initial request.
3947 // |redirect_method| is the method that is expected to be used for the second
3948 // request, after redirection.
3949 // If |include_data| is true, data is uploaded with the request. The
3950 // response body is expected to match it exactly, if and only if
3951 // |request_method| == |redirect_method|.
3952 void HTTPRedirectMethodTest(const GURL& redirect_url,
3953 const std::string& request_method,
3954 const std::string& redirect_method,
3955 bool include_data) {
3956 static const char kData[] = "hello world";
3957 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073958 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163959 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193960 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303961 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073962 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303963 HttpRequestHeaders headers;
3964 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:243965 base::NumberToString(base::size(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543966 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193967 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303968 }
[email protected]f7022f32014-08-21 16:32:193969 req->Start();
Wez2a31b222018-06-07 22:07:153970 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:193971 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:503972 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:303973 if (include_data) {
3974 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543975 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3976 HttpRequestHeaders::kContentLength));
3977 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3978 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303979 EXPECT_EQ(kData, d.data_received());
3980 } else {
svaldez5b3a8972015-10-09 23:23:543981 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3982 HttpRequestHeaders::kContentLength));
3983 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3984 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303985 EXPECT_NE(kData, d.data_received());
3986 }
3987 }
3988 if (HasFailure())
3989 LOG(WARNING) << "Request method was: " << request_method;
3990 }
3991
Alex Clarke1e08882b32017-10-06 14:22:403992 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
3993 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:513994 // |request_method| is the method to use for the initial request.
3995 // |redirect_method| is the method that is expected to be used for the second
3996 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:403997 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:513998 // redirection. If empty, expects that there will be no Origin header.
3999 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
4000 const std::string& request_method,
4001 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:404002 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:514003 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074004 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164005 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:514006 req->set_method(request_method);
4007 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
4008 redirect_url.GetOrigin().spec(), false);
4009 req->Start();
4010
Wez2a31b222018-06-07 22:07:154011 d.RunUntilComplete();
jww5fe460ff2015-03-28 00:22:514012
4013 EXPECT_EQ(redirect_method, req->method());
4014 // Note that there is no check for request success here because, for
4015 // purposes of testing, the request very well may fail. For example, if the
4016 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
4017 // origin, there is not an HTTPS server in this unit test framework, so the
4018 // request would fail. However, that's fine, as long as the request headers
4019 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:404020 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:514021 EXPECT_FALSE(
4022 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
4023 } else {
4024 std::string origin_header;
4025 EXPECT_TRUE(req->extra_request_headers().GetHeader(
4026 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:404027 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:514028 }
4029 }
4030
[email protected]762d2db2010-01-11 19:03:014031 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:014032 const int kMsgSize = 20000; // multiple of 10
4033 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:484034 char* uploadBytes = new char[kMsgSize+1];
4035 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:014036 char marker = 'a';
4037 for (int idx = 0; idx < kMsgSize/10; idx++) {
4038 memcpy(ptr, "----------", 10);
4039 ptr += 10;
4040 if (idx % 100 == 0) {
4041 ptr--;
4042 *ptr++ = marker;
4043 if (++marker > 'z')
4044 marker = 'a';
4045 }
4046 }
4047 uploadBytes[kMsgSize] = '\0';
4048
[email protected]762d2db2010-01-11 19:03:014049 for (int i = 0; i < kIterations; ++i) {
4050 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074051 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164052 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
4053 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194054 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:014055
mmenkecbc2b712014-10-09 20:29:074056 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:014057
[email protected]f7022f32014-08-21 16:32:194058 r->Start();
4059 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:014060
Wez2a31b222018-06-07 22:07:154061 d.RunUntilComplete();
[email protected]762d2db2010-01-11 19:03:014062
maksim.sisovb53724b52016-09-16 05:30:504063 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
4064 << d.request_status();
[email protected]762d2db2010-01-11 19:03:014065
4066 EXPECT_FALSE(d.received_data_before_response());
4067 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:014068 }
4069 delete[] uploadBytes;
4070 }
4071
[email protected]ede03212012-09-07 12:52:264072 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:344073 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074074 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:554075 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:364076 base::IntToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:164077 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:344078
[email protected]f7022f32014-08-21 16:32:194079 r->Start();
4080 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:344081
Wez2a31b222018-06-07 22:07:154082 d.RunUntilComplete();
[email protected]263163f2012-06-14 22:40:344083
maksim.sisovb53724b52016-09-16 05:30:504084 if (d.request_status() != OK) {
4085 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
4086 return false;
4087 }
[email protected]263163f2012-06-14 22:40:344088
maksim.sisovb53724b52016-09-16 05:30:504089 return true;
[email protected]263163f2012-06-14 22:40:344090 }
4091
David Benjamin42116f62017-11-20 21:45:394092 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:504093
tommycli59a63432015-11-06 00:10:554094 private:
David Benjamin42116f62017-11-20 21:45:394095 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:354096};
4097
tommycli59a63432015-11-06 00:10:554098namespace {
4099
danakj8522a25b2016-04-16 00:17:364100std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:554101 const test_server::HttpRequest& request) {
4102 if (request.headers.find("Host") == request.headers.end() ||
4103 request.headers.at("Host") != "www.redirect.com" ||
4104 request.method != test_server::METHOD_CONNECT) {
4105 return nullptr;
4106 }
4107
danakj8522a25b2016-04-16 00:17:364108 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554109 new test_server::BasicHttpResponse);
4110 http_response->set_code(HTTP_FOUND);
4111 http_response->AddCustomHeader("Location",
4112 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:484113 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554114}
4115
nharperb7441ef2016-01-25 23:54:144116class TestSSLConfigService : public SSLConfigService {
4117 public:
Nick Harper2243e8002018-09-28 20:33:264118 TestSSLConfigService()
4119 : min_version_(kDefaultSSLVersionMin),
davidben095ebb52017-04-12 22:23:344120 max_version_(kDefaultSSLVersionMax) {}
Ryan Sleevib8449e02018-07-15 04:31:074121 ~TestSSLConfigService() override = default;
nharperb7441ef2016-01-25 23:54:144122
davidben095ebb52017-04-12 22:23:344123 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:144124 void set_min_version(uint16_t version) { min_version_ = version; }
4125
nharperb7441ef2016-01-25 23:54:144126 // SSLConfigService:
4127 void GetSSLConfig(SSLConfig* config) override {
4128 *config = SSLConfig();
davidben095ebb52017-04-12 22:23:344129 config->version_min = min_version_;
4130 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:144131 }
4132
Nick Harper89bc7212018-07-31 19:07:574133 bool CanShareConnectionWithClientCerts(
4134 const std::string& hostname) const override {
4135 return false;
4136 }
4137
nharperb7441ef2016-01-25 23:54:144138 private:
nharperb7441ef2016-01-25 23:54:144139 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:344140 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:144141};
4142
Nick Harper89bc7212018-07-31 19:07:574143} // namespace
4144
nharperb7441ef2016-01-25 23:54:144145// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114146// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:554147// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:114148// follow.
[email protected]f2f31b32013-01-16 23:24:094149TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:554150 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124151 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:554152 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114153
[email protected]ceefd7fd2012-11-29 00:36:244154 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044155 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554156 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504157
[email protected]d1ec59082009-02-11 02:48:154158 TestDelegate d;
4159 {
danakj8522a25b2016-04-16 00:17:364160 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164161 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4162 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194163 r->Start();
4164 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:154165
Wez2a31b222018-06-07 22:07:154166 d.RunUntilComplete();
[email protected]d1ec59082009-02-11 02:48:154167
[email protected]d8fc4722014-06-13 13:17:154168 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474169 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504170 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084171 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:154172 // We should not have followed the redirect.
4173 EXPECT_EQ(0, d.received_redirect_count());
4174 }
4175}
4176
[email protected]8202d0c2011-02-23 08:31:144177// This is the same as the previous test, but checks that the network delegate
4178// registers the error.
[email protected]c044616e2013-02-20 02:01:264179TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554180 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144181
[email protected]ceefd7fd2012-11-29 00:36:244182 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044183 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554184 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504185
[email protected]8202d0c2011-02-23 08:31:144186 TestDelegate d;
4187 {
danakj8522a25b2016-04-16 00:17:364188 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164189 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4190 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194191 r->Start();
4192 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144193
Wez2a31b222018-06-07 22:07:154194 d.RunUntilComplete();
[email protected]8202d0c2011-02-23 08:31:144195
[email protected]d8fc4722014-06-13 13:17:154196 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474197 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:144198 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504199 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144200 // We should not have followed the redirect.
4201 EXPECT_EQ(0, d.received_redirect_count());
4202
4203 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014204 EXPECT_THAT(network_delegate.last_error(),
4205 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144206 }
4207}
4208
[email protected]dc5a5cf2012-09-26 02:49:304209// Tests that we can block and asynchronously return OK in various stages.
4210TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4211 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4212 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4213 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4214 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4215 };
Avi Drissman4365a4782018-12-28 19:26:244216 static const size_t blocking_stages_length = base::size(blocking_stages);
[email protected]dc5a5cf2012-09-26 02:49:304217
tommycli59a63432015-11-06 00:10:554218 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304219
4220 TestDelegate d;
4221 BlockingNetworkDelegate network_delegate(
4222 BlockingNetworkDelegate::USER_CALLBACK);
4223 network_delegate.set_block_on(
4224 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4225 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4226 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4227
4228 TestURLRequestContext context(true);
4229 context.set_network_delegate(&network_delegate);
4230 context.Init();
4231
4232 {
danakj8522a25b2016-04-16 00:17:364233 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164234 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4235 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304236
[email protected]f7022f32014-08-21 16:32:194237 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304238 for (size_t i = 0; i < blocking_stages_length; ++i) {
Wez2a31b222018-06-07 22:07:154239 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304240 EXPECT_EQ(blocking_stages[i],
4241 network_delegate.stage_blocked_for_callback());
4242 network_delegate.DoCallback(OK);
4243 }
Wez2a31b222018-06-07 22:07:154244 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194245 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504246 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304247 EXPECT_EQ(1, network_delegate.created_requests());
4248 EXPECT_EQ(0, network_delegate.destroyed_requests());
4249 }
4250 EXPECT_EQ(1, network_delegate.destroyed_requests());
4251}
4252
[email protected]4c76d7c2011-04-15 19:14:124253// Tests that the network delegate can block and cancel a request.
4254TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554255 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124256
4257 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304258 BlockingNetworkDelegate network_delegate(
4259 BlockingNetworkDelegate::AUTO_CALLBACK);
4260 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4261 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124262
[email protected]d5a4dd62012-05-23 01:41:044263 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554264 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504265
[email protected]4c76d7c2011-04-15 19:14:124266 {
rhalavatib7bd7c792017-04-27 05:25:164267 std::unique_ptr<URLRequest> r(
4268 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4269 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124270
[email protected]f7022f32014-08-21 16:32:194271 r->Start();
Wez2a31b222018-06-07 22:07:154272 d.RunUntilComplete();
[email protected]4c76d7c2011-04-15 19:14:124273
[email protected]d8fc4722014-06-13 13:17:154274 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474275 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504276 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124277 EXPECT_EQ(1, network_delegate.created_requests());
4278 EXPECT_EQ(0, network_delegate.destroyed_requests());
4279 }
4280 EXPECT_EQ(1, network_delegate.destroyed_requests());
4281}
4282
[email protected]b4438d32012-09-27 06:15:304283// Helper function for NetworkDelegateCancelRequestAsynchronously and
4284// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4285// delegate operating in |block_mode| and a request for |url|. It blocks the
4286// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4287void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4288 BlockingNetworkDelegate::Stage stage,
4289 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364290 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304291 BlockingNetworkDelegate network_delegate(block_mode);
4292 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4293 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364294
[email protected]b4438d32012-09-27 06:15:304295 TestURLRequestContext context(true);
4296 context.set_network_delegate(&network_delegate);
4297 context.Init();
[email protected]3cd384c602011-08-31 16:12:364298
4299 {
rhalavatib7bd7c792017-04-27 05:25:164300 std::unique_ptr<URLRequest> r(context.CreateRequest(
4301 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364302
[email protected]f7022f32014-08-21 16:32:194303 r->Start();
Wez2a31b222018-06-07 22:07:154304 d.RunUntilComplete();
[email protected]3cd384c602011-08-31 16:12:364305
[email protected]d8fc4722014-06-13 13:17:154306 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474307 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4308 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4309 EXPECT_FALSE(r->proxy_server().is_valid());
4310 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4311 EXPECT_TRUE(r->proxy_server().is_direct());
4312 } else {
4313 NOTREACHED();
4314 }
maksim.sisovb53724b52016-09-16 05:30:504315 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364316 EXPECT_EQ(1, network_delegate.created_requests());
4317 EXPECT_EQ(0, network_delegate.destroyed_requests());
4318 }
4319 EXPECT_EQ(1, network_delegate.destroyed_requests());
4320}
4321
[email protected]b4438d32012-09-27 06:15:304322// The following 3 tests check that the network delegate can cancel a request
4323// synchronously in various stages of the request.
4324TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554325 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304326 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4327 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554328 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304329}
4330
4331TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554332 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304333 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4334 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554335 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304336}
4337
4338TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554339 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304340 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4341 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554342 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304343}
4344
4345// The following 3 tests check that the network delegate can cancel a request
4346// asynchronously in various stages of the request.
4347TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554348 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304349 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4350 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554351 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304352}
4353
4354TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554355 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304356 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4357 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554358 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304359}
4360
4361TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554362 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304363 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4364 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554365 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304366}
4367
[email protected]4c76d7c2011-04-15 19:14:124368// Tests that the network delegate can block and redirect a request to a new
4369// URL.
4370TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554371 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124372
4373 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304374 BlockingNetworkDelegate network_delegate(
4375 BlockingNetworkDelegate::AUTO_CALLBACK);
4376 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
Eric Romanda790f92018-11-07 19:17:154377 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]4c76d7c2011-04-15 19:14:124378 network_delegate.set_redirect_url(redirect_url);
4379
[email protected]d5a4dd62012-05-23 01:41:044380 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554381 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504382
[email protected]4c76d7c2011-04-15 19:14:124383 {
Eric Romanda790f92018-11-07 19:17:154384 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164385 std::unique_ptr<URLRequest> r(context.CreateRequest(
4386 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124387
[email protected]6be6fa92014-08-06 23:44:564388 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194389 r->Start();
Wez0e717112018-06-18 23:09:224390 d.RunUntilRedirect();
[email protected]4c76d7c2011-04-15 19:14:124391
[email protected]6be6fa92014-08-06 23:44:564392 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194393 EXPECT_EQ(307, r->GetResponseCode());
4394 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564395 std::string location;
[email protected]f7022f32014-08-21 16:32:194396 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4397 &location));
[email protected]6be6fa92014-08-06 23:44:564398 EXPECT_EQ(redirect_url, GURL(location));
4399
4400 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354401 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4402 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154403 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:504404 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474405 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4406 http_test_server()->host_port_pair()),
4407 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094408 // before_send_headers_with_proxy_count only increments for headers sent
4409 // through an untunneled proxy.
4410 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554411 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4412 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274413
maksim.sisovb53724b52016-09-16 05:30:504414 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194415 EXPECT_EQ(redirect_url, r->url());
4416 EXPECT_EQ(original_url, r->original_url());
4417 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124418 EXPECT_EQ(1, network_delegate.created_requests());
4419 EXPECT_EQ(0, network_delegate.destroyed_requests());
4420 }
4421 EXPECT_EQ(1, network_delegate.destroyed_requests());
4422}
4423
[email protected]b813ed72012-04-05 08:21:364424// Tests that the network delegate can block and redirect a request to a new
4425// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4426TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554427 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364428
4429 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304430 BlockingNetworkDelegate network_delegate(
4431 BlockingNetworkDelegate::SYNCHRONOUS);
Eric Romanda790f92018-11-07 19:17:154432 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]b813ed72012-04-05 08:21:364433 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364434
[email protected]d5a4dd62012-05-23 01:41:044435 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554436 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364437
4438 {
Eric Romanda790f92018-11-07 19:17:154439 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164440 std::unique_ptr<URLRequest> r(context.CreateRequest(
4441 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364442
[email protected]6be6fa92014-08-06 23:44:564443 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194444 r->Start();
Wez0e717112018-06-18 23:09:224445 d.RunUntilRedirect();
[email protected]b813ed72012-04-05 08:21:364446
[email protected]6be6fa92014-08-06 23:44:564447 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194448 EXPECT_EQ(307, r->GetResponseCode());
4449 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564450 std::string location;
[email protected]f7022f32014-08-21 16:32:194451 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4452 &location));
[email protected]6be6fa92014-08-06 23:44:564453 EXPECT_EQ(redirect_url, GURL(location));
4454
4455 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354456 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4457 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154458 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564459
maksim.sisovb53724b52016-09-16 05:30:504460 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474461 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4462 http_test_server()->host_port_pair()),
4463 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094464 // before_send_headers_with_proxy_count only increments for headers sent
4465 // through an untunneled proxy.
4466 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554467 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4468 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504469 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194470 EXPECT_EQ(redirect_url, r->url());
4471 EXPECT_EQ(original_url, r->original_url());
4472 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364473 EXPECT_EQ(1, network_delegate.created_requests());
4474 EXPECT_EQ(0, network_delegate.destroyed_requests());
4475 }
4476 EXPECT_EQ(1, network_delegate.destroyed_requests());
4477}
4478
[email protected]3c5ca8c2011-09-29 01:14:514479// Tests that redirects caused by the network delegate preserve POST data.
4480TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554481 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514482
4483 const char kData[] = "hello world";
4484
4485 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304486 BlockingNetworkDelegate network_delegate(
4487 BlockingNetworkDelegate::AUTO_CALLBACK);
4488 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554489 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514490 network_delegate.set_redirect_url(redirect_url);
4491
[email protected]ef2bf422012-05-11 03:27:094492 TestURLRequestContext context(true);
4493 context.set_network_delegate(&network_delegate);
4494 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514495
4496 {
tommycli59a63432015-11-06 00:10:554497 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164498 std::unique_ptr<URLRequest> r(context.CreateRequest(
4499 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194500 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074501 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514502 HttpRequestHeaders headers;
4503 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244504 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194505 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564506
4507 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194508 r->Start();
Wez0e717112018-06-18 23:09:224509 d.RunUntilRedirect();
[email protected]3c5ca8c2011-09-29 01:14:514510
[email protected]6be6fa92014-08-06 23:44:564511 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194512 EXPECT_EQ(307, r->GetResponseCode());
4513 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564514 std::string location;
[email protected]f7022f32014-08-21 16:32:194515 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4516 &location));
[email protected]6be6fa92014-08-06 23:44:564517 EXPECT_EQ(redirect_url, GURL(location));
4518
4519 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354520 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4521 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154522 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564523
maksim.sisovb53724b52016-09-16 05:30:504524 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194525 EXPECT_EQ(redirect_url, r->url());
4526 EXPECT_EQ(original_url, r->original_url());
4527 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514528 EXPECT_EQ(1, network_delegate.created_requests());
4529 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194530 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514531 EXPECT_EQ(kData, d.data_received());
4532 }
4533 EXPECT_EQ(1, network_delegate.destroyed_requests());
4534}
4535
[email protected]5f714132014-03-26 10:41:164536// Tests that the network delegate can block and redirect a request to a new
4537// URL during OnHeadersReceived.
4538TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554539 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164540
4541 TestDelegate d;
4542 BlockingNetworkDelegate network_delegate(
4543 BlockingNetworkDelegate::AUTO_CALLBACK);
4544 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
Eric Romanda790f92018-11-07 19:17:154545 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]5f714132014-03-26 10:41:164546 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4547
4548 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554549 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164550
4551 {
Eric Romanda790f92018-11-07 19:17:154552 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164553 std::unique_ptr<URLRequest> r(context.CreateRequest(
4554 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164555
[email protected]f7022f32014-08-21 16:32:194556 r->Start();
Wez2a31b222018-06-07 22:07:154557 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:164558
maksim.sisovb53724b52016-09-16 05:30:504559 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474560 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4561 http_test_server()->host_port_pair()),
4562 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094563 // before_send_headers_with_proxy_count only increments for headers sent
4564 // through an untunneled proxy.
4565 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554566 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4567 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194568
maksim.sisovb53724b52016-09-16 05:30:504569 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194570 EXPECT_EQ(redirect_url, r->url());
4571 EXPECT_EQ(original_url, r->original_url());
4572 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164573 EXPECT_EQ(2, network_delegate.created_requests());
4574 EXPECT_EQ(0, network_delegate.destroyed_requests());
4575 }
4576 EXPECT_EQ(1, network_delegate.destroyed_requests());
4577}
4578
[email protected]c2911d72011-10-03 22:16:364579// Tests that the network delegate can synchronously complete OnAuthRequired
4580// by taking no action. This indicates that the NetworkDelegate does not want to
4581// handle the challenge, and is passing the buck along to the
4582// URLRequest::Delegate.
4583TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554584 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364585
4586 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304587 BlockingNetworkDelegate network_delegate(
4588 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364589
[email protected]ef2bf422012-05-11 03:27:094590 TestURLRequestContext context(true);
4591 context.set_network_delegate(&network_delegate);
4592 context.Init();
[email protected]c2911d72011-10-03 22:16:364593
[email protected]f3cf9802011-10-28 18:44:584594 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364595
4596 {
tommycli59a63432015-11-06 00:10:554597 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164598 std::unique_ptr<URLRequest> r(context.CreateRequest(
4599 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194600 r->Start();
[email protected]79e1fd62013-06-20 06:50:044601
Wez2a31b222018-06-07 22:07:154602 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044603
maksim.sisovb53724b52016-09-16 05:30:504604 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194605 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044606 EXPECT_TRUE(d.auth_required_called());
4607 EXPECT_EQ(1, network_delegate.created_requests());
4608 EXPECT_EQ(0, network_delegate.destroyed_requests());
4609 }
4610 EXPECT_EQ(1, network_delegate.destroyed_requests());
4611}
4612
4613TEST_F(URLRequestTestHTTP,
4614 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554615 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044616
4617 TestDelegate d;
4618 BlockingNetworkDelegate network_delegate(
4619 BlockingNetworkDelegate::SYNCHRONOUS);
4620
4621 TestURLRequestContext context(true);
4622 context.set_network_delegate(&network_delegate);
4623 context.Init();
4624
4625 d.set_credentials(AuthCredentials(kUser, kSecret));
4626
4627 {
tommycli59a63432015-11-06 00:10:554628 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164629 std::unique_ptr<URLRequest> r(context.CreateRequest(
4630 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194631 r->Start();
[email protected]79e1fd62013-06-20 06:50:044632
Wez2a31b222018-06-07 22:07:154633 d.RunUntilComplete();
shivanisha8061c4202017-06-13 23:35:524634
[email protected]79e1fd62013-06-20 06:50:044635 {
4636 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194637 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524638 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044639 }
4640
maksim.sisovb53724b52016-09-16 05:30:504641 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194642 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364643 EXPECT_TRUE(d.auth_required_called());
4644 EXPECT_EQ(1, network_delegate.created_requests());
4645 EXPECT_EQ(0, network_delegate.destroyed_requests());
4646 }
4647 EXPECT_EQ(1, network_delegate.destroyed_requests());
4648}
4649
4650// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404651// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364652TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554653 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364654
4655 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304656 BlockingNetworkDelegate network_delegate(
4657 BlockingNetworkDelegate::SYNCHRONOUS);
4658 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364659 network_delegate.set_auth_retval(
4660 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4661
[email protected]f3cf9802011-10-28 18:44:584662 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364663
[email protected]ef2bf422012-05-11 03:27:094664 TestURLRequestContext context(true);
4665 context.set_network_delegate(&network_delegate);
4666 context.Init();
[email protected]c2911d72011-10-03 22:16:364667
4668 {
tommycli59a63432015-11-06 00:10:554669 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164670 std::unique_ptr<URLRequest> r(context.CreateRequest(
4671 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194672 r->Start();
Wez2a31b222018-06-07 22:07:154673 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364674
maksim.sisovb53724b52016-09-16 05:30:504675 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194676 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364677 EXPECT_FALSE(d.auth_required_called());
4678 EXPECT_EQ(1, network_delegate.created_requests());
4679 EXPECT_EQ(0, network_delegate.destroyed_requests());
4680 }
4681 EXPECT_EQ(1, network_delegate.destroyed_requests());
4682}
4683
[email protected]79e1fd62013-06-20 06:50:044684// Same as above, but also tests that GetFullRequestHeaders returns the proper
4685// headers (for the first or second request) when called at the proper times.
4686TEST_F(URLRequestTestHTTP,
4687 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554688 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044689
4690 TestDelegate d;
4691 BlockingNetworkDelegate network_delegate(
4692 BlockingNetworkDelegate::SYNCHRONOUS);
4693 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4694 network_delegate.set_auth_retval(
4695 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4696
4697 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4698
4699 TestURLRequestContext context(true);
4700 context.set_network_delegate(&network_delegate);
4701 context.Init();
4702
4703 {
tommycli59a63432015-11-06 00:10:554704 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164705 std::unique_ptr<URLRequest> r(context.CreateRequest(
4706 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194707 r->Start();
Wez2a31b222018-06-07 22:07:154708 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044709
maksim.sisovb53724b52016-09-16 05:30:504710 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194711 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044712 EXPECT_FALSE(d.auth_required_called());
4713 EXPECT_EQ(1, network_delegate.created_requests());
4714 EXPECT_EQ(0, network_delegate.destroyed_requests());
4715
4716 {
4717 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194718 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044719 EXPECT_TRUE(headers.HasHeader("Authorization"));
4720 }
4721 }
4722 EXPECT_EQ(1, network_delegate.destroyed_requests());
4723}
4724
[email protected]c2911d72011-10-03 22:16:364725// Tests that the network delegate can synchronously complete OnAuthRequired
4726// by cancelling authentication.
4727TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554728 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364729
4730 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304731 BlockingNetworkDelegate network_delegate(
4732 BlockingNetworkDelegate::SYNCHRONOUS);
4733 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364734 network_delegate.set_auth_retval(
4735 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4736
[email protected]ef2bf422012-05-11 03:27:094737 TestURLRequestContext context(true);
4738 context.set_network_delegate(&network_delegate);
4739 context.Init();
[email protected]c2911d72011-10-03 22:16:364740
4741 {
tommycli59a63432015-11-06 00:10:554742 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164743 std::unique_ptr<URLRequest> r(context.CreateRequest(
4744 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194745 r->Start();
Wez2a31b222018-06-07 22:07:154746 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364747
maksim.sisovb53724b52016-09-16 05:30:504748 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194749 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364750 EXPECT_FALSE(d.auth_required_called());
4751 EXPECT_EQ(1, network_delegate.created_requests());
4752 EXPECT_EQ(0, network_delegate.destroyed_requests());
4753 }
4754 EXPECT_EQ(1, network_delegate.destroyed_requests());
4755}
4756
4757// Tests that the network delegate can asynchronously complete OnAuthRequired
4758// by taking no action. This indicates that the NetworkDelegate does not want
4759// to handle the challenge, and is passing the buck along to the
4760// URLRequest::Delegate.
4761TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554762 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364763
4764 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304765 BlockingNetworkDelegate network_delegate(
4766 BlockingNetworkDelegate::AUTO_CALLBACK);
4767 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364768
[email protected]ef2bf422012-05-11 03:27:094769 TestURLRequestContext context(true);
4770 context.set_network_delegate(&network_delegate);
4771 context.Init();
[email protected]c2911d72011-10-03 22:16:364772
[email protected]f3cf9802011-10-28 18:44:584773 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364774
4775 {
tommycli59a63432015-11-06 00:10:554776 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164777 std::unique_ptr<URLRequest> r(context.CreateRequest(
4778 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194779 r->Start();
Wez2a31b222018-06-07 22:07:154780 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364781
maksim.sisovb53724b52016-09-16 05:30:504782 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194783 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364784 EXPECT_TRUE(d.auth_required_called());
4785 EXPECT_EQ(1, network_delegate.created_requests());
4786 EXPECT_EQ(0, network_delegate.destroyed_requests());
4787 }
4788 EXPECT_EQ(1, network_delegate.destroyed_requests());
4789}
4790
4791// Tests that the network delegate can asynchronously complete OnAuthRequired
4792// by setting credentials.
4793TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554794 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364795
4796 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304797 BlockingNetworkDelegate network_delegate(
4798 BlockingNetworkDelegate::AUTO_CALLBACK);
4799 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364800 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364801 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4802
[email protected]f3cf9802011-10-28 18:44:584803 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364804 network_delegate.set_auth_credentials(auth_credentials);
4805
[email protected]ef2bf422012-05-11 03:27:094806 TestURLRequestContext context(true);
4807 context.set_network_delegate(&network_delegate);
4808 context.Init();
[email protected]c2911d72011-10-03 22:16:364809
4810 {
tommycli59a63432015-11-06 00:10:554811 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164812 std::unique_ptr<URLRequest> r(context.CreateRequest(
4813 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194814 r->Start();
Wez2a31b222018-06-07 22:07:154815 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364816
maksim.sisovb53724b52016-09-16 05:30:504817 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194818 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364819 EXPECT_FALSE(d.auth_required_called());
4820 EXPECT_EQ(1, network_delegate.created_requests());
4821 EXPECT_EQ(0, network_delegate.destroyed_requests());
4822 }
4823 EXPECT_EQ(1, network_delegate.destroyed_requests());
4824}
4825
4826// Tests that the network delegate can asynchronously complete OnAuthRequired
4827// by cancelling authentication.
4828TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554829 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364830
4831 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304832 BlockingNetworkDelegate network_delegate(
4833 BlockingNetworkDelegate::AUTO_CALLBACK);
4834 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364835 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364836 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4837
[email protected]ef2bf422012-05-11 03:27:094838 TestURLRequestContext context(true);
4839 context.set_network_delegate(&network_delegate);
4840 context.Init();
[email protected]c2911d72011-10-03 22:16:364841
4842 {
tommycli59a63432015-11-06 00:10:554843 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164844 std::unique_ptr<URLRequest> r(context.CreateRequest(
4845 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194846 r->Start();
Wez2a31b222018-06-07 22:07:154847 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364848
maksim.sisovb53724b52016-09-16 05:30:504849 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194850 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364851 EXPECT_FALSE(d.auth_required_called());
4852 EXPECT_EQ(1, network_delegate.created_requests());
4853 EXPECT_EQ(0, network_delegate.destroyed_requests());
4854 }
4855 EXPECT_EQ(1, network_delegate.destroyed_requests());
4856}
4857
David Benjamin0bda12f2018-02-07 19:58:454858// Tests that NetworkDelegate header overrides from the 401 response do not
4859// affect the 200 response. This is a regression test for
4860// https://crbug.com/801237.
4861TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
4862 ASSERT_TRUE(http_test_server()->Start());
4863
4864 TestDelegate d;
4865 d.set_credentials(AuthCredentials(kUser, kSecret));
4866 default_network_delegate_.set_add_header_to_first_response(true);
4867
4868 {
4869 GURL url(http_test_server()->GetURL("/auth-basic"));
Ryan Sleevib8449e02018-07-15 04:31:074870 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:454871 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4872 r->Start();
4873
Wez2a31b222018-06-07 22:07:154874 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:454875
4876 EXPECT_EQ(OK, d.request_status());
4877 EXPECT_EQ(200, r->GetResponseCode());
4878 EXPECT_TRUE(d.auth_required_called());
4879 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
4880 }
4881
4882 {
4883 GURL url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:074884 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:454885 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4886 r->Start();
4887
Wez2a31b222018-06-07 22:07:154888 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:454889
4890 // Check that set_add_header_to_first_response normally adds a header.
4891 EXPECT_EQ(OK, d.request_status());
4892 EXPECT_EQ(200, r->GetResponseCode());
4893 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
4894 }
4895}
4896
[email protected]9045b8822012-01-13 20:35:354897// Tests that we can handle when a network request was canceled while we were
4898// waiting for the network delegate.
4899// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4900TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554901 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354902
4903 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304904 BlockingNetworkDelegate network_delegate(
4905 BlockingNetworkDelegate::USER_CALLBACK);
4906 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354907
[email protected]ef2bf422012-05-11 03:27:094908 TestURLRequestContext context(true);
4909 context.set_network_delegate(&network_delegate);
4910 context.Init();
[email protected]9045b8822012-01-13 20:35:354911
4912 {
rhalavatib7bd7c792017-04-27 05:25:164913 std::unique_ptr<URLRequest> r(
4914 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4915 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354916
[email protected]f7022f32014-08-21 16:32:194917 r->Start();
Wez2a31b222018-06-07 22:07:154918 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304919 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4920 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354921 EXPECT_EQ(0, network_delegate.completed_requests());
4922 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194923 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354924 // Ensure that network delegate is notified.
4925 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504926 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354927 EXPECT_EQ(1, network_delegate.created_requests());
4928 EXPECT_EQ(0, network_delegate.destroyed_requests());
4929 }
4930 EXPECT_EQ(1, network_delegate.destroyed_requests());
4931}
4932
4933// Tests that we can handle when a network request was canceled while we were
4934// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:004935// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
4936// callback.
[email protected]9045b8822012-01-13 20:35:354937TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554938 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354939
4940 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304941 BlockingNetworkDelegate network_delegate(
4942 BlockingNetworkDelegate::USER_CALLBACK);
4943 network_delegate.set_block_on(
4944 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354945
[email protected]ef2bf422012-05-11 03:27:094946 TestURLRequestContext context(true);
4947 context.set_network_delegate(&network_delegate);
4948 context.Init();
[email protected]9045b8822012-01-13 20:35:354949
4950 {
rhalavatib7bd7c792017-04-27 05:25:164951 std::unique_ptr<URLRequest> r(
4952 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4953 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354954
[email protected]f7022f32014-08-21 16:32:194955 r->Start();
Wez2a31b222018-06-07 22:07:154956 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304957 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4958 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354959 EXPECT_EQ(0, network_delegate.completed_requests());
4960 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194961 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354962 // Ensure that network delegate is notified.
4963 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504964 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354965 EXPECT_EQ(1, network_delegate.created_requests());
4966 EXPECT_EQ(0, network_delegate.destroyed_requests());
4967 }
4968 EXPECT_EQ(1, network_delegate.destroyed_requests());
4969}
4970
4971// Tests that we can handle when a network request was canceled while we were
4972// waiting for the network delegate.
4973// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4974TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554975 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354976
4977 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304978 BlockingNetworkDelegate network_delegate(
4979 BlockingNetworkDelegate::USER_CALLBACK);
4980 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354981
[email protected]ef2bf422012-05-11 03:27:094982 TestURLRequestContext context(true);
4983 context.set_network_delegate(&network_delegate);
4984 context.Init();
[email protected]9045b8822012-01-13 20:35:354985
4986 {
rhalavatib7bd7c792017-04-27 05:25:164987 std::unique_ptr<URLRequest> r(
4988 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4989 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354990
[email protected]f7022f32014-08-21 16:32:194991 r->Start();
Wez2a31b222018-06-07 22:07:154992 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304993 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4994 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354995 EXPECT_EQ(0, network_delegate.completed_requests());
4996 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194997 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354998 // Ensure that network delegate is notified.
4999 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505000 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355001 EXPECT_EQ(1, network_delegate.created_requests());
5002 EXPECT_EQ(0, network_delegate.destroyed_requests());
5003 }
5004 EXPECT_EQ(1, network_delegate.destroyed_requests());
5005}
5006
5007// Tests that we can handle when a network request was canceled while we were
5008// waiting for the network delegate.
5009// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:025010TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:555011 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355012
5013 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305014 BlockingNetworkDelegate network_delegate(
5015 BlockingNetworkDelegate::USER_CALLBACK);
5016 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:355017
[email protected]ef2bf422012-05-11 03:27:095018 TestURLRequestContext context(true);
5019 context.set_network_delegate(&network_delegate);
5020 context.Init();
[email protected]9045b8822012-01-13 20:35:355021
5022 {
danakj8522a25b2016-04-16 00:17:365023 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165024 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
5025 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355026
[email protected]f7022f32014-08-21 16:32:195027 r->Start();
Wez2a31b222018-06-07 22:07:155028 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305029 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
5030 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355031 EXPECT_EQ(0, network_delegate.completed_requests());
5032 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195033 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355034 // Ensure that network delegate is notified.
5035 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505036 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355037 EXPECT_EQ(1, network_delegate.created_requests());
5038 EXPECT_EQ(0, network_delegate.destroyed_requests());
5039 }
5040 EXPECT_EQ(1, network_delegate.destroyed_requests());
5041}
5042
tommycli59a63432015-11-06 00:10:555043namespace {
5044
danakj8522a25b2016-04-16 00:17:365045std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:555046 const test_server::HttpRequest& request) {
5047 if (request.headers.find("Host") == request.headers.end() ||
5048 request.headers.at("Host") != "www.server-auth.com" ||
5049 request.method != test_server::METHOD_CONNECT) {
5050 return nullptr;
5051 }
5052
danakj8522a25b2016-04-16 00:17:365053 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:555054 new test_server::BasicHttpResponse);
5055 http_response->set_code(HTTP_UNAUTHORIZED);
5056 http_response->AddCustomHeader("WWW-Authenticate",
5057 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:485058 return std::move(http_response);
tommycli59a63432015-11-06 00:10:555059}
5060
5061} // namespace
5062
5063// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:115064// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:555065// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:355066TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:555067 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:125068 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:555069 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115070
[email protected]ceefd7fd2012-11-29 00:36:245071 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:045072 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:555073 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:505074
[email protected]dc651782009-02-14 01:45:085075 TestDelegate d;
5076 {
danakj8522a25b2016-04-16 00:17:365077 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165078 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
5079 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:085080
[email protected]f7022f32014-08-21 16:32:195081 r->Start();
5082 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:085083
Wez2a31b222018-06-07 22:07:155084 d.RunUntilComplete();
[email protected]dc651782009-02-14 01:45:085085
[email protected]d8fc4722014-06-13 13:17:155086 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:475087 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:505088 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:085089 }
5090}
5091
[email protected]b89290212009-08-14 22:37:355092TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:555093 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115094
initial.commit586acc5fe2008-07-26 22:42:525095 TestDelegate d;
5096 {
Ryan Sleevib8449e02018-07-15 04:31:075097 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165098 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5099 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525100
[email protected]f7022f32014-08-21 16:32:195101 r->Start();
5102 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525103
Wez2a31b222018-06-07 22:07:155104 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525105
5106 EXPECT_EQ(1, d.response_started_count());
5107 EXPECT_FALSE(d.received_data_before_response());
5108 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555109 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195110 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555111 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195112 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:165113
[email protected]9e743cd2010-03-16 07:03:535114 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:525115 }
initial.commit586acc5fe2008-07-26 22:42:525116}
5117
[email protected]263163f2012-06-14 22:40:345118// This test has the server send a large number of cookies to the client.
5119// To ensure that no number of cookies causes a crash, a galloping binary
5120// search is used to estimate that maximum number of cookies that are accepted
5121// by the browser. Beyond the maximum number, the request will fail with
5122// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:315123#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:305124// http://crbug.com/177916
5125#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
5126#else
5127#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
5128#endif // defined(OS_WIN)
5129TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:555130 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:345131
5132 int lower_bound = 0;
5133 int upper_bound = 1;
5134
5135 // Double the number of cookies until the response header limits are
5136 // exceeded.
5137 while (DoManyCookiesRequest(upper_bound)) {
5138 lower_bound = upper_bound;
5139 upper_bound *= 2;
5140 ASSERT_LT(upper_bound, 1000000);
5141 }
5142
pkasting6b68a162014-12-01 22:10:295143 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:345144 if (tolerance < 2)
5145 tolerance = 2;
5146
5147 // Perform a binary search to find the highest possible number of cookies,
5148 // within the desired tolerance.
5149 while (upper_bound - lower_bound >= tolerance) {
5150 int num_cookies = (lower_bound + upper_bound) / 2;
5151
5152 if (DoManyCookiesRequest(num_cookies))
5153 lower_bound = num_cookies;
5154 else
5155 upper_bound = num_cookies;
5156 }
5157 // Success: the test did not crash.
5158}
5159
[email protected]b89290212009-08-14 22:37:355160TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:555161 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115162
initial.commit586acc5fe2008-07-26 22:42:525163 TestDelegate d;
5164 {
Ryan Sleevib8449e02018-07-15 04:31:075165 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165166 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5167 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525168
[email protected]f7022f32014-08-21 16:32:195169 r->Start();
5170 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525171
Wez2a31b222018-06-07 22:07:155172 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525173
5174 EXPECT_EQ(1, d.response_started_count());
5175 EXPECT_FALSE(d.received_data_before_response());
5176 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555177 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195178 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555179 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195180 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:525181 }
[email protected]5d7b373e2009-09-02 07:19:035182}
5183
[email protected]79e1fd62013-06-20 06:50:045184TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555185 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045186
5187 TestDelegate d;
5188 {
tommycli59a63432015-11-06 00:10:555189 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075190 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165191 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045192
5193 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195194 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045195
[email protected]f7022f32014-08-21 16:32:195196 r->Start();
5197 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045198
Wez2a31b222018-06-07 22:07:155199 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:045200
5201 EXPECT_EQ(1, d.response_started_count());
5202 EXPECT_FALSE(d.received_data_before_response());
5203 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555204 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195205 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555206 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195207 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:045208
5209 EXPECT_TRUE(d.have_full_request_headers());
5210 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5211 }
5212}
5213
[email protected]58e32bb2013-01-21 18:23:255214TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555215 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255216
5217 TestDelegate d;
5218 {
Ryan Sleevib8449e02018-07-15 04:31:075219 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165220 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5221 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255222
[email protected]f7022f32014-08-21 16:32:195223 r->Start();
5224 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255225
Wez2a31b222018-06-07 22:07:155226 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255227
5228 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195229 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255230 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5231
5232 EXPECT_EQ(1, d.response_started_count());
5233 EXPECT_FALSE(d.received_data_before_response());
5234 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555235 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195236 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555237 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195238 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:255239 }
5240}
5241
tommycli59a63432015-11-06 00:10:555242// TODO(svaldez): Update tests to use EmbeddedTestServer.
5243#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395244TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555245 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555246 base::FilePath(kTestFilePath));
5247
5248 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395249
5250 // Parameter that specifies the Content-Length field in the response:
5251 // C - Compressed length.
5252 // U - Uncompressed length.
5253 // L - Large length (larger than both C & U).
5254 // M - Medium length (between C & U).
5255 // S - Small length (smaller than both C & U).
5256 const char test_parameters[] = "CULMS";
Avi Drissman4365a4782018-12-28 19:26:245257 const int num_tests = base::size(test_parameters) - 1; // Skip NULL.
[email protected]aad63572011-05-24 20:14:395258 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445259 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395260 // S has too little data, but we seem to accept it.
5261 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375262 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395263
xunjielifb4da222016-07-14 18:38:595264 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:195265 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
xunjielifb4da222016-07-14 18:38:595266 file_path = file_path.Append(kTestFilePath);
5267 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5268 std::string expected_content;
5269 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5270
5271 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395272 TestDelegate d;
5273 {
tommycli59a63432015-11-06 00:10:555274 std::string test_file = base::StringPrintf(
5275 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395276
[email protected]ceefd7fd2012-11-29 00:36:245277 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095278 TestURLRequestContext context(true);
5279 context.set_network_delegate(&network_delegate);
5280 context.Init();
[email protected]87a09a92011-07-14 15:50:505281
rhalavatib7bd7c792017-04-27 05:25:165282 std::unique_ptr<URLRequest> r(
5283 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5284 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195285 r->Start();
5286 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395287
Wez2a31b222018-06-07 22:07:155288 d.RunUntilComplete();
[email protected]aad63572011-05-24 20:14:395289
5290 EXPECT_EQ(1, d.response_started_count());
5291 EXPECT_FALSE(d.received_data_before_response());
5292 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505293 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395294 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505295 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5296 << "\"";
xunjielifb4da222016-07-14 18:38:595297 if (test_parameters[i] == 'S') {
5298 // When content length is smaller than both compressed length and
5299 // uncompressed length, HttpStreamParser might not read the full
5300 // response body.
5301 continue;
5302 }
5303 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395304 } else {
maksim.sisovb53724b52016-09-16 05:30:505305 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395306 << " Parameter = \"" << test_file << "\"";
5307 }
5308 }
5309 }
5310}
tommycli59a63432015-11-06 00:10:555311#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395312
[email protected]58e32bb2013-01-21 18:23:255313TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555314 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255315
tommycli59a63432015-11-06 00:10:555316 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455317 GURL original_url =
tommycli59a63432015-11-06 00:10:555318 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255319 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075320 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165321 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195322 req->Start();
Wez2a31b222018-06-07 22:07:155323 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255324
5325 EXPECT_EQ(1, d.response_started_count());
5326 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195327 EXPECT_EQ(destination_url, req->url());
5328 EXPECT_EQ(original_url, req->original_url());
5329 ASSERT_EQ(2U, req->url_chain().size());
5330 EXPECT_EQ(original_url, req->url_chain()[0]);
5331 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255332
5333 LoadTimingInfo load_timing_info_before_redirect;
5334 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5335 &load_timing_info_before_redirect));
5336 TestLoadTimingNotReused(load_timing_info_before_redirect,
5337 CONNECT_TIMING_HAS_DNS_TIMES);
5338
5339 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195340 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255341 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5342
5343 // Check that a new socket was used on redirect, since the server does not
5344 // supposed keep-alive sockets, and that the times before the redirect are
5345 // before the ones recorded for the second request.
5346 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5347 load_timing_info.socket_log_id);
5348 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5349 load_timing_info.connect_timing.connect_start);
5350}
5351
[email protected]8f1ac082011-04-19 21:14:135352TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555353 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135354
tommycli59a63432015-11-06 00:10:555355 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455356 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555357 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5358 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5359 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135360 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075361 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165362 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195363 req->Start();
Wez2a31b222018-06-07 22:07:155364 d.RunUntilComplete();
[email protected]8f1ac082011-04-19 21:14:135365
5366 EXPECT_EQ(1, d.response_started_count());
5367 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195368 EXPECT_EQ(destination_url, req->url());
5369 EXPECT_EQ(original_url, req->original_url());
5370 ASSERT_EQ(3U, req->url_chain().size());
5371 EXPECT_EQ(original_url, req->url_chain()[0]);
5372 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5373 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135374}
5375
[email protected]abe1c4a2013-10-25 19:28:515376// First and second pieces of information logged by delegates to URLRequests.
5377const char kFirstDelegateInfo[] = "Wonderful delegate";
5378const char kSecondDelegateInfo[] = "Exciting delegate";
5379
5380// Logs delegate information to a URLRequest. The first string is logged
5381// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5382// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5383// another asynchronous call is used to clear the delegate information
5384// before calling a callback. The object then deletes itself.
5385class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5386 public:
David Benjamind1f287bf2018-06-12 01:57:205387 using Callback = base::OnceCallback<void()>;
[email protected]abe1c4a2013-10-25 19:28:515388
5389 // Each time delegate information is added to the URLRequest, the resulting
5390 // load state is checked. The expected load state after each request is
5391 // passed in as an argument.
5392 static void Run(URLRequest* url_request,
5393 LoadState expected_first_load_state,
5394 LoadState expected_second_load_state,
5395 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205396 Callback callback) {
tzik38f920a2018-08-01 04:41:205397 // base::MakeRefCounted<AsyncDelegateLogger> is unavailable here, since the
5398 // constructor of AsyncDelegateLogger is private.
5399 auto logger = base::WrapRefCounted(new AsyncDelegateLogger(
David Benjamind1f287bf2018-06-12 01:57:205400 url_request, expected_first_load_state, expected_second_load_state,
tzik38f920a2018-08-01 04:41:205401 expected_third_load_state, std::move(callback)));
[email protected]abe1c4a2013-10-25 19:28:515402 logger->Start();
5403 }
5404
5405 // Checks that the log entries, starting with log_position, contain the
5406 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5407 // recorded. Returns the index of entry after the expected number of
5408 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465409 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515410 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515411 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5412 if (log_position + 3 >= entries.size()) {
5413 ADD_FAILURE() << "Not enough log entries";
5414 return entries.size();
5415 }
5416 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005417 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5418 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075419 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515420 &delegate_info));
5421 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5422
5423 ++log_position;
mikecirone8b85c432016-09-08 19:11:005424 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5425 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515426
5427 ++log_position;
mikecirone8b85c432016-09-08 19:11:005428 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5429 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075430 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515431 &delegate_info));
5432 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5433
5434 ++log_position;
mikecirone8b85c432016-09-08 19:11:005435 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5436 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515437
5438 return log_position + 1;
5439 }
5440
5441 private:
5442 friend class base::RefCounted<AsyncDelegateLogger>;
5443
5444 AsyncDelegateLogger(URLRequest* url_request,
5445 LoadState expected_first_load_state,
5446 LoadState expected_second_load_state,
5447 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205448 Callback callback)
[email protected]abe1c4a2013-10-25 19:28:515449 : url_request_(url_request),
5450 expected_first_load_state_(expected_first_load_state),
5451 expected_second_load_state_(expected_second_load_state),
5452 expected_third_load_state_(expected_third_load_state),
David Benjamind1f287bf2018-06-12 01:57:205453 callback_(std::move(callback)) {}
[email protected]abe1c4a2013-10-25 19:28:515454
Chris Watkins7a41d3552017-12-01 02:13:275455 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515456
5457 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535458 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515459 LoadStateWithParam load_state = url_request_->GetLoadState();
5460 EXPECT_EQ(expected_first_load_state_, load_state.state);
5461 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455462 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155463 FROM_HERE,
5464 base::BindOnce(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515465 }
5466
5467 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535468 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515469 LoadStateWithParam load_state = url_request_->GetLoadState();
5470 EXPECT_EQ(expected_second_load_state_, load_state.state);
5471 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5472 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5473 } else {
5474 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5475 }
skyostil4891b25b2015-06-11 11:43:455476 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155477 FROM_HERE, base::BindOnce(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515478 }
5479
5480 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535481 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515482 LoadStateWithParam load_state = url_request_->GetLoadState();
5483 EXPECT_EQ(expected_third_load_state_, load_state.state);
5484 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085485 EXPECT_EQ(base::string16(), load_state.param);
David Benjamind1f287bf2018-06-12 01:57:205486 std::move(callback_).Run();
[email protected]abe1c4a2013-10-25 19:28:515487 }
5488
5489 URLRequest* url_request_;
5490 const int expected_first_load_state_;
5491 const int expected_second_load_state_;
5492 const int expected_third_load_state_;
David Benjamind1f287bf2018-06-12 01:57:205493 Callback callback_;
[email protected]abe1c4a2013-10-25 19:28:515494
5495 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5496};
5497
5498// NetworkDelegate that logs delegate information before a request is started,
5499// before headers are sent, when headers are read, and when auth information
5500// is requested. Uses AsyncDelegateLogger.
5501class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5502 public:
Chris Watkins7a41d3552017-12-01 02:13:275503 AsyncLoggingNetworkDelegate() = default;
5504 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515505
5506 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205507 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205508 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:205509 GURL* new_url) override {
David Benjamind1f287bf2018-06-12 01:57:205510 // TestNetworkDelegate always completes synchronously.
5511 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
5512 request, base::NullCallback(), new_url));
5513 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515514 }
5515
ryansturm2343cb62016-06-15 01:09:005516 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205517 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:005518 HttpRequestHeaders* headers) override {
David Benjamind1f287bf2018-06-12 01:57:205519 // TestNetworkDelegate always completes synchronously.
5520 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
5521 request, base::NullCallback(), headers));
5522 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515523 }
5524
dchengb03027d2014-10-21 12:00:205525 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515526 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205527 CompletionOnceCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515528 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165529 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135530 GURL* allowed_unsafe_redirect_url) override {
David Benjamind1f287bf2018-06-12 01:57:205531 // TestNetworkDelegate always completes synchronously.
5532 CHECK_NE(ERR_IO_PENDING,
5533 TestNetworkDelegate::OnHeadersReceived(
5534 request, base::NullCallback(), original_response_headers,
5535 override_response_headers, allowed_unsafe_redirect_url));
5536 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515537 }
5538
dchengb03027d2014-10-21 12:00:205539 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515540 URLRequest* request,
5541 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:205542 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:135543 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515544 AsyncDelegateLogger::Run(
David Benjamind1f287bf2018-06-12 01:57:205545 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5546 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5547 base::BindOnce(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5548 std::move(callback), credentials));
[email protected]abe1c4a2013-10-25 19:28:515549 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5550 }
5551
5552 private:
David Benjamind1f287bf2018-06-12 01:57:205553 static int RunCallbackAsynchronously(URLRequest* request,
5554 CompletionOnceCallback callback) {
5555 AsyncDelegateLogger::Run(request, LOAD_STATE_WAITING_FOR_DELEGATE,
5556 LOAD_STATE_WAITING_FOR_DELEGATE,
5557 LOAD_STATE_WAITING_FOR_DELEGATE,
5558 base::BindOnce(std::move(callback), OK));
[email protected]abe1c4a2013-10-25 19:28:515559 return ERR_IO_PENDING;
5560 }
5561
David Benjamind1f287bf2018-06-12 01:57:205562 static void SetAuthAndResume(AuthCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515563 AuthCredentials* credentials) {
5564 *credentials = AuthCredentials(kUser, kSecret);
David Benjamind1f287bf2018-06-12 01:57:205565 std::move(callback).Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
[email protected]abe1c4a2013-10-25 19:28:515566 }
5567
5568 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5569};
5570
5571// URLRequest::Delegate that logs delegate information when the headers
5572// are received, when each read completes, and during redirects. Uses
5573// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5574//
5575// Inherits from TestDelegate to reuse the TestDelegate code to handle
5576// advancing to the next step in most cases, as well as cancellation.
5577class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5578 public:
5579 enum CancelStage {
5580 NO_CANCEL = 0,
5581 CANCEL_ON_RECEIVED_REDIRECT,
5582 CANCEL_ON_RESPONSE_STARTED,
5583 CANCEL_ON_READ_COMPLETED
5584 };
5585
5586 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5587 : cancel_stage_(cancel_stage) {
5588 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5589 set_cancel_in_received_redirect(true);
5590 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5591 set_cancel_in_response_started(true);
5592 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5593 set_cancel_in_received_data(true);
5594 }
Chris Watkins7a41d3552017-12-01 02:13:275595 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515596
5597 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205598 void OnReceivedRedirect(URLRequest* request,
5599 const RedirectInfo& redirect_info,
5600 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515601 *defer_redirect = true;
5602 AsyncDelegateLogger::Run(
5603 request,
5604 LOAD_STATE_WAITING_FOR_DELEGATE,
5605 LOAD_STATE_WAITING_FOR_DELEGATE,
5606 LOAD_STATE_WAITING_FOR_DELEGATE,
5607 base::Bind(
5608 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595609 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515610 }
5611
maksim.sisov0f4aa142016-09-05 05:55:285612 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515613 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285614 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5615 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5616 base::Bind(
5617 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5618 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515619 }
5620
dchengb03027d2014-10-21 12:00:205621 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515622 AsyncDelegateLogger::Run(
5623 request,
5624 LOAD_STATE_IDLE,
5625 LOAD_STATE_IDLE,
5626 LOAD_STATE_IDLE,
5627 base::Bind(
5628 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5629 base::Unretained(this), request, bytes_read));
5630 }
5631
5632 private:
5633 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595634 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515635 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595636 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515637 // FollowDeferredRedirect should not be called after cancellation.
5638 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5639 return;
Arthur Sonzognib8465ff72019-01-04 18:44:355640 if (!defer_redirect) {
5641 request->FollowDeferredRedirect(base::nullopt /* removed_headers */,
5642 base::nullopt /* modified_headers */);
5643 }
[email protected]abe1c4a2013-10-25 19:28:515644 }
5645
maksim.sisov0f4aa142016-09-05 05:55:285646 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515647 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285648 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515649 }
5650
5651 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5652 // The parent class continues the request.
5653 TestDelegate::OnReadCompleted(request, bytes_read);
5654 }
5655
5656 const CancelStage cancel_stage_;
5657
5658 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5659};
5660
5661// Tests handling of delegate info before a request starts.
5662TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555663 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515664
5665 TestDelegate request_delegate;
5666 TestURLRequestContext context(true);
5667 context.set_network_delegate(NULL);
5668 context.set_net_log(&net_log_);
5669 context.Init();
5670
5671 {
rhalavatib7bd7c792017-04-27 05:25:165672 std::unique_ptr<URLRequest> r(context.CreateRequest(
5673 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5674 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195675 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515676 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085677 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515678
5679 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195680 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515681 LOAD_STATE_WAITING_FOR_DELEGATE,
5682 LOAD_STATE_WAITING_FOR_DELEGATE,
5683 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195684 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515685
Wez2a31b222018-06-07 22:07:155686 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515687
[email protected]f7022f32014-08-21 16:32:195688 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505689 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515690 }
5691
mmenke43758e62015-05-04 21:09:465692 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515693 net_log_.GetEntries(&entries);
5694 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005695 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515696
5697 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5698
5699 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005700 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5701 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515702}
5703
5704// Tests handling of delegate info from a network delegate.
5705TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555706 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515707
5708 TestDelegate request_delegate;
5709 AsyncLoggingNetworkDelegate network_delegate;
5710 TestURLRequestContext context(true);
5711 context.set_network_delegate(&network_delegate);
5712 context.set_net_log(&net_log_);
5713 context.Init();
5714
5715 {
rhalavatib7bd7c792017-04-27 05:25:165716 std::unique_ptr<URLRequest> r(context.CreateRequest(
5717 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
5718 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195719 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515720 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085721 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515722
[email protected]f7022f32014-08-21 16:32:195723 r->Start();
Wez2a31b222018-06-07 22:07:155724 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515725
[email protected]f7022f32014-08-21 16:32:195726 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505727 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515728 EXPECT_EQ(1, network_delegate.created_requests());
5729 EXPECT_EQ(0, network_delegate.destroyed_requests());
5730 }
5731 EXPECT_EQ(1, network_delegate.destroyed_requests());
5732
5733 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465734 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515735 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155736 static const NetLogEventType kExpectedEvents[] = {
5737 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5738 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5739 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5740 };
5741 for (NetLogEventType event : kExpectedEvents) {
5742 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515743 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155744 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515745
5746 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5747 log_position + 1);
5748
5749 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155750 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005751 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515752 }
5753
mikecirone8b85c432016-09-08 19:11:005754 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5755 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515756}
5757
5758// Tests handling of delegate info from a network delegate in the case of an
5759// HTTP redirect.
5760TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555761 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515762
5763 TestDelegate request_delegate;
5764 AsyncLoggingNetworkDelegate network_delegate;
5765 TestURLRequestContext context(true);
5766 context.set_network_delegate(&network_delegate);
5767 context.set_net_log(&net_log_);
5768 context.Init();
5769
5770 {
danakj8522a25b2016-04-16 00:17:365771 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555772 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165773 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195774 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515775 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085776 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515777
[email protected]f7022f32014-08-21 16:32:195778 r->Start();
Wez2a31b222018-06-07 22:07:155779 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515780
[email protected]f7022f32014-08-21 16:32:195781 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505782 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515783 EXPECT_EQ(2, network_delegate.created_requests());
5784 EXPECT_EQ(0, network_delegate.destroyed_requests());
5785 }
5786 EXPECT_EQ(1, network_delegate.destroyed_requests());
5787
5788 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465789 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515790 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155791 static const NetLogEventType kExpectedEvents[] = {
5792 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5793 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5794 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5795 };
5796 for (NetLogEventType event : kExpectedEvents) {
5797 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515798 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155799 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515800
David Benjamin9776ca22018-06-13 00:00:155801 log_position =
5802 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:515803
5804 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155805 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005806 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515807 }
5808
5809 // The URLRequest::Delegate then gets informed about the redirect.
5810 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155811 entries, log_position + 1,
5812 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
mikecirone8b85c432016-09-08 19:11:005813 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515814
5815 // The NetworkDelegate logged information in the same three events as before.
David Benjamin9776ca22018-06-13 00:00:155816 for (NetLogEventType event : kExpectedEvents) {
5817 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515818 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155819 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515820
5821 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5822 log_position + 1);
5823
5824 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155825 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005826 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515827 }
5828
mikecirone8b85c432016-09-08 19:11:005829 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5830 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515831}
5832
5833// Tests handling of delegate info from a network delegate in the case of HTTP
5834// AUTH.
5835TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555836 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515837
5838 TestDelegate request_delegate;
5839 AsyncLoggingNetworkDelegate network_delegate;
5840 TestURLRequestContext context(true);
5841 context.set_network_delegate(&network_delegate);
5842 context.set_net_log(&net_log_);
5843 context.Init();
5844
5845 {
rhalavatib7bd7c792017-04-27 05:25:165846 std::unique_ptr<URLRequest> r(context.CreateRequest(
5847 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
5848 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195849 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515850 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085851 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515852
[email protected]f7022f32014-08-21 16:32:195853 r->Start();
Wez2a31b222018-06-07 22:07:155854 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515855
[email protected]f7022f32014-08-21 16:32:195856 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505857 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515858 EXPECT_EQ(1, network_delegate.created_requests());
5859 EXPECT_EQ(0, network_delegate.destroyed_requests());
5860 }
5861 EXPECT_EQ(1, network_delegate.destroyed_requests());
5862
5863 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465864 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515865 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155866 static const NetLogEventType kExpectedEvents[] = {
5867 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5868 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5869 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5870 NetLogEventType::NETWORK_DELEGATE_AUTH_REQUIRED,
5871 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5872 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5873 };
5874 for (NetLogEventType event : kExpectedEvents) {
5875 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515876 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155877 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515878
David Benjamin9776ca22018-06-13 00:00:155879 log_position =
5880 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:515881
5882 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155883 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005884 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515885 }
5886
mikecirone8b85c432016-09-08 19:11:005887 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5888 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515889}
5890
tommycli59a63432015-11-06 00:10:555891// TODO(svaldez): Update tests to use EmbeddedTestServer.
5892#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515893// Tests handling of delegate info from a URLRequest::Delegate.
5894TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555895 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555896 base::FilePath(kTestFilePath));
5897
5898 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515899
5900 AsyncLoggingUrlRequestDelegate request_delegate(
5901 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5902 TestURLRequestContext context(true);
5903 context.set_network_delegate(NULL);
5904 context.set_net_log(&net_log_);
5905 context.Init();
5906
5907 {
5908 // A chunked response with delays between chunks is used to make sure that
5909 // attempts by the URLRequest delegate to log information while reading the
5910 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485911 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515912 // that it occurs.
danakj8522a25b2016-04-16 00:17:365913 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555914 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:165915 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195916 LoadStateWithParam load_state = r->GetLoadState();
5917 r->Start();
Wez2a31b222018-06-07 22:07:155918 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515919
[email protected]f7022f32014-08-21 16:32:195920 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505921 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515922 }
5923
mmenke43758e62015-05-04 21:09:465924 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515925 net_log_.GetEntries(&entries);
5926
[email protected]1826a402014-01-08 15:40:485927 size_t log_position = 0;
5928
[email protected]abe1c4a2013-10-25 19:28:515929 // The delegate info should only have been logged on header complete. Other
5930 // times it should silently be ignored.
David Benjamin9776ca22018-06-13 00:00:155931 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5932 entries, 0, NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST));
mikecirone8b85c432016-09-08 19:11:005933 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155934 entries, log_position + 1,
5935 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
mikecirone8b85c432016-09-08 19:11:005936 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515937
David Benjamin9776ca22018-06-13 00:00:155938 log_position =
5939 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:515940
5941 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155942 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
5943 entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005944 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515945
mikecirone8b85c432016-09-08 19:11:005946 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5947 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515948 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
David Benjamin9776ca22018-06-13 00:00:155949 entries, log_position + 1,
5950 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED));
[email protected]abe1c4a2013-10-25 19:28:515951}
tommycli59a63432015-11-06 00:10:555952#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515953
5954// Tests handling of delegate info from a URLRequest::Delegate in the case of
5955// an HTTP redirect.
5956TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555957 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515958
5959 AsyncLoggingUrlRequestDelegate request_delegate(
5960 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5961 TestURLRequestContext context(true);
5962 context.set_network_delegate(NULL);
5963 context.set_net_log(&net_log_);
5964 context.Init();
5965
5966 {
danakj8522a25b2016-04-16 00:17:365967 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555968 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165969 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195970 LoadStateWithParam load_state = r->GetLoadState();
5971 r->Start();
Wez2a31b222018-06-07 22:07:155972 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515973
[email protected]f7022f32014-08-21 16:32:195974 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505975 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515976 }
5977
mmenke43758e62015-05-04 21:09:465978 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515979 net_log_.GetEntries(&entries);
5980
5981 // Delegate info should only have been logged in OnReceivedRedirect and
5982 // OnResponseStarted.
5983 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:155984 static const NetLogEventType kExpectedEvents[] = {
5985 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
5986 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
5987 };
5988 for (NetLogEventType event : kExpectedEvents) {
5989 SCOPED_TRACE(NetLog::EventTypeToString(event));
5990 log_position = ExpectLogContainsSomewhereAfter(entries, log_position, event,
5991 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515992
David Benjamin9776ca22018-06-13 00:00:155993 log_position =
5994 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:515995
5996 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155997 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005998 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515999 }
6000
mikecirone8b85c432016-09-08 19:11:006001 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6002 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516003}
6004
6005// Tests handling of delegate info from a URLRequest::Delegate in the case of
6006// an HTTP redirect, with cancellation at various points.
6007TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:556008 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516009
6010 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
6011 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
6012 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
6013 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
6014 };
6015
David Benjamin9776ca22018-06-13 00:00:156016 for (auto cancel_stage : kCancelStages) {
6017 AsyncLoggingUrlRequestDelegate request_delegate(cancel_stage);
vishal.b62985ca92015-04-17 08:45:516018 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046019 TestURLRequestContext context(true);
[email protected]abe1c4a2013-10-25 19:28:516020 context.set_network_delegate(NULL);
6021 context.set_net_log(&net_log);
6022 context.Init();
6023
6024 {
danakj8522a25b2016-04-16 00:17:366025 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556026 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166027 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196028 LoadStateWithParam load_state = r->GetLoadState();
6029 r->Start();
Wez2a31b222018-06-07 22:07:156030 request_delegate.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506031 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
Wez2a31b222018-06-07 22:07:156032
6033 // Spin the message loop to run AsyncDelegateLogger task(s) posted after
6034 // the |request_delegate| completion task.
6035 base::RunLoop().RunUntilIdle();
[email protected]abe1c4a2013-10-25 19:28:516036 }
6037
mmenke43758e62015-05-04 21:09:466038 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516039 net_log.GetEntries(&entries);
6040
6041 // Delegate info is always logged in both OnReceivedRedirect and
6042 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6043 // OnResponseStarted delegate call is after cancellation, but logging is
6044 // still currently supported in that call.
6045 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156046 static const NetLogEventType kExpectedEvents[] = {
6047 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6048 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6049 };
6050 for (NetLogEventType event : kExpectedEvents) {
6051 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516052 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156053 entries, log_position, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516054
David Benjamin9776ca22018-06-13 00:00:156055 log_position =
6056 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516057
6058 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156059 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006060 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516061 }
6062
mikecirone8b85c432016-09-08 19:11:006063 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6064 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516065 }
6066}
6067
[email protected]847c0fa92012-11-06 16:37:426068namespace {
6069
6070const char kExtraHeader[] = "Allow-Snafu";
6071const char kExtraValue[] = "fubar";
6072
6073class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206074 void OnReceivedRedirect(URLRequest* request,
6075 const RedirectInfo& redirect_info,
6076 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596077 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426078 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6079 }
6080};
6081
6082} // namespace
6083
6084TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556085 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426086
tommycli59a63432015-11-06 00:10:556087 GURL destination_url =
6088 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6089 GURL original_url =
6090 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426091 RedirectWithAdditionalHeadersDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076092 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166093 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196094 req->Start();
Wez2a31b222018-06-07 22:07:156095 d.RunUntilComplete();
[email protected]847c0fa92012-11-06 16:37:426096
6097 std::string value;
[email protected]f7022f32014-08-21 16:32:196098 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426099 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6100 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196101 EXPECT_FALSE(req->is_pending());
6102 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426103 EXPECT_EQ(kExtraValue, d.data_received());
6104}
6105
[email protected]251a1b92012-11-13 11:01:096106namespace {
6107
6108const char kExtraHeaderToRemove[] = "To-Be-Removed";
6109
6110class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206111 void OnReceivedRedirect(URLRequest* request,
6112 const RedirectInfo& redirect_info,
6113 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596114 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096115 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6116 }
6117};
6118
6119} // namespace
6120
6121TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556122 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096123
tommycli59a63432015-11-06 00:10:556124 GURL destination_url = http_test_server()->GetURL(
6125 "/echoheader?" + std::string(kExtraHeaderToRemove));
6126 GURL original_url =
6127 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096128 RedirectWithHeaderRemovalDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076129 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166130 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196131 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6132 req->Start();
Wez2a31b222018-06-07 22:07:156133 d.RunUntilComplete();
[email protected]251a1b92012-11-13 11:01:096134
6135 std::string value;
[email protected]f7022f32014-08-21 16:32:196136 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096137 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196138 EXPECT_FALSE(req->is_pending());
6139 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096140 EXPECT_EQ("None", d.data_received());
6141}
6142
mmenke94f1bd92016-12-07 21:13:056143TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446144 TestDelegate d;
6145 {
Ryan Sleevib8449e02018-07-15 04:31:076146 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166147 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6148 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446149
[email protected]f7022f32014-08-21 16:32:196150 r->Start();
6151 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446152
[email protected]f7022f32014-08-21 16:32:196153 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446154
Wez2a31b222018-06-07 22:07:156155 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446156
6157 // We expect to receive OnResponseStarted even though the request has been
6158 // cancelled.
6159 EXPECT_EQ(1, d.response_started_count());
6160 EXPECT_EQ(0, d.bytes_received());
6161 EXPECT_FALSE(d.received_data_before_response());
6162 }
6163}
6164
mmenke94f1bd92016-12-07 21:13:056165TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556166 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446167
6168 TestDelegate d;
6169 {
Ryan Sleevib8449e02018-07-15 04:31:076170 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166171 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6172 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446173
6174 d.set_cancel_in_response_started(true);
6175
[email protected]f7022f32014-08-21 16:32:196176 r->Start();
6177 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446178
Wez2a31b222018-06-07 22:07:156179 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446180
6181 EXPECT_EQ(1, d.response_started_count());
6182 EXPECT_EQ(0, d.bytes_received());
6183 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506184 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446185 }
6186}
6187
mmenke94f1bd92016-12-07 21:13:056188TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556189 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446190
6191 TestDelegate d;
6192 {
Ryan Sleevib8449e02018-07-15 04:31:076193 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166194 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6195 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056196
6197 d.set_cancel_in_received_data(true);
6198
6199 r->Start();
6200 EXPECT_TRUE(r->is_pending());
6201
Wez2a31b222018-06-07 22:07:156202 d.RunUntilComplete();
mmenke94f1bd92016-12-07 21:13:056203
6204 EXPECT_EQ(1, d.response_started_count());
6205 EXPECT_NE(0, d.received_bytes_count());
6206 EXPECT_FALSE(d.received_data_before_response());
6207 EXPECT_EQ(ERR_ABORTED, d.request_status());
6208 }
6209}
6210
6211TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6212 ASSERT_TRUE(http_test_server()->Start());
6213
6214 TestDelegate d;
6215 {
6216 // This returns an empty response (With headers).
Ryan Sleevib8449e02018-07-15 04:31:076217 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166218 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6219 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446220
6221 d.set_cancel_in_received_data(true);
6222
[email protected]f7022f32014-08-21 16:32:196223 r->Start();
6224 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446225
Wez2a31b222018-06-07 22:07:156226 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446227
6228 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056229 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446230 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506231 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446232 }
6233}
6234
mmenke94f1bd92016-12-07 21:13:056235TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556236 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446237
6238 TestDelegate d;
6239 {
Ryan Sleevib8449e02018-07-15 04:31:076240 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166241 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6242 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446243
[email protected]f7022f32014-08-21 16:32:196244 r->Start();
6245 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446246
6247 // The request will be implicitly canceled when it is destroyed. The
6248 // test delegate must not post a quit message when this happens because
6249 // this test doesn't actually have a message loop. The quit message would
6250 // get put on this thread's message queue and the next test would exit
6251 // early, causing problems.
Wez0e717112018-06-18 23:09:226252 d.set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:446253 }
6254 // expect things to just cleanup properly.
6255
kimwjdalsl2bb4ff02015-12-16 22:06:026256 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446257 // message loop
6258 EXPECT_FALSE(d.received_data_before_response());
6259 EXPECT_EQ(0, d.bytes_received());
6260}
6261
mmenke94f1bd92016-12-07 21:13:056262TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556263 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446264
6265 // populate cache
6266 {
6267 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076268 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166269 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6270 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196271 r->Start();
Wez2a31b222018-06-07 22:07:156272 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506273 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446274 }
6275
6276 // cancel read from cache (see bug 990242)
6277 {
6278 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076279 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166280 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6281 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196282 r->Start();
6283 r->Cancel();
Wez2a31b222018-06-07 22:07:156284 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446285
maksim.sisovb53724b52016-09-16 05:30:506286 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446287 EXPECT_EQ(1, d.response_started_count());
6288 EXPECT_EQ(0, d.bytes_received());
6289 EXPECT_FALSE(d.received_data_before_response());
6290 }
6291}
6292
6293TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556294 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446295 HTTPUploadDataOperationTest("POST");
6296}
6297
6298TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556299 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446300 HTTPUploadDataOperationTest("PUT");
6301}
6302
6303TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556304 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446305
6306 TestDelegate d;
6307 {
Ryan Sleevib8449e02018-07-15 04:31:076308 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166309 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6310 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196311 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446312
[email protected]f7022f32014-08-21 16:32:196313 r->Start();
6314 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446315
Wez2a31b222018-06-07 22:07:156316 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446317
maksim.sisovb53724b52016-09-16 05:30:506318 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6319 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446320
6321 EXPECT_FALSE(d.received_data_before_response());
6322 EXPECT_TRUE(d.data_received().empty());
6323 }
6324}
6325
6326TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556327 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446328
6329 TestDelegate d;
6330 {
Ryan Sleevib8449e02018-07-15 04:31:076331 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166332 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6333 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196334 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446335
[email protected]6cdfd7f2013-02-08 20:40:156336 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196337 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026338 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446339
danakj8522a25b2016-04-16 00:17:366340 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446341
[email protected]6cdfd7f2013-02-08 20:40:156342 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196343 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476344 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446345 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196346 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146347 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076348 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046349 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6350 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446351
[email protected]f7022f32014-08-21 16:32:196352 r->Start();
6353 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446354
Wez2a31b222018-06-07 22:07:156355 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446356
avibf0746c2015-12-09 19:53:146357 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296358 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6359 ASSERT_LE(size64, std::numeric_limits<int>::max());
6360 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366361 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446362
[email protected]7600d0b2013-12-08 21:43:306363 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446364
maksim.sisovb53724b52016-09-16 05:30:506365 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6366 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446367
6368 EXPECT_FALSE(d.received_data_before_response());
6369
[email protected]329b68b2012-11-14 17:54:276370 EXPECT_EQ(size, d.bytes_received());
6371 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446372 }
6373}
6374
[email protected]999dd8c2013-11-12 06:45:546375TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556376 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546377
6378 TestDelegate d;
6379 {
Ryan Sleevib8449e02018-07-15 04:31:076380 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166381 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6382 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196383 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546384
danakj8522a25b2016-04-16 00:17:366385 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546386
Jeremy Roman0579ed62017-08-29 15:56:196387 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456388 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546389 base::FilePath(FILE_PATH_LITERAL(
6390 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076391 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046392 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6393 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546394
[email protected]f7022f32014-08-21 16:32:196395 r->Start();
6396 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546397
Wez2a31b222018-06-07 22:07:156398 d.RunUntilComplete();
[email protected]999dd8c2013-11-12 06:45:546399
[email protected]999dd8c2013-11-12 06:45:546400 EXPECT_TRUE(d.request_failed());
6401 EXPECT_FALSE(d.received_data_before_response());
6402 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506403 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546404 }
6405}
6406
mmenke56b0cbb912016-03-28 21:34:536407namespace {
6408
6409// Adds a standard set of data to an upload for chunked upload integration
6410// tests.
6411void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6412 writer->AppendData("a", 1, false);
6413 writer->AppendData("bcd", 3, false);
6414 writer->AppendData("this is a longer chunk than before.", 35, false);
6415 writer->AppendData("\r\n\r\n", 4, false);
6416 writer->AppendData("0", 1, false);
6417 writer->AppendData("2323", 4, true);
6418}
6419
6420// Checks that the upload data added in AddChunksToUpload() was echoed back from
6421// the server.
6422void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6423 // This should match the chunks sent by AddChunksToUpload().
6424 const std::string expected_data =
6425 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6426
maksim.sisovb53724b52016-09-16 05:30:506427 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6428 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536429
6430 EXPECT_FALSE(d->received_data_before_response());
6431
6432 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6433 EXPECT_EQ(expected_data, d->data_received());
6434}
6435
6436} // namespace
6437
[email protected]316c1e5e2012-09-12 15:17:446438TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556439 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446440
6441 TestDelegate d;
6442 {
Ryan Sleevib8449e02018-07-15 04:31:076443 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166444 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6445 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366446 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536447 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366448 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536449 upload_data_stream->CreateWriter();
6450 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196451 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536452 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196453 r->Start();
6454 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446455
Wez2a31b222018-06-07 22:07:156456 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446457
[email protected]f7022f32014-08-21 16:32:196458 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446459 }
6460}
6461
[email protected]329b68b2012-11-14 17:54:276462TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556463 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276464
6465 TestDelegate d;
6466 {
Ryan Sleevib8449e02018-07-15 04:31:076467 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166468 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6469 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366470 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536471 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366472 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536473 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046474 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196475 r->set_method("POST");
6476 r->Start();
6477 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536478 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156479 d.RunUntilComplete();
[email protected]329b68b2012-11-14 17:54:276480
[email protected]f7022f32014-08-21 16:32:196481 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276482 }
6483}
6484
Asanka Herathf05753e2018-08-16 17:38:206485TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556486 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446487
6488 TestDelegate d;
6489 {
Ryan Sleevib8449e02018-07-15 04:31:076490 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166491 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6492 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366493 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536494 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366495 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536496 upload_data_stream->CreateWriter();
6497 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196498 r->set_method("POST");
6499 r->Start();
6500 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446501
Asanka Herathf05753e2018-08-16 17:38:206502 // Pump messages until we start sending headers..
[email protected]255620da2013-08-19 13:14:296503 base::RunLoop().RunUntilIdle();
Asanka Herathf05753e2018-08-16 17:38:206504
6505 // And now wait for completion.
6506 base::RunLoop run_loop;
6507 d.set_on_complete(run_loop.QuitClosure());
mmenke56b0cbb912016-03-28 21:34:536508 AddDataToUpload(writer.get());
Asanka Herathf05753e2018-08-16 17:38:206509 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:446510
[email protected]f7022f32014-08-21 16:32:196511 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446512 }
6513}
6514
6515TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556516 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446517
6518 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076519 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166520 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6521 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196522 req->Start();
Wez2a31b222018-06-07 22:07:156523 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446524
[email protected]f7022f32014-08-21 16:32:196525 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446526
6527 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196528 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446529
6530 std::string header;
6531 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6532 EXPECT_EQ("private", header);
6533
6534 header.clear();
6535 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6536 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6537
6538 // The response has two "X-Multiple-Entries" headers.
6539 // This verfies our output has them concatenated together.
6540 header.clear();
6541 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6542 EXPECT_EQ("a, b", header);
6543}
6544
tommycli59a63432015-11-06 00:10:556545// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6546// security state. (see http://crbug.com/550977).
6547#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466548TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556549 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6550 https_test_server.SetSSLConfig(
6551 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6552 https_test_server.ServeFilesFromSourceDirectory(
6553 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466554 ASSERT_TRUE(https_test_server.Start());
6555
tommycli59a63432015-11-06 00:10:556556 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466557 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076558 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166559 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6560 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196561 request->Start();
Wez2a31b222018-06-07 22:07:156562 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466563
6564 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076565 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406566 TransportSecurityState::STSState sts_state;
6567 TransportSecurityState::PKPState pkp_state;
6568 EXPECT_TRUE(
6569 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6570 EXPECT_FALSE(
6571 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6572 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6573 sts_state.upgrade_mode);
6574 EXPECT_TRUE(sts_state.include_subdomains);
6575 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036576#if defined(OS_ANDROID)
6577 // Android's CertVerifyProc does not (yet) handle pins.
6578#else
martijnc0d6b622015-06-30 19:14:406579 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036580#endif
[email protected]37fd55fb2013-06-29 13:13:276581}
6582
estarka5da76702015-04-09 04:00:166583TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556584 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6585 https_test_server.ServeFilesFromSourceDirectory(
6586 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166587 ASSERT_TRUE(https_test_server.Start());
6588 // Make sure this test fails if the test server is changed to not
6589 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556590 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6591 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166592
6593 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076594 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166595 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6596 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166597 request->Start();
Wez2a31b222018-06-07 22:07:156598 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:166599 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076600 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406601 TransportSecurityState::STSState sts_state;
6602 EXPECT_FALSE(
6603 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166604}
6605
estark06e0dac2015-08-07 21:56:016606namespace {
Martijn Croonenb1383da2017-10-11 11:56:356607const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
Matt Mueller230996f12018-10-22 19:39:446608const char kPKPReportUri[] = "http://report-uri.preloaded.test/pkp";
6609const char kPKPHost[] = "with-report-uri-pkp.preloaded.test";
estark06e0dac2015-08-07 21:56:016610} // namespace
6611
Matt Mueller230996f12018-10-22 19:39:446612// Tests that reports get sent on PKP violations when a report-uri is set.
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516613TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
Matt Mueller230996f12018-10-22 19:39:446614 GURL report_uri(kPKPReportUri);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516615 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6616 https_test_server.SetSSLConfig(
6617 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6618 https_test_server.ServeFilesFromSourceDirectory(
6619 base::FilePath(kTestFilePath));
6620 ASSERT_TRUE(https_test_server.Start());
6621
Matt Mueller230996f12018-10-22 19:39:446622 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016623
6624 // Set up a pin for |test_server_hostname|.
6625 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446626 security_state.EnableStaticPinsForTesting();
6627 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016628
6629 MockCertificateReportSender mock_report_sender;
6630 security_state.SetReportSender(&mock_report_sender);
6631
6632 // Set up a MockCertVerifier to trigger a violation of the previously
6633 // set pin.
6634 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6635 ASSERT_TRUE(cert);
6636
6637 MockCertVerifier cert_verifier;
6638 CertVerifyResult verify_result;
6639 verify_result.verified_cert = cert;
6640 verify_result.is_issued_by_known_root = true;
6641 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446642 ASSERT_TRUE(
6643 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016644 verify_result.public_key_hashes.push_back(hash3);
6645 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6646
6647 TestNetworkDelegate network_delegate;
6648 TestURLRequestContext context(true);
6649 context.set_transport_security_state(&security_state);
6650 context.set_network_delegate(&network_delegate);
6651 context.set_cert_verifier(&cert_verifier);
6652 context.Init();
6653
6654 // Now send a request to trigger the violation.
6655 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366656 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446657 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166658 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016659 violating_request->Start();
Wez2a31b222018-06-07 22:07:156660 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016661
6662 // Check that a report was sent.
6663 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6664 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446665 EXPECT_EQ("application/json; charset=utf-8",
6666 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366667 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016668 base::JSONReader::Read(mock_report_sender.latest_report()));
6669 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086670 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016671 base::DictionaryValue* report_dict;
6672 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6673 std::string report_hostname;
6674 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6675 EXPECT_EQ(test_server_hostname, report_hostname);
6676}
6677
Matt Mueller230996f12018-10-22 19:39:446678// Tests that reports do not get sent on requests to static pkp hosts that
6679// don't have pin violations.
6680TEST_F(URLRequestTestHTTP, ProcessPKPWithNoViolation) {
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));
estark06e0dac2015-08-07 21:56:016686 ASSERT_TRUE(https_test_server.Start());
6687
Matt Mueller230996f12018-10-22 19:39:446688 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016689
6690 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446691 security_state.EnableStaticPinsForTesting();
6692 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016693 MockCertificateReportSender mock_report_sender;
6694 security_state.SetReportSender(&mock_report_sender);
6695
Matt Mueller230996f12018-10-22 19:39:446696 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6697 ASSERT_TRUE(cert);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516698 MockCertVerifier mock_cert_verifier;
Matt Mueller230996f12018-10-22 19:39:446699 CertVerifyResult verify_result;
6700 verify_result.verified_cert = cert;
6701 verify_result.is_issued_by_known_root = true;
6702 HashValue hash;
6703 // The expected value of GoodPin1 used by |test_default::kHSTSSource|.
6704 ASSERT_TRUE(
6705 hash.FromString("sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY="));
6706 verify_result.public_key_hashes.push_back(hash);
6707 mock_cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6708
6709 TestNetworkDelegate network_delegate;
estark06e0dac2015-08-07 21:56:016710 TestURLRequestContext context(true);
6711 context.set_transport_security_state(&security_state);
6712 context.set_network_delegate(&network_delegate);
6713 context.set_cert_verifier(&mock_cert_verifier);
estark06e0dac2015-08-07 21:56:016714 context.Init();
6715
6716 // Now send a request that does not trigger the violation.
6717 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366718 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446719 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166720 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016721 request->Start();
Wez2a31b222018-06-07 22:07:156722 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016723
Matt Mueller230996f12018-10-22 19:39:446724 // Check that the request succeeded, a report was not sent and the pkp was
6725 // not bypassed.
6726 EXPECT_EQ(OK, d.request_status());
estark06e0dac2015-08-07 21:56:016727 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6728 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
Matt Mueller230996f12018-10-22 19:39:446729 TransportSecurityState::STSState sts_state;
martijnc0d6b622015-06-30 19:14:406730 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:446731 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
6732 &sts_state, &pkp_state));
6733 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
6734 EXPECT_FALSE(request->ssl_info().pkp_bypassed);
estarka5da76702015-04-09 04:00:166735}
6736
dadriandf302c42016-06-10 18:48:596737TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6738 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6739 https_test_server.SetSSLConfig(
6740 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6741 https_test_server.ServeFilesFromSourceDirectory(
6742 base::FilePath(kTestFilePath));
6743 ASSERT_TRUE(https_test_server.Start());
6744
6745 // Set up a MockCertVerifier to be a local root that violates the pin
6746 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6747 ASSERT_TRUE(cert);
6748
6749 MockCertVerifier cert_verifier;
6750 CertVerifyResult verify_result;
6751 verify_result.verified_cert = cert;
6752 verify_result.is_issued_by_known_root = false;
6753 HashValue hash;
6754 ASSERT_TRUE(
6755 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6756 verify_result.public_key_hashes.push_back(hash);
6757 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
dadriandf302c42016-06-10 18:48:596758
Matt Mueller230996f12018-10-22 19:39:446759 std::string test_server_hostname = kPKPHost;
dadriandf302c42016-06-10 18:48:596760
Matt Mueller230996f12018-10-22 19:39:446761 // Set up PKP
dadriandf302c42016-06-10 18:48:596762 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446763 security_state.EnableStaticPinsForTesting();
6764 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
6765 MockCertificateReportSender mock_report_sender;
6766 security_state.SetReportSender(&mock_report_sender);
dadriandf302c42016-06-10 18:48:596767
6768 TestNetworkDelegate network_delegate;
6769 TestURLRequestContext context(true);
6770 context.set_transport_security_state(&security_state);
6771 context.set_network_delegate(&network_delegate);
6772 context.set_cert_verifier(&cert_verifier);
6773 context.Init();
6774
6775 TestDelegate d;
6776 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446777 https_test_server.GetURL(test_server_hostname, "/simple.html"),
6778 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:596779 request->Start();
Wez2a31b222018-06-07 22:07:156780 d.RunUntilComplete();
dadriandf302c42016-06-10 18:48:596781
Matt Mueller230996f12018-10-22 19:39:446782 // Check that the request succeeded, a report was not sent and the PKP was
6783 // bypassed.
6784 EXPECT_EQ(OK, d.request_status());
6785 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6786 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6787 TransportSecurityState::STSState sts_state;
dadriandf302c42016-06-10 18:48:596788 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:446789 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
6790 &sts_state, &pkp_state));
6791 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
dadriandf302c42016-06-10 18:48:596792 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6793}
6794
[email protected]242d8562012-10-30 21:20:466795TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556796 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6797 https_test_server.SetSSLConfig(
6798 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6799 https_test_server.ServeFilesFromSourceDirectory(
6800 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466801 ASSERT_TRUE(https_test_server.Start());
6802
tommycli59a63432015-11-06 00:10:556803 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166804
[email protected]242d8562012-10-30 21:20:466805 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076806 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:556807 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166808 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196809 request->Start();
Wez2a31b222018-06-07 22:07:156810 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466811
6812 // We should have set parameters from the first header, not the second.
6813 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076814 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406815 TransportSecurityState::STSState sts_state;
6816 EXPECT_TRUE(
6817 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6818 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6819 sts_state.upgrade_mode);
6820 EXPECT_FALSE(sts_state.include_subdomains);
6821 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466822}
6823
estark1614475f2016-03-10 03:46:476824// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6825// called.
6826class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6827 public:
6828 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:276829 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:476830
6831 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6832 const GURL& report_uri,
estarkae028b462017-06-20 23:25:016833 base::Time expiration,
estarkbf1b52962017-05-05 17:05:256834 const X509Certificate* validated_certificate_chain,
6835 const X509Certificate* served_certificate_chain,
6836 const SignedCertificateTimestampAndStatusList&
6837 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:476838 num_failures_++;
6839 }
6840
6841 uint32_t num_failures() { return num_failures_; }
6842
6843 private:
6844 uint32_t num_failures_;
6845};
6846
Emily Stark627238f2017-11-29 03:29:546847// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:476848// for every certificate.
6849class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6850 public:
6851 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:546852 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:276853 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:476854
Emily Stark627238f2017-11-29 03:29:546855 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:476856 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:236857 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:206858 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:476859 return default_result_;
6860 }
6861
Emily Stark627238f2017-11-29 03:29:546862 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:476863 default_result_ = default_result;
6864 }
6865
6866 private:
Emily Stark627238f2017-11-29 03:29:546867 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:476868};
6869
Emily Stark4cfecf072017-08-08 01:05:516870// Tests that Expect CT headers for the preload list are processed correctly.
6871TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:356872 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
6873
estark1614475f2016-03-10 03:46:476874 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6875 https_test_server.SetSSLConfig(
6876 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6877 https_test_server.ServeFilesFromSourceDirectory(
6878 base::FilePath(kTestFilePath));
6879 ASSERT_TRUE(https_test_server.Start());
6880
6881 MockExpectCTReporter reporter;
6882 TransportSecurityState transport_security_state;
6883 transport_security_state.enable_static_expect_ct_ = true;
6884 transport_security_state.SetExpectCTReporter(&reporter);
6885
6886 // Set up a MockCertVerifier to accept the certificate that the server sends.
6887 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6888 ASSERT_TRUE(cert);
6889 MockCertVerifier cert_verifier;
6890 CertVerifyResult verify_result;
6891 verify_result.verified_cert = cert;
6892 verify_result.is_issued_by_known_root = true;
6893 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6894
rsleevi22cae1672016-12-28 01:53:366895 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
6896 // CT violation.
6897 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:476898 MockCTPolicyEnforcer ct_policy_enforcer;
6899 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:546900 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:476901
6902 TestNetworkDelegate network_delegate;
6903 // Use a MockHostResolver (which by default maps all hosts to
6904 // 127.0.0.1) so that the request can be sent to a site on the Expect
6905 // CT preload list.
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);
vabr13d00742017-06-05 10:31:466913 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:476914 context.Init();
6915
6916 // Now send a request to trigger the violation.
6917 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:516918 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:476919 GURL::Replacements replace_host;
6920 replace_host.SetHostStr(kExpectCTStaticHostname);
6921 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:166922 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
6923 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:476924 violating_request->Start();
Wez2a31b222018-06-07 22:07:156925 d.RunUntilComplete();
estark1614475f2016-03-10 03:46:476926
6927 EXPECT_EQ(1u, reporter.num_failures());
6928}
Emily Stark4cfecf072017-08-08 01:05:516929
6930// Tests that Expect CT HTTP headers are processed correctly.
6931TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6932 base::test::ScopedFeatureList feature_list;
6933 feature_list.InitAndEnableFeature(
6934 TransportSecurityState::kDynamicExpectCTFeature);
6935
6936 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6937 https_test_server.SetSSLConfig(
6938 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6939 https_test_server.ServeFilesFromSourceDirectory(
6940 base::FilePath(kTestFilePath));
6941 ASSERT_TRUE(https_test_server.Start());
6942
6943 MockExpectCTReporter reporter;
6944 TransportSecurityState transport_security_state;
6945 transport_security_state.SetExpectCTReporter(&reporter);
6946
6947 // Set up a MockCertVerifier to accept the certificate that the server sends.
6948 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6949 ASSERT_TRUE(cert);
6950 MockCertVerifier cert_verifier;
6951 CertVerifyResult verify_result;
6952 verify_result.verified_cert = cert;
6953 verify_result.is_issued_by_known_root = true;
6954 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6955
6956 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
6957 // compliance.
6958 DoNothingCTVerifier ct_verifier;
6959 MockCTPolicyEnforcer ct_policy_enforcer;
6960 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:546961 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:516962
6963 TestNetworkDelegate network_delegate;
6964 // Use a MockHostResolver (which by default maps all hosts to
6965 // 127.0.0.1).
6966 MockHostResolver host_resolver;
6967 TestURLRequestContext context(true);
6968 context.set_host_resolver(&host_resolver);
6969 context.set_transport_security_state(&transport_security_state);
6970 context.set_network_delegate(&network_delegate);
6971 context.set_cert_verifier(&cert_verifier);
6972 context.set_cert_transparency_verifier(&ct_verifier);
6973 context.set_ct_policy_enforcer(&ct_policy_enforcer);
6974 context.Init();
6975
6976 // Now send a request to trigger the header processing.
6977 TestDelegate d;
6978 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6979 std::unique_ptr<URLRequest> request(context.CreateRequest(
6980 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
6981 request->Start();
Wez2a31b222018-06-07 22:07:156982 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:516983
6984 TransportSecurityState::ExpectCTState state;
6985 ASSERT_TRUE(
6986 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
6987 EXPECT_TRUE(state.enforce);
6988 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
6989}
6990
6991// Tests that if multiple Expect CT HTTP headers are sent, they are all
6992// processed.
6993TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
6994 base::test::ScopedFeatureList feature_list;
6995 feature_list.InitAndEnableFeature(
6996 TransportSecurityState::kDynamicExpectCTFeature);
6997
6998 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6999 https_test_server.SetSSLConfig(
7000 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7001 https_test_server.ServeFilesFromSourceDirectory(
7002 base::FilePath(kTestFilePath));
7003 ASSERT_TRUE(https_test_server.Start());
7004
7005 MockExpectCTReporter reporter;
7006 TransportSecurityState transport_security_state;
7007 transport_security_state.SetExpectCTReporter(&reporter);
7008
7009 // Set up a MockCertVerifier to accept the certificate that the server sends.
7010 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7011 ASSERT_TRUE(cert);
7012 MockCertVerifier cert_verifier;
7013 CertVerifyResult verify_result;
7014 verify_result.verified_cert = cert;
7015 verify_result.is_issued_by_known_root = true;
7016 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7017
7018 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7019 // compliance.
7020 DoNothingCTVerifier ct_verifier;
7021 MockCTPolicyEnforcer ct_policy_enforcer;
7022 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547023 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517024
7025 TestNetworkDelegate network_delegate;
7026 // Use a MockHostResolver (which by default maps all hosts to
7027 // 127.0.0.1).
7028 MockHostResolver host_resolver;
7029 TestURLRequestContext context(true);
7030 context.set_host_resolver(&host_resolver);
7031 context.set_transport_security_state(&transport_security_state);
7032 context.set_network_delegate(&network_delegate);
7033 context.set_cert_verifier(&cert_verifier);
7034 context.set_cert_transparency_verifier(&ct_verifier);
7035 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7036 context.Init();
7037
7038 // Now send a request to trigger the header processing.
7039 TestDelegate d;
7040 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7041 std::unique_ptr<URLRequest> request(context.CreateRequest(
7042 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7043 request->Start();
Wez2a31b222018-06-07 22:07:157044 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517045
7046 TransportSecurityState::ExpectCTState state;
7047 ASSERT_TRUE(
7048 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7049 EXPECT_TRUE(state.enforce);
7050 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7051}
7052
mmenkefd9d15c2017-06-29 13:45:547053#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477054
Lily Chenfec60d92019-01-24 01:16:427055#if BUILDFLAG(ENABLE_REPORTING)
7056
7057TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicSuccess) {
7058 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7059 https_test_server.ServeFilesFromSourceDirectory(
7060 base::FilePath(kTestFilePath));
7061 ASSERT_TRUE(https_test_server.Start());
7062 GURL request_url = https_test_server.GetURL("/simple.html");
7063
7064 TestNetworkErrorLoggingService nel_service;
7065 TestURLRequestContext context(true);
7066 context.set_network_error_logging_service(&nel_service);
7067 context.Init();
7068
7069 TestDelegate d;
7070 std::unique_ptr<URLRequest> request(context.CreateRequest(
7071 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7072 request->Start();
7073 d.RunUntilComplete();
7074
7075 ASSERT_EQ(1u, nel_service.errors().size());
7076 const TestNetworkErrorLoggingService::RequestDetails& error =
7077 nel_service.errors()[0];
7078 EXPECT_EQ(request_url, error.uri);
7079 EXPECT_EQ(200, error.status_code);
7080 EXPECT_EQ(OK, error.type);
7081}
7082
7083TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicError) {
7084 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7085 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7086 ASSERT_TRUE(https_test_server.Start());
7087 GURL request_url = https_test_server.GetURL("/close-socket");
7088
7089 TestNetworkErrorLoggingService nel_service;
7090 TestURLRequestContext context(true);
7091 context.set_network_error_logging_service(&nel_service);
7092 context.Init();
7093
7094 TestDelegate d;
7095 std::unique_ptr<URLRequest> request(context.CreateRequest(
7096 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7097 request->Start();
7098 d.RunUntilComplete();
7099
7100 ASSERT_EQ(1u, nel_service.errors().size());
7101 const TestNetworkErrorLoggingService::RequestDetails& error =
7102 nel_service.errors()[0];
7103 EXPECT_EQ(request_url, error.uri);
7104 EXPECT_EQ(0, error.status_code);
7105 EXPECT_EQ(ERR_EMPTY_RESPONSE, error.type);
7106}
7107
7108TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Redirect) {
7109 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7110 https_test_server.ServeFilesFromSourceDirectory(
7111 base::FilePath(kTestFilePath));
7112 ASSERT_TRUE(https_test_server.Start());
7113 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7114 GURL redirect_url = https_test_server.GetURL("/with-headers.html");
7115
7116 TestNetworkErrorLoggingService nel_service;
7117 TestURLRequestContext context(true);
7118 context.set_network_error_logging_service(&nel_service);
7119 context.Init();
7120
7121 TestDelegate d;
7122 std::unique_ptr<URLRequest> request(context.CreateRequest(
7123 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7124 request->Start();
7125 d.RunUntilComplete();
7126
7127 ASSERT_EQ(2u, nel_service.errors().size());
7128 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7129 nel_service.errors()[0];
7130 EXPECT_EQ(request_url, error1.uri);
7131 EXPECT_EQ(302, error1.status_code);
7132 EXPECT_EQ(OK, error1.type);
7133 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7134 nel_service.errors()[1];
7135 EXPECT_EQ(redirect_url, error2.uri);
7136 EXPECT_EQ(200, error2.status_code);
7137 EXPECT_EQ(OK, error2.type);
7138}
7139
7140TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Auth) {
7141 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7142 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7143 ASSERT_TRUE(https_test_server.Start());
7144 GURL request_url = https_test_server.GetURL("/auth-basic");
7145
7146 TestNetworkErrorLoggingService nel_service;
7147 TestURLRequestContext context(true);
7148 context.set_network_error_logging_service(&nel_service);
7149 context.Init();
7150
7151 TestDelegate d;
7152 d.set_credentials(AuthCredentials(kUser, kSecret));
7153 std::unique_ptr<URLRequest> request(context.CreateRequest(
7154 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7155 request->Start();
7156 d.RunUntilComplete();
7157
7158 ASSERT_EQ(2u, nel_service.errors().size());
7159 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7160 nel_service.errors()[0];
7161 EXPECT_EQ(request_url, error1.uri);
7162 EXPECT_EQ(401, error1.status_code);
7163 EXPECT_EQ(OK, error1.type);
7164 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7165 nel_service.errors()[1];
7166 EXPECT_EQ(request_url, error2.uri);
7167 EXPECT_EQ(200, error2.status_code);
7168 EXPECT_EQ(OK, error2.type);
7169}
7170
7171TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Cancel) {
7172 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7173 https_test_server.ServeFilesFromSourceDirectory(
7174 base::FilePath(kTestFilePath));
7175 ASSERT_TRUE(https_test_server.Start());
7176 GURL request_url = https_test_server.GetURL("/simple.html");
7177
7178 TestNetworkErrorLoggingService nel_service;
7179 TestURLRequestContext context(true);
7180 context.set_network_error_logging_service(&nel_service);
7181 context.Init();
7182
7183 TestDelegate d;
7184 d.set_cancel_in_response_started(true);
7185 std::unique_ptr<URLRequest> request(context.CreateRequest(
7186 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7187 request->Start();
7188 d.RunUntilComplete();
7189
7190 ASSERT_EQ(1u, nel_service.errors().size());
7191 const TestNetworkErrorLoggingService::RequestDetails& error =
7192 nel_service.errors()[0];
7193 EXPECT_EQ(request_url, error.uri);
7194 EXPECT_EQ(200, error.status_code);
7195 EXPECT_EQ(OK, error.type);
7196}
7197
7198#endif // BUILDFLAG(ENABLE_REPORTING)
7199
[email protected]316c1e5e2012-09-12 15:17:447200TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557201 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447202
7203 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077204 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557205 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167206 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197207 req->Start();
Wez2a31b222018-06-07 22:07:157208 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447209
7210 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197211 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447212 EXPECT_EQ("text/html", mime_type);
7213
7214 std::string charset;
[email protected]f7022f32014-08-21 16:32:197215 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447216 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197217 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447218}
7219
[email protected]02494ec2014-05-07 15:05:297220TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347221 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347222 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347223 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027224 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347225
7226 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507227 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347228}
7229
brettwa1228ebb2016-10-28 03:51:347230#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297231TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7232 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7233 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457234 FileProtocolHandler file_protocol_handler(
7235 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297236 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7237
7238 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507239 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297240}
7241
[email protected]588614c22013-08-16 00:09:027242TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557243 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447244
7245 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077246 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557247 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167248 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197249 req->Start();
Wez2a31b222018-06-07 22:07:157250 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447251
maksim.sisovb53724b52016-09-16 05:30:507252 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307253
7254 // The redirect should have been rejected before reporting it to the caller.
7255 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447256}
brettwa1228ebb2016-10-28 03:51:347257#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447258
[email protected]588614c22013-08-16 00:09:027259TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557260 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027261
7262 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077263 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557264 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167265 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197266 req->Start();
Wez2a31b222018-06-07 22:07:157267 d.RunUntilComplete();
[email protected]588614c22013-08-16 00:09:027268
maksim.sisovb53724b52016-09-16 05:30:507269 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307270
7271 // The redirect should have been rejected before reporting it to the
7272 // caller. See https://crbug.com/723796
7273 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027274}
7275
davidbend894710b2017-06-06 19:28:307276// Test that redirects to invalid URLs are rejected. See
7277// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447278TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557279 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447280
7281 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077282 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557283 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167284 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197285 req->Start();
Wez2a31b222018-06-07 22:07:157286 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447287
davidbend894710b2017-06-06 19:28:307288 EXPECT_EQ(1, d.response_started_count());
7289 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7290
7291 // The redirect should have been rejected before reporting it to the caller.
7292 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447293}
7294
[email protected]e50efea2014-03-24 18:41:007295// Make sure redirects are cached, despite not reading their bodies.
7296TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557297 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007298 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557299 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007300
7301 {
7302 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077303 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167304 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197305 req->Start();
Wez2a31b222018-06-07 22:07:157306 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507307 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007308 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557309 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007310 }
7311
7312 {
7313 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077314 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167315 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197316 req->Start();
Wez0e717112018-06-18 23:09:227317 d.RunUntilRedirect();
[email protected]e50efea2014-03-24 18:41:007318
7319 EXPECT_EQ(1, d.received_redirect_count());
7320 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197321 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007322
Arthur Sonzognib8465ff72019-01-04 18:44:357323 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7324 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157325 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007326 EXPECT_EQ(1, d.received_redirect_count());
7327 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507328 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557329 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007330 }
7331}
7332
7333// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7334// when the headers are read, since the body won't have been read.
7335TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557336 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007337 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557338 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007339
7340 {
7341 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557342 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007343 default_network_delegate_.set_redirect_on_headers_received_url(
7344 redirect_to_url);
7345
7346 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077347 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167348 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197349 req->Start();
Wez2a31b222018-06-07 22:07:157350 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507351 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007352 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197353 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007354 }
7355
7356 {
7357 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077358 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167359 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197360 req->Start();
Wez2a31b222018-06-07 22:07:157361 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007362
maksim.sisovb53724b52016-09-16 05:30:507363 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197364 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007365 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197366 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007367 }
7368}
7369
[email protected]5f714132014-03-26 10:41:167370// Tests that redirection to an unsafe URL is allowed when it has been marked as
7371// safe.
7372TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557373 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167374
7375 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7376 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7377 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7378
7379 TestDelegate d;
7380 {
Ryan Sleevib8449e02018-07-15 04:31:077381 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167382 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7383 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167384
[email protected]f7022f32014-08-21 16:32:197385 r->Start();
Wez2a31b222018-06-07 22:07:157386 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167387
maksim.sisovb53724b52016-09-16 05:30:507388 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197389 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197390 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167391 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7392 }
7393}
7394
7395// Tests that a redirect to a different unsafe URL is blocked, even after adding
7396// some other URL to the whitelist.
7397TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557398 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167399
7400 GURL unsafe_url("data:text/html,something");
7401 GURL different_unsafe_url("data:text/html,something-else");
7402 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7403 default_network_delegate_.set_allowed_unsafe_redirect_url(
7404 different_unsafe_url);
7405
7406 TestDelegate d;
7407 {
Ryan Sleevib8449e02018-07-15 04:31:077408 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167409 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7410 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167411
[email protected]f7022f32014-08-21 16:32:197412 r->Start();
Wez2a31b222018-06-07 22:07:157413 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167414
maksim.sisovb53724b52016-09-16 05:30:507415 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307416
7417 // The redirect should have been rejected before reporting it to the caller.
7418 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167419 }
7420}
7421
[email protected]5f714132014-03-26 10:41:167422// Redirects from an URL with fragment to an unsafe URL with fragment should
7423// be allowed, and the reference fragment of the target URL should be preserved.
7424TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557425 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167426
tommycli59a63432015-11-06 00:10:557427 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167428 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7429 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7430
7431 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7432 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7433
7434 TestDelegate d;
7435 {
Ryan Sleevib8449e02018-07-15 04:31:077436 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167437 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167438
[email protected]f7022f32014-08-21 16:32:197439 r->Start();
Wez2a31b222018-06-07 22:07:157440 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167441
[email protected]f7022f32014-08-21 16:32:197442 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507443 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197444 EXPECT_EQ(original_url, r->original_url());
7445 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167446 }
7447}
7448
7449// When a delegate has specified a safe redirect URL, but it does not match the
7450// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147451TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557452 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167453
tommycli59a63432015-11-06 00:10:557454 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167455 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557456 GURL redirect_url(http_test_server()->GetURL("/target"));
7457 GURL expected_redirect_url(
7458 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167459
7460 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7461 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7462
7463 TestDelegate d;
7464 {
Ryan Sleevib8449e02018-07-15 04:31:077465 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167466 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167467
[email protected]f7022f32014-08-21 16:32:197468 r->Start();
Wez2a31b222018-06-07 22:07:157469 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167470
[email protected]f7022f32014-08-21 16:32:197471 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507472 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197473 EXPECT_EQ(original_url, r->original_url());
7474 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167475 }
7476}
7477
[email protected]f878230e2014-04-03 15:36:147478// When a delegate has specified a safe redirect URL, assume that the redirect
7479// URL should not be changed. In particular, the reference fragment should not
7480// be modified.
7481TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557482 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147483
tommycli59a63432015-11-06 00:10:557484 GURL original_url(
7485 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147486 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7487
7488 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7489 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7490
7491 TestDelegate d;
7492 {
Ryan Sleevib8449e02018-07-15 04:31:077493 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167494 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147495
[email protected]f7022f32014-08-21 16:32:197496 r->Start();
Wez2a31b222018-06-07 22:07:157497 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147498
[email protected]f7022f32014-08-21 16:32:197499 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507500 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197501 EXPECT_EQ(original_url, r->original_url());
7502 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147503 }
7504}
7505
7506// When a URLRequestRedirectJob is created, the redirection must be followed and
7507// the reference fragment of the target URL must not be modified.
7508TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557509 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147510
tommycli59a63432015-11-06 00:10:557511 GURL original_url(
7512 http_test_server()->GetURL("/original#should-not-be-appended"));
7513 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147514
7515 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077516 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167517 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147518
danakj8522a25b2016-04-16 00:17:367519 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197520 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427521 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7522 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:147523
[email protected]f7022f32014-08-21 16:32:197524 r->Start();
Wez2a31b222018-06-07 22:07:157525 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147526
maksim.sisovb53724b52016-09-16 05:30:507527 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197528 EXPECT_EQ(original_url, r->original_url());
7529 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147530}
7531
lizeb5120f6dc2016-02-19 09:29:447532TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
7533 ASSERT_TRUE(http_test_server()->Start());
7534
7535 const std::string referrer("foobar://totally.legit.referrer");
7536 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077537 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167538 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7539 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:447540 req->SetReferrer(referrer);
7541 req->Start();
Wez2a31b222018-06-07 22:07:157542 d.RunUntilComplete();
lizeb5120f6dc2016-02-19 09:29:447543
7544 EXPECT_EQ(std::string("None"), d.data_received());
7545}
7546
[email protected]316c1e5e2012-09-12 15:17:447547TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:557548 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447549
7550 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077551 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167552 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7553 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197554 req->SetReferrer("http://user:[email protected]/");
7555 req->Start();
Wez2a31b222018-06-07 22:07:157556 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447557
7558 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
7559}
7560
[email protected]99ecf6e2013-04-10 22:46:137561TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:557562 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137563
7564 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077565 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167566 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7567 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197568 req->SetReferrer("http://foo.com/test#fragment");
7569 req->Start();
Wez2a31b222018-06-07 22:07:157570 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:137571
7572 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
7573}
7574
7575TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:557576 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137577
7578 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077579 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167580 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7581 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197582 req->SetReferrer("http://foo.com/test#fragment");
7583 req->SetReferrer("");
7584 req->Start();
Wez2a31b222018-06-07 22:07:157585 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:137586
7587 EXPECT_EQ(std::string("None"), d.data_received());
7588}
7589
[email protected]316c1e5e2012-09-12 15:17:447590TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:557591 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447592
7593 TestDelegate d;
7594 {
7595 d.set_cancel_in_received_redirect(true);
Ryan Sleevib8449e02018-07-15 04:31:077596 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167597 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7598 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197599 req->Start();
Wez2a31b222018-06-07 22:07:157600 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447601
7602 EXPECT_EQ(1, d.response_started_count());
7603 EXPECT_EQ(0, d.bytes_received());
7604 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507605 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447606 }
7607}
7608
7609TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:557610 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447611
7612 TestDelegate d;
7613 {
tommycli59a63432015-11-06 00:10:557614 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:077615 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167616 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047617
[email protected]f7022f32014-08-21 16:32:197618 req->Start();
Wez0e717112018-06-18 23:09:227619 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:447620
7621 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:237622 EXPECT_TRUE(d.have_full_request_headers());
7623 CheckFullRequestHeaders(d.full_request_headers(), test_url);
7624 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:447625
Arthur Sonzognib8465ff72019-01-04 18:44:357626 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7627 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157628 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447629
7630 EXPECT_EQ(1, d.response_started_count());
7631 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507632 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447633
[email protected]6cdfd7f2013-02-08 20:40:157634 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:197635 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477636 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:447637 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7638
7639 std::string contents;
[email protected]82f84b92013-08-30 18:23:507640 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:447641 EXPECT_EQ(contents, d.data_received());
7642 }
7643}
7644
[email protected]79e1fd62013-06-20 06:50:047645TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:557646 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:047647
7648 TestDelegate d;
7649 {
tommycli59a63432015-11-06 00:10:557650 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:077651 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167652 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047653
7654 EXPECT_FALSE(d.have_full_request_headers());
7655
[email protected]f7022f32014-08-21 16:32:197656 req->Start();
Wez0e717112018-06-18 23:09:227657 d.RunUntilRedirect();
[email protected]79e1fd62013-06-20 06:50:047658
7659 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:047660
Arthur Sonzognib8465ff72019-01-04 18:44:357661 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7662 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157663 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:047664
tommycli59a63432015-11-06 00:10:557665 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:047666 EXPECT_EQ(1, d.response_started_count());
7667 EXPECT_TRUE(d.have_full_request_headers());
7668 CheckFullRequestHeaders(d.full_request_headers(), target_url);
7669 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507670 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:047671
7672 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:197673 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477674 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:047675 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7676
7677 std::string contents;
[email protected]82f84b92013-08-30 18:23:507678 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:047679 EXPECT_EQ(contents, d.data_received());
7680 }
7681}
7682
Arthur Sonzognib8465ff72019-01-04 18:44:357683TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedHeaders) {
Chong Zhang7607f1f2018-06-01 20:52:207684 ASSERT_TRUE(http_test_server()->Start());
7685
7686 TestDelegate d;
7687 {
Chong Zhang7607f1f2018-06-01 20:52:207688 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:077689 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Chong Zhang7607f1f2018-06-01 20:52:207690 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7691
7692 // Set initial headers for the request.
7693 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
7694 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
7695
7696 req->Start();
Wez0e717112018-06-18 23:09:227697 d.RunUntilRedirect();
Chong Zhang7607f1f2018-06-01 20:52:207698
7699 // Initial request should only have initial headers.
7700 EXPECT_EQ(1, d.received_redirect_count());
7701 EXPECT_TRUE(d.have_full_request_headers());
7702 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
7703 std::string sent_value;
7704 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
7705 EXPECT_EQ("Value1", sent_value);
7706 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
7707 EXPECT_EQ("Value2", sent_value);
7708 EXPECT_FALSE(sent_headers1.GetHeader("Header3", &sent_value));
7709 d.ClearFullRequestHeaders();
7710
7711 // Overwrite Header2 and add Header3.
Arthur Sonzognib8465ff72019-01-04 18:44:357712 net::HttpRequestHeaders modified_headers;
7713 modified_headers.SetHeader("Header2", "");
7714 modified_headers.SetHeader("Header3", "Value3");
Chong Zhang7607f1f2018-06-01 20:52:207715
Arthur Sonzognib8465ff72019-01-04 18:44:357716 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7717 modified_headers);
Wez2a31b222018-06-07 22:07:157718 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:207719
7720 EXPECT_EQ(1, d.response_started_count());
7721 EXPECT_FALSE(d.received_data_before_response());
7722 EXPECT_EQ(OK, d.request_status());
7723
7724 // Redirected request should also have modified headers.
7725 EXPECT_TRUE(d.have_full_request_headers());
7726 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
7727 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
7728 EXPECT_EQ("Value1", sent_value);
7729 EXPECT_TRUE(sent_headers2.GetHeader("Header2", &sent_value));
7730 EXPECT_EQ("", sent_value);
7731 EXPECT_TRUE(sent_headers2.GetHeader("Header3", &sent_value));
7732 EXPECT_EQ("Value3", sent_value);
7733 }
7734}
7735
Arthur Sonzognib8465ff72019-01-04 18:44:357736TEST_F(URLRequestTestHTTP, DeferredRedirect_RemovedHeaders) {
7737 ASSERT_TRUE(http_test_server()->Start());
7738
7739 TestDelegate d;
7740 {
7741 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
7742 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
7743 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7744
7745 // Set initial headers for the request.
7746 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
7747 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
7748
7749 req->Start();
7750 d.RunUntilRedirect();
7751
7752 // Initial request should have initial headers.
7753 EXPECT_EQ(1, d.received_redirect_count());
7754 EXPECT_TRUE(d.have_full_request_headers());
7755 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
7756 std::string sent_value;
7757 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
7758 EXPECT_EQ("Value1", sent_value);
7759 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
7760 EXPECT_EQ("Value2", sent_value);
7761 d.ClearFullRequestHeaders();
7762
7763 // Keep Header1 and remove Header2.
7764 std::vector<std::string> removed_headers({"Header2"});
7765 req->FollowDeferredRedirect(removed_headers,
7766 base::nullopt /* modified_headers */);
7767 d.RunUntilComplete();
7768
7769 EXPECT_EQ(1, d.response_started_count());
7770 EXPECT_FALSE(d.received_data_before_response());
7771 EXPECT_EQ(OK, d.request_status());
7772
7773 // Redirected request should also have
7774 EXPECT_TRUE(d.have_full_request_headers());
7775 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
7776 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
7777 EXPECT_EQ("Value1", sent_value);
7778 EXPECT_FALSE(sent_headers2.GetHeader("Header2", &sent_value));
7779 }
7780}
7781
[email protected]316c1e5e2012-09-12 15:17:447782TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:557783 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447784
7785 TestDelegate d;
7786 {
Ryan Sleevib8449e02018-07-15 04:31:077787 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167788 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7789 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197790 req->Start();
Wez0e717112018-06-18 23:09:227791 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:447792
7793 EXPECT_EQ(1, d.received_redirect_count());
7794
[email protected]f7022f32014-08-21 16:32:197795 req->Cancel();
Wez2a31b222018-06-07 22:07:157796 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447797
7798 EXPECT_EQ(1, d.response_started_count());
7799 EXPECT_EQ(0, d.bytes_received());
7800 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507801 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447802 }
7803}
7804
7805TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:557806 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447807
[email protected]3b23a222013-05-15 21:33:257808 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:447809 {
7810 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077811 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557812 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167813 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447814 HttpRequestHeaders headers;
7815 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197816 req->SetExtraRequestHeaders(headers);
7817 req->Start();
Wez2a31b222018-06-07 22:07:157818 d.RunUntilComplete();
[email protected]3b23a222013-05-15 21:33:257819
7820 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197821 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257822 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447823 }
7824
[email protected]3b23a222013-05-15 21:33:257825 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:447826 {
7827 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077828 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557829 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167830 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447831 HttpRequestHeaders headers;
7832 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197833 req->SetExtraRequestHeaders(headers);
7834 req->Start();
Wez2a31b222018-06-07 22:07:157835 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447836
[email protected]f7022f32014-08-21 16:32:197837 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257838
7839 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197840 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257841 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:447842 }
7843
[email protected]3b23a222013-05-15 21:33:257844 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:447845 {
7846 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077847 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557848 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167849 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447850 HttpRequestHeaders headers;
7851 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:197852 req->SetExtraRequestHeaders(headers);
7853 req->Start();
Wez2a31b222018-06-07 22:07:157854 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447855
[email protected]f7022f32014-08-21 16:32:197856 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257857
7858 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197859 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257860 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447861 }
7862}
7863
7864TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:557865 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447866
7867 // populate the cache
7868 {
7869 TestDelegate d;
7870 d.set_credentials(AuthCredentials(kUser, kSecret));
7871
Ryan Sleevib8449e02018-07-15 04:31:077872 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167873 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7874 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197875 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447876
Wez2a31b222018-06-07 22:07:157877 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447878
7879 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7880 }
7881
7882 // repeat request with end-to-end validation. since auth-basic results in a
7883 // cachable page, we expect this test to result in a 304. in which case, the
7884 // response should be fetched from the cache.
7885 {
7886 TestDelegate d;
7887 d.set_credentials(AuthCredentials(kUser, kSecret));
7888
Ryan Sleevib8449e02018-07-15 04:31:077889 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167890 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7891 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197892 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7893 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447894
Wez2a31b222018-06-07 22:07:157895 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447896
7897 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7898
7899 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197900 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:447901 }
7902}
7903
7904// Check that Set-Cookie headers in 401 responses are respected.
7905// http://crbug.com/6450
7906TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:557907 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447908
7909 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:557910 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:447911
7912 // Request a page that will give a 401 containing a Set-Cookie header.
7913 // Verify that when the transaction is restarted, it includes the new cookie.
7914 {
[email protected]ceefd7fd2012-11-29 00:36:247915 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447916 TestURLRequestContext context(true);
7917 context.set_network_delegate(&network_delegate);
7918 context.Init();
7919
7920 TestDelegate d;
7921 d.set_credentials(AuthCredentials(kUser, kSecret));
7922
danakj8522a25b2016-04-16 00:17:367923 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:167924 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
7925 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197926 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447927
Wez2a31b222018-06-07 22:07:157928 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447929
7930 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7931
7932 // Make sure we sent the cookie in the restarted transaction.
7933 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7934 != std::string::npos);
7935 }
7936
7937 // Same test as above, except this time the restart is initiated earlier
7938 // (without user intervention since identity is embedded in the URL).
7939 {
[email protected]ceefd7fd2012-11-29 00:36:247940 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447941 TestURLRequestContext context(true);
7942 context.set_network_delegate(&network_delegate);
7943 context.Init();
7944
7945 TestDelegate d;
7946
7947 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:187948 replacements.SetUsernameStr("user2");
7949 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:447950 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
7951
rhalavatib7bd7c792017-04-27 05:25:167952 std::unique_ptr<URLRequest> r(context.CreateRequest(
7953 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197954 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447955
Wez2a31b222018-06-07 22:07:157956 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447957
7958 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
7959
7960 // Make sure we sent the cookie in the restarted transaction.
7961 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7962 != std::string::npos);
7963 }
7964}
7965
[email protected]58e32bb2013-01-21 18:23:257966// Tests that load timing works as expected with auth and the cache.
7967TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:557968 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:257969
7970 // populate the cache
7971 {
7972 TestDelegate d;
7973 d.set_credentials(AuthCredentials(kUser, kSecret));
7974
Ryan Sleevib8449e02018-07-15 04:31:077975 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167976 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7977 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197978 r->Start();
[email protected]58e32bb2013-01-21 18:23:257979
Wez2a31b222018-06-07 22:07:157980 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:257981
7982 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7983
7984 LoadTimingInfo load_timing_info_before_auth;
7985 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7986 &load_timing_info_before_auth));
7987 TestLoadTimingNotReused(load_timing_info_before_auth,
7988 CONNECT_TIMING_HAS_DNS_TIMES);
7989
7990 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197991 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257992 // The test server does not support keep alive sockets, so the second
7993 // request with auth should use a new socket.
7994 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7995 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7996 load_timing_info.socket_log_id);
7997 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7998 load_timing_info.connect_timing.connect_start);
7999 }
8000
[email protected]3b23a222013-05-15 21:33:258001 // Repeat request with end-to-end validation. Since auth-basic results in a
8002 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258003 // response should be fetched from the cache.
8004 {
8005 TestDelegate d;
8006 d.set_credentials(AuthCredentials(kUser, kSecret));
8007
Ryan Sleevib8449e02018-07-15 04:31:078008 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168009 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8010 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198011 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8012 r->Start();
[email protected]58e32bb2013-01-21 18:23:258013
Wez2a31b222018-06-07 22:07:158014 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258015
8016 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8017
8018 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198019 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258020
[email protected]3b23a222013-05-15 21:33:258021 // Since there was a request that went over the wire, the load timing
8022 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258023 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198024 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258025 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258026 }
8027}
8028
[email protected]316c1e5e2012-09-12 15:17:448029// In this test, we do a POST which the server will 302 redirect.
8030// The subsequent transaction should use GET, and should not send the
8031// Content-Type header.
8032// http://code.google.com/p/chromium/issues/detail?id=843
8033TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558034 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448035
8036 const char kData[] = "hello world";
8037
8038 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078039 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168040 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8041 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198042 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078043 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448044
8045 // Set headers (some of which are specific to the POST).
8046 HttpRequestHeaders headers;
Yeol45b9e0a2018-07-27 02:03:298047 headers.SetHeader("Content-Type",
8048 "multipart/form-data;"
8049 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ");
8050 headers.SetHeader("Accept",
8051 "text/xml,application/xml,application/xhtml+xml,"
8052 "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
8053 headers.SetHeader("Accept-Language", "en-US,en");
8054 headers.SetHeader("Accept-Charset", "ISO-8859-1,*,utf-8");
8055 headers.SetHeader("Content-Length", "11");
8056 headers.SetHeader("Origin", "http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198057 req->SetExtraRequestHeaders(headers);
8058 req->Start();
Wez2a31b222018-06-07 22:07:158059 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448060
8061 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198062 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448063 EXPECT_EQ("text/html", mime_type);
8064
8065 const std::string& data = d.data_received();
8066
8067 // Check that the post-specific headers were stripped:
8068 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8069 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498070 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448071
8072 // These extra request headers should not have been stripped.
8073 EXPECT_TRUE(ContainsString(data, "Accept:"));
8074 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8075 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8076}
8077
jww5fe460ff2015-03-28 00:22:518078// The following tests check that we handle mutating the request for HTTP
8079// redirects as expected.
8080// See https://crbug.com/56373, https://crbug.com/102130, and
8081// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448082
8083TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558084 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448085
tommycli59a63432015-11-06 00:10:558086 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518087 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558088 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448089
8090 HTTPRedirectMethodTest(url, "POST", "GET", true);
8091 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8092 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518093
8094 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8095 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498096 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8097 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8098 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408099 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8100 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448101}
8102
8103TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558104 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448105
tommycli59a63432015-11-06 00:10:558106 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518107 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558108 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448109
8110 HTTPRedirectMethodTest(url, "POST", "GET", true);
8111 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8112 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518113
8114 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8115 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498116 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8117 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8118 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408119 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8120 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448121}
8122
8123TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558124 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448125
tommycli59a63432015-11-06 00:10:558126 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518127 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558128 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448129
8130 HTTPRedirectMethodTest(url, "POST", "GET", true);
8131 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8132 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518133
Alex Clarke1e08882b32017-10-06 14:22:408134 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8135 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8136 std::string());
8137 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8138 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8139 std::string());
jww5fe460ff2015-03-28 00:22:518140 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8141 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408142 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8143 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8144 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8145 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8146 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498147 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8148 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8149 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408150 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
8151 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:448152}
8153
8154TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558155 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448156
tommycli59a63432015-11-06 00:10:558157 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518158 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558159 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448160
8161 HTTPRedirectMethodTest(url, "POST", "POST", true);
8162 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8163 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518164
8165 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8166 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8167 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8168 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408169 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8170 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448171}
8172
[email protected]0a17aab32014-04-24 03:32:378173TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558174 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378175
tommycli59a63432015-11-06 00:10:558176 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518177 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558178 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378179
8180 HTTPRedirectMethodTest(url, "POST", "POST", true);
8181 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8182 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518183
8184 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8185 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8186 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8187 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408188 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8189 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:378190}
8191
8192// Make sure that 308 responses without bodies are not treated as redirects.
8193// Certain legacy apis that pre-date the response code expect this behavior
8194// (Like Google Drive).
8195TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558196 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378197
8198 TestDelegate d;
tommycli59a63432015-11-06 00:10:558199 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378200
Ryan Sleevib8449e02018-07-15 04:31:078201 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168202 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378203
[email protected]f7022f32014-08-21 16:32:198204 request->Start();
Wez2a31b222018-06-07 22:07:158205 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:508206 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378207 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198208 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378209 EXPECT_EQ("This is not a redirect.", d.data_received());
8210}
8211
[email protected]f878230e2014-04-03 15:36:148212TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558213 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148214
tommycli59a63432015-11-06 00:10:558215 GURL original_url(
8216 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8217 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148218
8219 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148220 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8221 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148222
Josh Karlinbe37f912018-12-07 01:05:148223 r->Start();
8224 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148225
Josh Karlinbe37f912018-12-07 01:05:148226 EXPECT_EQ(2U, r->url_chain().size());
8227 EXPECT_EQ(OK, d.request_status());
8228 EXPECT_EQ(original_url, r->original_url());
8229 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148230}
8231
[email protected]cba24642014-08-15 20:49:598232TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558233 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598234
tommycli59a63432015-11-06 00:10:558235 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598236 GURL first_party_url("http://example.com");
8237
8238 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148239 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8240 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8241 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598242
Josh Karlinbe37f912018-12-07 01:05:148243 r->Start();
8244 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598245
Josh Karlinbe37f912018-12-07 01:05:148246 EXPECT_EQ(2U, r->url_chain().size());
8247 EXPECT_EQ(OK, d.request_status());
8248 EXPECT_EQ(first_party_url, r->site_for_cookies());
8249}
8250
8251TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameOrigin) {
8252 ASSERT_TRUE(http_test_server()->Start());
8253
8254 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8255 url::Origin top_frame_origin =
8256 url::Origin::Create(GURL("http://example.com"));
8257 TestDelegate d;
8258
8259 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8260 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8261 r->set_top_frame_origin(top_frame_origin);
8262
8263 r->Start();
8264 d.RunUntilComplete();
8265
8266 EXPECT_EQ(2U, r->url_chain().size());
8267 EXPECT_EQ(OK, d.request_status());
8268 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
8269}
8270
8271TEST_F(URLRequestTestHTTP, RedirectPreserveUnsetTopFrameOrigin) {
8272 ASSERT_TRUE(http_test_server()->Start());
8273
8274 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8275 TestDelegate d;
8276
8277 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8278 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8279 // Since we're not setting a top frame origin, we wouldn't expect one after
8280 // the redirect.
8281 r->Start();
8282 d.RunUntilComplete();
8283
8284 EXPECT_EQ(2U, r->url_chain().size());
8285 EXPECT_EQ(OK, d.request_status());
8286 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:598287}
8288
Josh Karlinf3caee1642018-12-10 22:54:278289TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameURL) {
8290 ASSERT_TRUE(http_test_server()->Start());
8291
8292 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8293 url::Origin top_frame_origin =
8294 url::Origin::Create(GURL("http://example.com"));
8295 TestDelegate d;
8296 {
8297 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8298 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8299 r->set_top_frame_origin(top_frame_origin);
8300
8301 r->Start();
8302 d.RunUntilComplete();
8303
8304 EXPECT_EQ(2U, r->url_chain().size());
8305 EXPECT_EQ(OK, d.request_status());
8306 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
8307 }
8308}
8309
[email protected]cba24642014-08-15 20:49:598310TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558311 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598312
tommycli59a63432015-11-06 00:10:558313 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598314 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558315 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598316
8317 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148318
Ryan Sleevib8449e02018-07-15 04:31:078319 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168320 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468321 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198322 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598323 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8324
[email protected]f7022f32014-08-21 16:32:198325 r->Start();
Wez2a31b222018-06-07 22:07:158326 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598327
[email protected]f7022f32014-08-21 16:32:198328 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508329 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468330 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
Josh Karlinbe37f912018-12-07 01:05:148331}
8332
8333TEST_F(URLRequestTestHTTP, RedirectUpdateTopFrameOrigin) {
8334 ASSERT_TRUE(http_test_server()->Start());
8335
8336 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8337 url::Origin original_top_frame_origin =
8338 url::Origin::Create(GURL("http://example.com"));
8339 url::Origin expected_top_frame_origin =
8340 url::Origin::Create(GURL(http_test_server()->GetURL("/echo")));
8341
8342 TestDelegate d;
8343
8344 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8345 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8346 r->set_top_frame_origin(original_top_frame_origin);
8347 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8348
8349 r->Start();
8350 d.RunUntilComplete();
8351
8352 EXPECT_EQ(2U, r->url_chain().size());
8353 EXPECT_EQ(OK, d.request_status());
8354 EXPECT_EQ(expected_top_frame_origin, *r->top_frame_origin());
8355}
8356
8357TEST_F(URLRequestTestHTTP, RedirectIgnoreUnsetTopFrameOrigin) {
8358 ASSERT_TRUE(http_test_server()->Start());
8359
8360 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8361 TestDelegate d;
8362
8363 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8364 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8365 // Since we're not setting a top frame origin, we wouldn't expect one after
8366 // the redirect.
8367 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8368
8369 r->Start();
8370 d.RunUntilComplete();
8371
8372 EXPECT_EQ(2U, r->url_chain().size());
8373 EXPECT_EQ(OK, d.request_status());
8374 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:598375}
8376
[email protected]316c1e5e2012-09-12 15:17:448377TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558378 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448379
8380 const char kData[] = "hello world";
8381
8382 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078383 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168384 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8385 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198386 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078387 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448388 HttpRequestHeaders headers;
8389 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:248390 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198391 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448392
danakj8522a25b2016-04-16 00:17:368393 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558394 req.get(), &default_network_delegate_,
8395 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428396 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8397 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448398
[email protected]f7022f32014-08-21 16:32:198399 req->Start();
Wez2a31b222018-06-07 22:07:158400 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198401 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:448402}
8403
8404TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:558405 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448406
8407 const char kData[] = "hello world";
8408
8409 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078410 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168411 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8412 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198413 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078414 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448415 HttpRequestHeaders headers;
8416 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:248417 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198418 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448419
danakj8522a25b2016-04-16 00:17:368420 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558421 req.get(), &default_network_delegate_,
8422 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:098423 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:428424 "Very Good Reason"));
8425 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448426
[email protected]f7022f32014-08-21 16:32:198427 req->Start();
Wez2a31b222018-06-07 22:07:158428 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198429 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:448430 EXPECT_EQ(kData, d.data_received());
8431}
8432
8433// Check that default A-L header is sent.
8434TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558435 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448436
[email protected]8790210c2013-12-02 05:29:538437 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:248438 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448439 TestURLRequestContext context(true);
8440 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:438441 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448442 context.Init();
8443
8444 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368445 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558446 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168447 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198448 req->Start();
Wez2a31b222018-06-07 22:07:158449 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448450 EXPECT_EQ("en", d.data_received());
8451}
8452
8453// Check that an empty A-L header is not sent. http://crbug.com/77365.
8454TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558455 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448456
[email protected]8790210c2013-12-02 05:29:538457 std::string empty_string; // Avoid most vexing parse on line below.
8458 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:248459 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448460 TestURLRequestContext context(true);
8461 context.set_network_delegate(&network_delegate);
8462 context.Init();
8463 // We override the language after initialization because empty entries
8464 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:438465 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448466
8467 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368468 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558469 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168470 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198471 req->Start();
Wez2a31b222018-06-07 22:07:158472 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448473 EXPECT_EQ("None", d.data_received());
8474}
8475
8476// Check that if request overrides the A-L header, the default is not appended.
8477// See http://crbug.com/20894
8478TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558479 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448480
8481 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078482 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558483 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168484 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448485 HttpRequestHeaders headers;
8486 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:198487 req->SetExtraRequestHeaders(headers);
8488 req->Start();
Wez2a31b222018-06-07 22:07:158489 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448490 EXPECT_EQ(std::string("ru"), d.data_received());
8491}
8492
8493// Check that default A-E header is sent.
8494TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558495 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448496
8497 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078498 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558499 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168500 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448501 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:198502 req->SetExtraRequestHeaders(headers);
8503 req->Start();
Wez2a31b222018-06-07 22:07:158504 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448505 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
8506}
8507
8508// Check that if request overrides the A-E header, the default is not appended.
8509// See http://crbug.com/47381
8510TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558511 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448512
8513 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078514 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558515 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168516 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448517 HttpRequestHeaders headers;
8518 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:198519 req->SetExtraRequestHeaders(headers);
8520 req->Start();
Wez2a31b222018-06-07 22:07:158521 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448522 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
8523 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
8524}
8525
[email protected]84f05432013-03-15 01:00:128526// Check that setting the A-C header sends the proper header.
8527TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:558528 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448529
8530 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078531 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558532 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:168533 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448534 HttpRequestHeaders headers;
8535 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:198536 req->SetExtraRequestHeaders(headers);
8537 req->Start();
Wez2a31b222018-06-07 22:07:158538 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448539 EXPECT_EQ(std::string("koi-8r"), d.data_received());
8540}
8541
8542// Check that default User-Agent header is sent.
8543TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:558544 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448545
8546 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078547 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558548 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168549 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198550 req->Start();
Wez2a31b222018-06-07 22:07:158551 d.RunUntilComplete();
Ryan Sleevib8449e02018-07-15 04:31:078552 EXPECT_EQ(default_context().http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:378553 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448554}
8555
8556// Check that if request overrides the User-Agent header,
8557// the default is not appended.
marqf14fff8d2015-12-02 15:52:298558// TODO(crbug.com/564656) This test is flaky on iOS.
8559#if defined(OS_IOS)
8560#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
8561#else
8562#define MAYBE_OverrideUserAgent OverrideUserAgent
8563#endif
8564TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:558565 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448566
8567 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078568 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558569 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168570 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448571 HttpRequestHeaders headers;
8572 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:198573 req->SetExtraRequestHeaders(headers);
8574 req->Start();
Wez2a31b222018-06-07 22:07:158575 d.RunUntilComplete();
[email protected]cd6f2522014-01-16 18:27:358576 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448577}
8578
[email protected]ee4c30d2012-11-07 15:08:438579// Check that a NULL HttpUserAgentSettings causes the corresponding empty
8580// User-Agent header to be sent but does not send the Accept-Language and
8581// Accept-Charset headers.
8582TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:558583 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:438584
[email protected]ceefd7fd2012-11-29 00:36:248585 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:438586 TestURLRequestContext context(true);
8587 context.set_network_delegate(&network_delegate);
8588 context.Init();
8589 // We override the HttpUserAgentSettings after initialization because empty
8590 // entries get overridden by Init().
8591 context.set_http_user_agent_settings(NULL);
8592
8593 struct {
8594 const char* request;
8595 const char* expected_response;
tommycli59a63432015-11-06 00:10:558596 } tests[] = {{"/echoheader?Accept-Language", "None"},
8597 {"/echoheader?Accept-Charset", "None"},
8598 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:438599
Avi Drissman4365a4782018-12-28 19:26:248600 for (size_t i = 0; i < base::size(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:438601 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368602 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168603 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
8604 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198605 req->Start();
Wez2a31b222018-06-07 22:07:158606 d.RunUntilComplete();
[email protected]ee4c30d2012-11-07 15:08:438607 EXPECT_EQ(tests[i].expected_response, d.data_received())
8608 << " Request = \"" << tests[i].request << "\"";
8609 }
8610}
8611
[email protected]5033ab82013-03-22 20:17:468612// Make sure that URLRequest passes on its priority updates to
8613// newly-created jobs after the first one.
8614TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:558615 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:468616
8617 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078618 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168619 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8620 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198621 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:468622
danakj8522a25b2016-04-16 00:17:368623 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558624 req.get(), &default_network_delegate_,
8625 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428626 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8627 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:468628
[email protected]f7022f32014-08-21 16:32:198629 req->SetPriority(LOW);
8630 req->Start();
8631 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:468632
mmenkeed0498b2015-12-08 23:20:428633 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:368634 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:428635 req.get(), &default_network_delegate_, &job_priority));
8636 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:468637
8638 // Should trigger |job| to be started.
Wez2a31b222018-06-07 22:07:158639 d.RunUntilComplete();
mmenkeed0498b2015-12-08 23:20:428640 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:468641}
8642
[email protected]80abdad2014-03-15 00:20:548643// Check that creating a network request while entering/exiting suspend mode
8644// fails as it should. This is the only case where an HttpTransactionFactory
8645// does not return an HttpTransaction.
8646TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
8647 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:368648 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
Ryan Sleevib8449e02018-07-15 04:31:078649 default_context().http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:548650 network_layer->OnSuspend();
8651
dchengc7eeda422015-12-26 03:56:488652 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:038653 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:278654 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:548655
8656 TestURLRequestContext context(true);
8657 context.set_http_transaction_factory(&http_cache);
8658 context.Init();
8659
8660 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368661 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:168662 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
8663 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198664 req->Start();
Wez2a31b222018-06-07 22:07:158665 d.RunUntilComplete();
[email protected]80abdad2014-03-15 00:20:548666
8667 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:508668 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:548669}
8670
mmenke2281f3762015-11-02 20:38:178671namespace {
[email protected]80abdad2014-03-15 00:20:548672
mmenke2281f3762015-11-02 20:38:178673// HttpTransactionFactory that synchronously fails to create transactions.
8674class FailingHttpTransactionFactory : public HttpTransactionFactory {
8675 public:
8676 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
8677 : network_session_(network_session) {}
8678
Chris Watkins7a41d3552017-12-01 02:13:278679 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:178680
8681 // HttpTransactionFactory methods:
8682 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:368683 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:178684 return ERR_FAILED;
8685 }
8686
8687 HttpCache* GetCache() override { return nullptr; }
8688
8689 HttpNetworkSession* GetSession() override { return network_session_; }
8690
8691 private:
8692 HttpNetworkSession* network_session_;
8693
8694 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
8695};
8696
8697} // namespace
8698
8699// Check that when a request that fails to create an HttpTransaction can be
8700// cancelled while the failure notification is pending, and doesn't send two
8701// failure notifications.
8702//
8703// This currently only happens when in suspend mode and there's no cache, but
8704// just use a special HttpTransactionFactory, to avoid depending on those
8705// behaviors.
8706TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
8707 FailingHttpTransactionFactory http_transaction_factory(
Ryan Sleevib8449e02018-07-15 04:31:078708 default_context().http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:548709 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:178710 context.set_http_transaction_factory(&http_transaction_factory);
8711 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:548712 context.Init();
8713
8714 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368715 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:168716 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
8717 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:178718 // Don't send cookies (Collecting cookies is asynchronous, and need request to
8719 // try to create an HttpNetworkTransaction synchronously on start).
8720 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:198721 req->Start();
mmenke2281f3762015-11-02 20:38:178722 req->Cancel();
Wez2a31b222018-06-07 22:07:158723 d.RunUntilComplete();
mmenke2281f3762015-11-02 20:38:178724 // Run pending error task, if there is one.
8725 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:548726
8727 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:178728 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:508729 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:178730
8731 // NetworkDelegate should see the cancellation, but not the error.
8732 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
8733 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:548734}
8735
ttuttlec0c828492015-05-15 01:25:558736TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:558737 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558738
8739 TestDelegate d;
tommycli59a63432015-11-06 00:10:558740 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:078741 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168742 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:558743
8744 req->Start();
Wez2a31b222018-06-07 22:07:158745 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:558746
8747 EXPECT_TRUE(req->response_info().network_accessed);
8748}
8749
8750TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:558751 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558752
8753 // Populate the cache.
8754 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078755 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168756 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
8757 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:558758 req->Start();
Wez2a31b222018-06-07 22:07:158759 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:558760
maksim.sisovb53724b52016-09-16 05:30:508761 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:558762 EXPECT_TRUE(req->response_info().network_accessed);
8763 EXPECT_FALSE(req->response_info().was_cached);
8764
Ryan Sleevib8449e02018-07-15 04:31:078765 req = default_context().CreateRequest(
8766 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
8767 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:558768 req->Start();
Wez2a31b222018-06-07 22:07:158769 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:558770
maksim.sisovb53724b52016-09-16 05:30:508771 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:558772 EXPECT_FALSE(req->response_info().network_accessed);
8773 EXPECT_TRUE(req->response_info().was_cached);
8774}
8775
8776TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:558777 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558778
8779 TestDelegate d;
tommycli59a63432015-11-06 00:10:558780 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:078781 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168782 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:338783 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:558784
8785 req->Start();
Wez2a31b222018-06-07 22:07:158786 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:558787
8788 EXPECT_FALSE(req->response_info().network_accessed);
8789}
8790
rdsmithbf8c3c12016-11-18 18:16:248791// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:088792// correctly in the absence of contention.
8793TEST_F(URLRequestTestHTTP, ThrottledPriority) {
8794 ASSERT_TRUE(http_test_server()->Start());
8795
8796 TestDelegate d;
8797 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:078798 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168799 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:088800 req->Start();
Wez2a31b222018-06-07 22:07:158801 d.RunUntilComplete();
rdsmith5eb6fbc2016-10-21 17:36:088802
8803 EXPECT_TRUE(req->status().is_success());
8804}
8805
ricea3a1c71f2016-06-17 10:05:268806TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
8807 ASSERT_TRUE(http_test_server()->Start());
8808
8809 TestDelegate d;
8810 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168811 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
8812 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:268813 req->Start();
Wez2a31b222018-06-07 22:07:158814 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:268815
8816 EXPECT_EQ(5, req->GetRawBodyBytes());
8817}
8818
8819TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
8820 ASSERT_TRUE(http_test_server()->Start());
8821
8822 TestDelegate d;
8823 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168824 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
8825 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:268826 req->Start();
Wez2a31b222018-06-07 22:07:158827 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:268828
8829 EXPECT_EQ(30, req->GetRawBodyBytes());
8830}
8831
jamd3f5a3c2016-10-27 18:52:028832// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
8833// the delegate isn't called back synchronously.
8834TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
8835 ASSERT_TRUE(http_test_server()->Start());
8836 default_network_delegate_.set_before_start_transaction_fails();
8837
8838 TestDelegate d;
8839 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168840 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
8841 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:028842 req->Start();
8843 DCHECK(!d.response_completed());
Wez2a31b222018-06-07 22:07:158844 d.RunUntilComplete();
jamd3f5a3c2016-10-27 18:52:028845 DCHECK(d.response_completed());
8846 EXPECT_EQ(ERR_FAILED, d.request_status());
8847}
8848
bengr1bf8e942014-11-07 01:36:508849class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
8850 public:
8851 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
8852 // ideally remove the dependency on URLRequestTestJob, and maybe move these
8853 // tests into the factory tests.
8854 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
8855 }
8856
8857 void SetUpFactory() override {
8858 interceptor_ = new MockURLRequestInterceptor();
8859 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:368860 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:508861 }
8862
8863 MockURLRequestInterceptor* interceptor() const {
8864 return interceptor_;
8865 }
8866
8867 private:
8868 MockURLRequestInterceptor* interceptor_;
8869};
8870
8871TEST_F(URLRequestInterceptorTestHTTP,
8872 NetworkDelegateNotificationOnRedirectIntercept) {
8873 interceptor()->set_intercept_redirect(true);
8874 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
8875 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
8876
tommycli59a63432015-11-06 00:10:558877 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508878
8879 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368880 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168881 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8882 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:508883 req->Start();
Wez2a31b222018-06-07 22:07:158884 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:508885
8886 EXPECT_TRUE(interceptor()->did_intercept_redirect());
8887 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:508888 int status = d.request_status();
8889 EXPECT_EQ(OK, status);
8890 if (status == OK)
bengr1bf8e942014-11-07 01:36:508891 EXPECT_EQ(200, req->response_headers()->response_code());
8892
8893 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8894 EXPECT_EQ(1, d.response_started_count());
8895 EXPECT_EQ(0, d.received_redirect_count());
8896
8897 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008898 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508899 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
8900}
8901
8902TEST_F(URLRequestInterceptorTestHTTP,
8903 NetworkDelegateNotificationOnErrorIntercept) {
8904 // Intercept that error and respond with an OK response.
8905 interceptor()->set_intercept_final_response(true);
8906 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
8907 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
8908 default_network_delegate()->set_can_be_intercepted_on_error(true);
8909
tommycli59a63432015-11-06 00:10:558910 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508911
8912 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368913 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558914 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168915 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:508916 req->set_method("GET");
8917 req->Start();
Wez2a31b222018-06-07 22:07:158918 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:508919
8920 EXPECT_TRUE(interceptor()->did_intercept_final());
8921
8922 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:508923 int status = d.request_status();
8924 EXPECT_EQ(OK, status);
8925 if (status == OK)
bengr1bf8e942014-11-07 01:36:508926 EXPECT_EQ(200, req->response_headers()->response_code());
8927 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8928 EXPECT_EQ(1, d.response_started_count());
8929 EXPECT_EQ(0, d.received_redirect_count());
8930
8931 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008932 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508933 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
8934}
8935
8936TEST_F(URLRequestInterceptorTestHTTP,
8937 NetworkDelegateNotificationOnResponseIntercept) {
8938 // Intercept that error and respond with an OK response.
8939 interceptor()->set_intercept_final_response(true);
8940
8941 // Intercept with a real URLRequestHttpJob.
8942 interceptor()->set_use_url_request_http_job(true);
8943
tommycli59a63432015-11-06 00:10:558944 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508945
8946 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368947 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168948 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
8949 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:508950 req->set_method("GET");
8951 req->Start();
Wez2a31b222018-06-07 22:07:158952 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:508953
8954 EXPECT_TRUE(interceptor()->did_intercept_final());
8955
8956 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:508957 int status = d.request_status();
8958 EXPECT_EQ(OK, status);
8959 if (status == OK)
bengr1bf8e942014-11-07 01:36:508960 EXPECT_EQ(200, req->response_headers()->response_code());
8961 EXPECT_EQ("hello", d.data_received());
8962 EXPECT_EQ(1, d.response_started_count());
8963 EXPECT_EQ(0, d.received_redirect_count());
8964
8965 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008966 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508967 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
8968}
8969
mkwst0c5eab872014-11-21 14:18:548970class URLRequestTestReferrerPolicy : public URLRequestTest {
8971 public:
Chris Watkins7a41d3552017-12-01 02:13:278972 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:548973
tommycli59a63432015-11-06 00:10:558974 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
8975 origin_server_.reset(new EmbeddedTestServer(type));
8976 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
8977 origin_server_->AddDefaultHandlers(
8978 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8979 } else {
8980 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8981 }
mkwst0c5eab872014-11-21 14:18:548982 ASSERT_TRUE(origin_server_->Start());
8983 }
8984
tommycli59a63432015-11-06 00:10:558985 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
8986 net::EmbeddedTestServer::Type dest_type) {
8987 origin_server_.reset(new EmbeddedTestServer(origin_type));
8988 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8989 origin_server_->AddDefaultHandlers(
8990 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8991 } else {
8992 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8993 }
mkwst0c5eab872014-11-21 14:18:548994 ASSERT_TRUE(origin_server_->Start());
8995
tommycli59a63432015-11-06 00:10:558996 destination_server_.reset(new EmbeddedTestServer(dest_type));
8997 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8998 destination_server_->AddDefaultHandlers(
8999 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9000 } else {
9001 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9002 }
mkwst0c5eab872014-11-21 14:18:549003 ASSERT_TRUE(destination_server_->Start());
9004 }
9005
9006 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9007 const GURL& referrer,
9008 const GURL& expected) {
9009 // Create and execute the request: we'll only have a |destination_server_|
9010 // if the origins are meant to be distinct. Otherwise, we'll use the
9011 // |origin_server_| for both endpoints.
9012 GURL destination_url =
tommycli59a63432015-11-06 00:10:559013 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9014 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549015 GURL origin_url =
tommycli59a63432015-11-06 00:10:559016 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549017
9018 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079019 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169020 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549021 req->set_referrer_policy(policy);
9022 req->SetReferrer(referrer.spec());
9023 req->Start();
Wez2a31b222018-06-07 22:07:159024 d.RunUntilComplete();
mkwst0c5eab872014-11-21 14:18:549025
9026 EXPECT_EQ(1, d.response_started_count());
9027 EXPECT_EQ(1, d.received_redirect_count());
9028 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509029 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549030 EXPECT_EQ(200, req->response_headers()->response_code());
9031
9032 EXPECT_EQ(expected.spec(), req->referrer());
9033 if (expected.is_empty())
9034 EXPECT_EQ("None", d.data_received());
9035 else
9036 EXPECT_EQ(expected.spec(), d.data_received());
9037 }
9038
tommycli59a63432015-11-06 00:10:559039 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549040
9041 private:
danakj8522a25b2016-04-16 00:17:369042 std::unique_ptr<EmbeddedTestServer> origin_server_;
9043 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549044};
9045
9046TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559047 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549048
estarkc8ccba82017-06-13 22:37:409049 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549050 VerifyReferrerAfterRedirect(
9051 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409052 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549053
9054 VerifyReferrerAfterRedirect(
9055 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409056 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549057
9058 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409059 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549060
estarkc8ccba82017-06-13 22:37:409061 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9062 referrer);
9063
9064 // The original referrer set on the request is expected to obey the referrer
9065 // policy and already be stripped to the origin; thus this test case just
9066 // checks that this policy doesn't cause the referrer to change when following
9067 // a redirect.
9068 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9069 referrer.GetOrigin());
9070
9071 VerifyReferrerAfterRedirect(
9072 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9073 referrer);
9074
9075 // The original referrer set on the request is expected to obey the referrer
9076 // policy and already be stripped to the origin; thus this test case just
9077 // checks that this policy doesn't cause the referrer to change when following
9078 // a redirect.
9079 VerifyReferrerAfterRedirect(
9080 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9081 referrer.GetOrigin(), referrer.GetOrigin());
9082
9083 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549084}
9085
tommycli59a63432015-11-06 00:10:559086TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9087 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9088 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409089 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549090
9091 VerifyReferrerAfterRedirect(
9092 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409093 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549094
9095 VerifyReferrerAfterRedirect(
9096 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409097 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549098
9099 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409100 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9101 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549102
estarkc8ccba82017-06-13 22:37:409103 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9104 referrer);
9105
9106 // The original referrer set on the request is expected to obey the referrer
9107 // policy and already be stripped to the origin; thus this test case just
9108 // checks that this policy doesn't cause the referrer to change when following
9109 // a redirect.
9110 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9111 referrer.GetOrigin());
9112
9113 VerifyReferrerAfterRedirect(
9114 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9115
9116 // The original referrer set on the request is expected to obey the referrer
9117 // policy and already be stripped to the origin; thus this test case just
9118 // checks that this policy doesn't cause the referrer to change when following
9119 // a redirect.
9120 VerifyReferrerAfterRedirect(
9121 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9122 referrer.GetOrigin(), referrer.GetOrigin());
9123
9124 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549125}
9126
9127TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559128 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409129 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549130
9131 VerifyReferrerAfterRedirect(
9132 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409133 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549134
9135 VerifyReferrerAfterRedirect(
9136 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409137 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549138
9139 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409140 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549141
estarkc8ccba82017-06-13 22:37:409142 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9143 referrer);
9144
9145 // The original referrer set on the request is expected to obey the referrer
9146 // policy and already be stripped to the origin; thus this test case just
9147 // checks that this policy doesn't cause the referrer to change when following
9148 // a redirect.
9149 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9150 referrer.GetOrigin());
9151
9152 VerifyReferrerAfterRedirect(
9153 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9154 referrer);
9155
9156 // The original referrer set on the request is expected to obey the referrer
9157 // policy and already be stripped to the origin; thus this test case just
9158 // checks that this policy doesn't cause the referrer to change when following
9159 // a redirect.
9160 VerifyReferrerAfterRedirect(
9161 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9162 referrer.GetOrigin(), referrer.GetOrigin());
9163
9164 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549165}
9166
tommycli59a63432015-11-06 00:10:559167TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
9168 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9169 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409170 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549171
9172 VerifyReferrerAfterRedirect(
9173 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409174 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549175
9176 VerifyReferrerAfterRedirect(
9177 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409178 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549179
9180 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409181 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559182 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549183
estarkc8ccba82017-06-13 22:37:409184 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9185 referrer);
9186
9187 // The original referrer set on the request is expected to obey the referrer
9188 // policy and already be stripped to the origin; thus this test case just
9189 // checks that this policy doesn't cause the referrer to change when following
9190 // a redirect.
9191 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9192 referrer.GetOrigin());
9193
9194 VerifyReferrerAfterRedirect(
9195 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9196
9197 // The original referrer set on the request is expected to obey the referrer
9198 // policy and already be stripped to the origin; thus this test case just
9199 // checks that this policy doesn't cause the referrer to change when following
9200 // a redirect.
9201 VerifyReferrerAfterRedirect(
9202 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9203 referrer.GetOrigin(), referrer.GetOrigin());
9204
9205 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549206}
9207
tommycli59a63432015-11-06 00:10:559208TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
9209 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9210 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409211 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549212
9213 VerifyReferrerAfterRedirect(
9214 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409215 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549216
9217 VerifyReferrerAfterRedirect(
9218 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409219 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549220
9221 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409222 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559223 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549224
estarkc8ccba82017-06-13 22:37:409225 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9226 referrer);
9227
9228 // The original referrer set on the request is expected to obey the referrer
9229 // policy and already be stripped to the origin; thus this test case just
9230 // checks that this policy doesn't cause the referrer to change when following
9231 // a redirect.
9232 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9233 referrer.GetOrigin());
9234
9235 VerifyReferrerAfterRedirect(
9236 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9237
9238 // The original referrer set on the request is expected to obey the referrer
9239 // policy and already be stripped to the origin; thus this test case just
9240 // checks that this policy doesn't cause the referrer to change when following
9241 // a redirect.
9242 VerifyReferrerAfterRedirect(
9243 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9244 referrer.GetOrigin(), referrer.GetOrigin());
9245
9246 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549247}
9248
tommycli59a63432015-11-06 00:10:559249TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
9250 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9251 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409252 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549253
9254 VerifyReferrerAfterRedirect(
9255 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409256 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549257
9258 VerifyReferrerAfterRedirect(
9259 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409260 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549261
9262 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409263 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559264 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549265
estarkc8ccba82017-06-13 22:37:409266 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9267 referrer);
9268
9269 // The original referrer set on the request is expected to obey the referrer
9270 // policy and already be stripped to the origin; thus this test case just
9271 // checks that this policy doesn't cause the referrer to change when following
9272 // a redirect.
9273 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9274 referrer.GetOrigin());
9275
9276 VerifyReferrerAfterRedirect(
9277 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9278
9279 // The original referrer set on the request is expected to obey the referrer
9280 // policy and already be stripped to the origin, though it should be
9281 // subsequently cleared during the downgrading redirect.
9282 VerifyReferrerAfterRedirect(
9283 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9284 referrer.GetOrigin(), GURL());
9285
9286 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549287}
9288
Bence Béky98447b12018-05-08 03:14:019289class HTTPSRequestTest : public TestWithScopedTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:509290 public:
fdorayf33fede2017-05-11 21:18:109291 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:099292 default_context_.set_network_delegate(&default_network_delegate_);
9293 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:509294 }
Martijn Croonenb1383da2017-10-11 11:56:359295 ~HTTPSRequestTest() override {
9296 SetTransportSecurityStateSourceForTesting(nullptr);
9297 }
[email protected]87a09a92011-07-14 15:50:509298
9299 protected:
[email protected]ceefd7fd2012-11-29 00:36:249300 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:099301 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:469302};
9303
[email protected]c044616e2013-02-20 02:01:269304TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:559305 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9306 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229307 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119308 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469309
[email protected]ea224582008-12-07 20:25:469310 TestDelegate d;
9311 {
danakj8522a25b2016-04-16 00:17:369312 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169313 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9314 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199315 r->Start();
9316 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469317
Wez2a31b222018-06-07 22:07:159318 d.RunUntilComplete();
[email protected]ea224582008-12-07 20:25:469319
9320 EXPECT_EQ(1, d.response_started_count());
9321 EXPECT_FALSE(d.received_data_before_response());
9322 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199323 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199324 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199325 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199326 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199327 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:469328 }
[email protected]ea224582008-12-07 20:25:469329}
9330
[email protected]5774ada2010-07-15 06:30:549331TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559332 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9333 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9334 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229335 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119336 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339337
9338 bool err_allowed = true;
9339 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9340 TestDelegate d;
9341 {
9342 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369343 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169344 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9345 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339346
[email protected]f7022f32014-08-21 16:32:199347 r->Start();
9348 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339349
Wez2a31b222018-06-07 22:07:159350 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339351
9352 EXPECT_EQ(1, d.response_started_count());
9353 EXPECT_FALSE(d.received_data_before_response());
9354 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179355 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339356 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199357 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179358 } else {
[email protected]bacff652009-03-31 17:50:339359 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179360 }
[email protected]bacff652009-03-31 17:50:339361 }
9362 }
9363}
9364
[email protected]5774ada2010-07-15 06:30:549365TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559366 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9367 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9368 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229369 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119370 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339371
9372 // Iterate from false to true, just so that we do the opposite of the
9373 // previous test in order to increase test coverage.
9374 bool err_allowed = false;
9375 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9376 TestDelegate d;
9377 {
9378 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369379 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169380 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9381 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339382
[email protected]f7022f32014-08-21 16:32:199383 r->Start();
9384 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339385
Wez2a31b222018-06-07 22:07:159386 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339387
9388 EXPECT_EQ(1, d.response_started_count());
9389 EXPECT_FALSE(d.received_data_before_response());
9390 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179391 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339392 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199393 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179394 } else {
[email protected]bacff652009-03-31 17:50:339395 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179396 }
[email protected]bacff652009-03-31 17:50:339397 }
9398 }
9399}
[email protected]73e0bba2009-02-19 22:57:099400
tommycli59a63432015-11-06 00:10:559401// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
9402// security state. (see http://crbug.com/550977).
9403#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:359404// This tests that a load of a domain with preloaded HSTS and HPKP with a
9405// certificate error sets the |certificate_errors_are_fatal| flag correctly.
9406// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:449407TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359408 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9409
tommycli59a63432015-11-06 00:10:559410 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9411 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9412 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449413 ASSERT_TRUE(test_server.Start());
9414
Martijn Croonenb1383da2017-10-11 11:56:359415 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9416 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9417 // means that we have to use a MockHostResolver in order to direct
9418 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9419 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449420
9421 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249422 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449423 TestURLRequestContext context(true);
9424 context.set_network_delegate(&network_delegate);
9425 context.set_host_resolver(&host_resolver);
9426 TransportSecurityState transport_security_state;
9427 context.set_transport_security_state(&transport_security_state);
9428 context.Init();
9429
9430 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369431 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359432 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369433 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169434 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449435
[email protected]f7022f32014-08-21 16:32:199436 r->Start();
9437 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449438
Wez2a31b222018-06-07 22:07:159439 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449440
9441 EXPECT_EQ(1, d.response_started_count());
9442 EXPECT_FALSE(d.received_data_before_response());
9443 EXPECT_TRUE(d.have_certificate_errors());
9444 EXPECT_TRUE(d.certificate_errors_are_fatal());
9445}
9446
9447// This tests that cached HTTPS page loads do not cause any updates to the
9448// TransportSecurityState.
9449TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359450 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9451
[email protected]316c1e5e2012-09-12 15:17:449452 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
9453 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:559454 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9455 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9456 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449457 ASSERT_TRUE(test_server.Start());
9458
Martijn Croonenb1383da2017-10-11 11:56:359459 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9460 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9461 // means that we have to use a MockHostResolver in order to direct
9462 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9463 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449464
9465 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249466 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449467 TestURLRequestContext context(true);
9468 context.set_network_delegate(&network_delegate);
9469 context.set_host_resolver(&host_resolver);
9470 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:269471
martijnc0d6b622015-06-30 19:14:409472 TransportSecurityState::STSState static_sts_state;
9473 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269474 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359475 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:449476 context.set_transport_security_state(&transport_security_state);
9477 context.Init();
9478
martijnc0d6b622015-06-30 19:14:409479 TransportSecurityState::STSState dynamic_sts_state;
9480 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:359481 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
9482 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
9483 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
9484 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269485
[email protected]316c1e5e2012-09-12 15:17:449486 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369487 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359488 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369489 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169490 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449491
[email protected]f7022f32014-08-21 16:32:199492 r->Start();
9493 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449494
Wez2a31b222018-06-07 22:07:159495 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449496
9497 EXPECT_EQ(1, d.response_started_count());
9498 EXPECT_FALSE(d.received_data_before_response());
9499 EXPECT_TRUE(d.have_certificate_errors());
9500 EXPECT_TRUE(d.certificate_errors_are_fatal());
9501
[email protected]9e6968d2014-05-07 21:46:269502 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:409503 TransportSecurityState::STSState new_static_sts_state;
9504 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269505 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359506 "hsts-hpkp-preloaded.test", &new_static_sts_state,
9507 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:409508 TransportSecurityState::STSState new_dynamic_sts_state;
9509 TransportSecurityState::PKPState new_dynamic_pkp_state;
9510 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:359511 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:409512 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:359513 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269514
martijnc0d6b622015-06-30 19:14:409515 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
9516 EXPECT_EQ(new_static_sts_state.include_subdomains,
9517 static_sts_state.include_subdomains);
9518 EXPECT_EQ(new_static_pkp_state.include_subdomains,
9519 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:489520 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
9521 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
9522 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:449523}
9524
[email protected]8ccc69f2012-11-28 19:52:149525// Make sure HSTS preserves a POST request's method and body.
9526TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
9527 static const char kData[] = "hello world";
9528
tommycli59a63432015-11-06 00:10:559529 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9530 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229531 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:149532 ASSERT_TRUE(test_server.Start());
9533
9534
9535 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9536 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:559537 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:229538 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:149539 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:149540
9541 // Force https for www.somewhere.com.
9542 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:209543 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
9544 bool include_subdomains = false;
9545 transport_security_state.AddHSTS("www.somewhere.com", expiry,
9546 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:149547
9548 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9549
9550 TestURLRequestContext context(true);
9551 context.set_host_resolver(&host_resolver);
9552 context.set_transport_security_state(&transport_security_state);
9553 context.set_network_delegate(&network_delegate);
9554 context.Init();
9555
9556 TestDelegate d;
9557 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
9558 // cause a certificate error. Ignore the error.
9559 d.set_allow_certificate_errors(true);
9560
danakj8522a25b2016-04-16 00:17:369561 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199562 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:369563 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169564 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199565 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079566 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:149567
[email protected]f7022f32014-08-21 16:32:199568 req->Start();
Wez2a31b222018-06-07 22:07:159569 d.RunUntilComplete();
[email protected]8ccc69f2012-11-28 19:52:149570
[email protected]f7022f32014-08-21 16:32:199571 EXPECT_EQ("https", req->url().scheme());
9572 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:149573 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:409574
9575 LoadTimingInfo load_timing_info;
9576 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
9577 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
9578 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:149579}
9580
rob4e0be1f2014-09-11 23:40:229581// Make sure that the CORS headers are added to cross-origin HSTS redirects.
9582TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
9583 static const char kOriginHeaderValue[] = "http://www.example.com";
9584
tommycli59a63432015-11-06 00:10:559585 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9586 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:229587 ASSERT_TRUE(test_server.Start());
9588
9589 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9590 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:559591 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
9592 // default.
rob4e0be1f2014-09-11 23:40:229593 MockHostResolver host_resolver;
9594
9595 TransportSecurityState transport_security_state;
9596 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
9597 bool include_subdomains = false;
9598 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
9599
9600 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9601
9602 MockCertVerifier cert_verifier;
9603 cert_verifier.set_default_result(OK);
9604
9605 TestURLRequestContext context(true);
9606 context.set_host_resolver(&host_resolver);
9607 context.set_transport_security_state(&transport_security_state);
9608 context.set_network_delegate(&network_delegate);
9609 context.set_cert_verifier(&cert_verifier);
9610 context.Init();
9611
9612 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
9613 test_server.host_port_pair().port()));
9614 url::Replacements<char> replacements;
9615 const char kNewScheme[] = "https";
9616 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
9617 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
9618
9619 TestDelegate d;
rob4e0be1f2014-09-11 23:40:229620
rhalavatib7bd7c792017-04-27 05:25:169621 std::unique_ptr<URLRequest> req(context.CreateRequest(
9622 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:229623 // Set Origin header to simulate a cross-origin request.
9624 HttpRequestHeaders request_headers;
9625 request_headers.SetHeader("Origin", kOriginHeaderValue);
9626 req->SetExtraRequestHeaders(request_headers);
9627
9628 req->Start();
Wez0e717112018-06-18 23:09:229629 d.RunUntilRedirect();
rob4e0be1f2014-09-11 23:40:229630
9631 EXPECT_EQ(1, d.received_redirect_count());
9632
9633 const HttpResponseHeaders* headers = req->response_headers();
9634 std::string redirect_location;
9635 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
9636 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
9637
9638 std::string received_cors_header;
9639 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
9640 &received_cors_header));
9641 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
9642}
9643
[email protected]316c1e5e2012-09-12 15:17:449644namespace {
9645
9646class SSLClientAuthTestDelegate : public TestDelegate {
9647 public:
9648 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
Wez0e717112018-06-18 23:09:229649 set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:449650 }
dchengb03027d2014-10-21 12:00:209651 void OnCertificateRequested(URLRequest* request,
9652 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:449653 on_certificate_requested_count_++;
Wez0e717112018-06-18 23:09:229654 std::move(on_certificate_requested_).Run();
9655 }
9656 void RunUntilCertificateRequested() {
9657 base::RunLoop run_loop;
9658 on_certificate_requested_ = run_loop.QuitClosure();
9659 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:449660 }
9661 int on_certificate_requested_count() {
9662 return on_certificate_requested_count_;
9663 }
9664 private:
9665 int on_certificate_requested_count_;
Wez0e717112018-06-18 23:09:229666 base::OnceClosure on_certificate_requested_;
[email protected]316c1e5e2012-09-12 15:17:449667};
9668
David Benjamin76a40ad2018-02-24 22:22:089669class TestSSLPrivateKey : public SSLPrivateKey {
9670 public:
9671 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
9672 : key_(std::move(key)) {}
9673
9674 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
9675 int sign_count() const { return sign_count_; }
9676
David Benjaminb65b0732018-11-09 20:33:539677 std::string GetProviderName() override { return key_->GetProviderName(); }
David Benjamin76a40ad2018-02-24 22:22:089678 std::vector<uint16_t> GetAlgorithmPreferences() override {
9679 return key_->GetAlgorithmPreferences();
9680 }
9681 void Sign(uint16_t algorithm,
9682 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:269683 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:089684 sign_count_++;
9685 if (fail_signing_) {
9686 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:269687 FROM_HERE, base::BindOnce(std::move(callback),
9688 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
9689 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:089690 } else {
David Benjamin8f2d2c12018-02-27 00:08:269691 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:089692 }
9693 }
9694
9695 private:
9696 ~TestSSLPrivateKey() override = default;
9697
9698 scoped_refptr<SSLPrivateKey> key_;
9699 bool fail_signing_ = false;
9700 int sign_count_ = 0;
9701};
9702
[email protected]316c1e5e2012-09-12 15:17:449703} // namespace
9704
9705// TODO(davidben): Test the rest of the code. Specifically,
9706// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:449707// - Getting a certificate request in an SSL renegotiation sending the
9708// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:089709TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:559710 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9711 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:129712 ssl_config.client_cert_type =
9713 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:089714 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:559715 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229716 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449717 ASSERT_TRUE(test_server.Start());
9718
9719 SSLClientAuthTestDelegate d;
9720 {
danakj8522a25b2016-04-16 00:17:369721 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169722 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9723 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449724
[email protected]f7022f32014-08-21 16:32:199725 r->Start();
9726 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449727
Wez0e717112018-06-18 23:09:229728 d.RunUntilCertificateRequested();
9729 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449730
9731 EXPECT_EQ(1, d.on_certificate_requested_count());
9732 EXPECT_FALSE(d.received_data_before_response());
9733 EXPECT_EQ(0, d.bytes_received());
9734
9735 // Send no certificate.
9736 // TODO(davidben): Get temporary client cert import (with keys) working on
9737 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:549738 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:449739
Wez2a31b222018-06-07 22:07:159740 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449741
David Benjamin76a40ad2018-02-24 22:22:089742 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:449743 EXPECT_EQ(1, d.response_started_count());
9744 EXPECT_FALSE(d.received_data_before_response());
9745 EXPECT_NE(0, d.bytes_received());
9746 }
9747}
9748
David Benjamin76a40ad2018-02-24 22:22:089749TEST_F(HTTPSRequestTest, ClientAuth) {
9750 std::unique_ptr<FakeClientCertIdentity> identity =
9751 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
9752 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
9753 ASSERT_TRUE(identity);
9754 scoped_refptr<TestSSLPrivateKey> private_key =
9755 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
9756
9757 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9758 net::SSLServerConfig ssl_config;
9759 ssl_config.client_cert_type =
9760 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
9761 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
9762 test_server.AddDefaultHandlers(
9763 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9764 ASSERT_TRUE(test_server.Start());
9765
9766 {
9767 SSLClientAuthTestDelegate d;
9768 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9769 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9770 TRAFFIC_ANNOTATION_FOR_TESTS));
9771
9772 r->Start();
9773 EXPECT_TRUE(r->is_pending());
9774
Wez0e717112018-06-18 23:09:229775 d.RunUntilCertificateRequested();
9776 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:089777
9778 EXPECT_EQ(1, d.on_certificate_requested_count());
9779 EXPECT_FALSE(d.received_data_before_response());
9780 EXPECT_EQ(0, d.bytes_received());
9781
9782 // Send a certificate.
9783 r->ContinueWithCertificate(identity->certificate(), private_key);
9784
Wez2a31b222018-06-07 22:07:159785 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:089786
9787 EXPECT_EQ(OK, d.request_status());
9788 EXPECT_EQ(1, d.response_started_count());
9789 EXPECT_FALSE(d.received_data_before_response());
9790 EXPECT_NE(0, d.bytes_received());
9791
9792 // The private key should have been used.
9793 EXPECT_EQ(1, private_key->sign_count());
9794 }
9795
9796 // Close all connections and clear the session cache to force a new handshake.
9797 default_context_.http_transaction_factory()
9798 ->GetSession()
9799 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:479800 default_context_.http_transaction_factory()
9801 ->GetSession()
9802 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:089803
9804 // Connecting again should not call OnCertificateRequested. The identity is
9805 // taken from the client auth cache.
9806 {
9807 SSLClientAuthTestDelegate d;
9808 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9809 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9810 TRAFFIC_ANNOTATION_FOR_TESTS));
9811
9812 r->Start();
9813 EXPECT_TRUE(r->is_pending());
9814
Wez2a31b222018-06-07 22:07:159815 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:089816
9817 EXPECT_EQ(OK, d.request_status());
9818 EXPECT_EQ(0, d.on_certificate_requested_count());
9819 EXPECT_FALSE(d.received_data_before_response());
9820 EXPECT_EQ(1, d.response_started_count());
9821 EXPECT_FALSE(d.received_data_before_response());
9822 EXPECT_NE(0, d.bytes_received());
9823
9824 // The private key should have been used.
9825 EXPECT_EQ(2, private_key->sign_count());
9826 }
9827}
9828
9829// Test that private keys that fail to sign anything get evicted from the cache.
9830TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
9831 std::unique_ptr<FakeClientCertIdentity> identity =
9832 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
9833 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
9834 ASSERT_TRUE(identity);
9835 scoped_refptr<TestSSLPrivateKey> private_key =
9836 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
9837 private_key->set_fail_signing(true);
9838
9839 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9840 net::SSLServerConfig ssl_config;
9841 ssl_config.client_cert_type =
9842 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
9843 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
9844 test_server.AddDefaultHandlers(
9845 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9846 ASSERT_TRUE(test_server.Start());
9847
9848 {
9849 SSLClientAuthTestDelegate d;
9850 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9851 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9852 TRAFFIC_ANNOTATION_FOR_TESTS));
9853
9854 r->Start();
9855 EXPECT_TRUE(r->is_pending());
Wez0e717112018-06-18 23:09:229856
9857 d.RunUntilCertificateRequested();
9858 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:089859
9860 EXPECT_EQ(1, d.on_certificate_requested_count());
9861 EXPECT_FALSE(d.received_data_before_response());
9862 EXPECT_EQ(0, d.bytes_received());
9863
9864 // Send a certificate.
9865 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:159866 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:089867
9868 // The private key cannot sign anything, so we report an error.
9869 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
9870 EXPECT_EQ(1, d.response_started_count());
9871 EXPECT_FALSE(d.received_data_before_response());
9872 EXPECT_EQ(0, d.bytes_received());
9873
9874 // The private key should have been used.
9875 EXPECT_EQ(1, private_key->sign_count());
9876 }
9877
9878 // Close all connections and clear the session cache to force a new handshake.
9879 default_context_.http_transaction_factory()
9880 ->GetSession()
9881 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:479882 default_context_.http_transaction_factory()
9883 ->GetSession()
9884 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:089885
9886 // The bad identity should have been evicted from the cache, so connecting
9887 // again should call OnCertificateRequested again.
9888 {
9889 SSLClientAuthTestDelegate d;
9890 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9891 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9892 TRAFFIC_ANNOTATION_FOR_TESTS));
9893
9894 r->Start();
9895 EXPECT_TRUE(r->is_pending());
9896
Wez0e717112018-06-18 23:09:229897 d.RunUntilCertificateRequested();
9898 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:089899
9900 EXPECT_EQ(1, d.on_certificate_requested_count());
9901 EXPECT_FALSE(d.received_data_before_response());
9902 EXPECT_EQ(0, d.bytes_received());
9903
9904 // There should have been no additional uses of the private key.
9905 EXPECT_EQ(1, private_key->sign_count());
9906 }
9907}
9908
9909// Test that cached private keys that fail to sign anything trigger a
9910// retry. This is so we handle unplugged smartcards
9911// gracefully. https://crbug.com/813022.
9912TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
9913 std::unique_ptr<FakeClientCertIdentity> identity =
9914 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
9915 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
9916 ASSERT_TRUE(identity);
9917 scoped_refptr<TestSSLPrivateKey> private_key =
9918 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
9919
9920 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9921 net::SSLServerConfig ssl_config;
9922 ssl_config.client_cert_type =
9923 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
9924 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
9925 test_server.AddDefaultHandlers(
9926 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9927 ASSERT_TRUE(test_server.Start());
9928
9929 // Connect with a client certificate to put it in the client auth cache.
9930 {
9931 SSLClientAuthTestDelegate d;
9932 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9933 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9934 TRAFFIC_ANNOTATION_FOR_TESTS));
9935
9936 r->Start();
9937 EXPECT_TRUE(r->is_pending());
9938
Wez0e717112018-06-18 23:09:229939 d.RunUntilCertificateRequested();
9940 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:089941
9942 EXPECT_EQ(1, d.on_certificate_requested_count());
9943 EXPECT_FALSE(d.received_data_before_response());
9944 EXPECT_EQ(0, d.bytes_received());
9945
9946 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:159947 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:089948
9949 EXPECT_EQ(OK, d.request_status());
9950 EXPECT_EQ(1, d.response_started_count());
9951 EXPECT_FALSE(d.received_data_before_response());
9952 EXPECT_NE(0, d.bytes_received());
9953
9954 // The private key should have been used.
9955 EXPECT_EQ(1, private_key->sign_count());
9956 }
9957
9958 // Close all connections and clear the session cache to force a new handshake.
9959 default_context_.http_transaction_factory()
9960 ->GetSession()
9961 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:479962 default_context_.http_transaction_factory()
9963 ->GetSession()
9964 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:089965
9966 // Cause the private key to fail. Connecting again should attempt to use it,
9967 // notice the failure, and then request a new identity via
9968 // OnCertificateRequested.
9969 private_key->set_fail_signing(true);
9970
9971 {
9972 SSLClientAuthTestDelegate d;
9973 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9974 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9975 TRAFFIC_ANNOTATION_FOR_TESTS));
9976
9977 r->Start();
9978 EXPECT_TRUE(r->is_pending());
9979
Wez0e717112018-06-18 23:09:229980 d.RunUntilCertificateRequested();
9981 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:089982
9983 // There was an additional signing call on the private key (the one which
9984 // failed).
9985 EXPECT_EQ(2, private_key->sign_count());
9986
9987 // That caused another OnCertificateRequested call.
9988 EXPECT_EQ(1, d.on_certificate_requested_count());
9989 EXPECT_FALSE(d.received_data_before_response());
9990 EXPECT_EQ(0, d.bytes_received());
9991 }
9992}
9993
[email protected]316c1e5e2012-09-12 15:17:449994TEST_F(HTTPSRequestTest, ResumeTest) {
9995 // Test that we attempt a session resume when making two connections to the
9996 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:229997 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:449998 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:229999 SpawnedTestServer test_server(
10000 SpawnedTestServer::TYPE_HTTPS,
10001 ssl_options,
10002 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410003 ASSERT_TRUE(test_server.Start());
10004
Daniel McArdle3a663d62019-01-31 00:48:4710005 default_context_.http_transaction_factory()
10006 ->GetSession()
10007 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4410008
10009 {
10010 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610011 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610012 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10013 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410014
[email protected]f7022f32014-08-21 16:32:1910015 r->Start();
10016 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410017
Wez2a31b222018-06-07 22:07:1510018 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410019
10020 EXPECT_EQ(1, d.response_started_count());
10021 }
10022
10023 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10024 CloseAllConnections();
10025
10026 {
10027 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610028 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610029 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10030 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410031
[email protected]f7022f32014-08-21 16:32:1910032 r->Start();
10033 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410034
Wez2a31b222018-06-07 22:07:1510035 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410036
10037 // The response will look like;
Steven Valdez0ef94d02018-11-19 23:28:1310038 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]316c1e5e2012-09-12 15:17:4410039 // insert abc
10040 // lookup abc
10041 // insert xyz
10042 //
10043 // With a newline at the end which makes the split think that there are
10044 // four lines.
10045
10046 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2910047 std::vector<std::string> lines = base::SplitString(
10048 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Steven Valdez0ef94d02018-11-19 23:28:1310049 ASSERT_EQ(5u, lines.size()) << d.data_received();
[email protected]316c1e5e2012-09-12 15:17:4410050
10051 std::string session_id;
10052
Steven Valdez0ef94d02018-11-19 23:28:1310053 for (size_t i = 0; i < 3; i++) {
brettw3a2c6902015-07-06 19:43:2910054 std::vector<std::string> parts = base::SplitString(
10055 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410056 ASSERT_EQ(2u, parts.size());
Steven Valdez0ef94d02018-11-19 23:28:1310057 if (i % 2 == 1) {
[email protected]316c1e5e2012-09-12 15:17:4410058 EXPECT_EQ("insert", parts[0]);
10059 session_id = parts[1];
10060 } else {
10061 EXPECT_EQ("lookup", parts[0]);
Steven Valdez0ef94d02018-11-19 23:28:1310062 if (i != 0)
10063 EXPECT_EQ(session_id, parts[1]);
[email protected]316c1e5e2012-09-12 15:17:4410064 }
10065 }
10066 }
10067}
10068
10069TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
10070 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
10071 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2210072 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410073 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210074 SpawnedTestServer test_server(
10075 SpawnedTestServer::TYPE_HTTPS,
10076 ssl_options,
10077 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410078 ASSERT_TRUE(test_server.Start());
10079
Daniel McArdle3a663d62019-01-31 00:48:4710080 default_context_.http_transaction_factory()
10081 ->GetSession()
10082 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4410083
10084 {
10085 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610086 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0410087 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1610088 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410089
[email protected]f7022f32014-08-21 16:32:1910090 r->Start();
10091 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410092
Wez2a31b222018-06-07 22:07:1510093 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410094
10095 EXPECT_EQ(1, d.response_started_count());
10096 }
10097
10098 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4110099 HttpNetworkSession::Context session_context;
10100 session_context.host_resolver = default_context_.host_resolver();
10101 session_context.cert_verifier = default_context_.cert_verifier();
10102 session_context.transport_security_state =
10103 default_context_.transport_security_state();
10104 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2010105 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4110106 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5910107 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4110108 session_context.ssl_config_service = default_context_.ssl_config_service();
10109 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4410110 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4110111 session_context.http_server_properties =
10112 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4410113
mmenke6ddfbea2017-05-31 21:48:4110114 HttpNetworkSession network_session(HttpNetworkSession::Params(),
10115 session_context);
zhongyi4928bd52017-02-08 02:16:2710116 std::unique_ptr<HttpCache> cache(
10117 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
10118 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4410119
10120 default_context_.set_http_transaction_factory(cache.get());
10121
10122 {
10123 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610124 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610125 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10126 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410127
[email protected]f7022f32014-08-21 16:32:1910128 r->Start();
10129 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410130
Wez2a31b222018-06-07 22:07:1510131 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410132
[email protected]316c1e5e2012-09-12 15:17:4410133 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0410134 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]316c1e5e2012-09-12 15:17:4410135 }
10136}
10137
Bence Béky98447b12018-05-08 03:14:0110138class HTTPSFallbackTest : public TestWithScopedTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:5510139 public:
fdorayf33fede2017-05-11 21:18:1010140 HTTPSFallbackTest() : context_(true) {
Nick Harper2243e8002018-09-28 20:33:2610141 ssl_config_service_ = std::make_unique<TestSSLConfigService>();
davidben095ebb52017-04-12 22:23:3410142 context_.set_ssl_config_service(ssl_config_service_.get());
10143 }
Chris Watkins7a41d3552017-12-01 02:13:2710144 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5510145
10146 protected:
davidben095ebb52017-04-12 22:23:3410147 TestSSLConfigService* ssl_config_service() {
10148 return ssl_config_service_.get();
10149 }
10150
[email protected]48d2b7c52014-06-27 01:16:5510151 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
10152 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0010153 context_.Init();
10154 delegate_.set_allow_certificate_errors(true);
10155
[email protected]48d2b7c52014-06-27 01:16:5510156 SpawnedTestServer test_server(
10157 SpawnedTestServer::TYPE_HTTPS,
10158 ssl_options,
10159 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10160 ASSERT_TRUE(test_server.Start());
10161
tommycli59a63432015-11-06 00:10:5510162 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1610163 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5510164 request_->Start();
10165
Wez2a31b222018-06-07 22:07:1510166 delegate_.RunUntilComplete();
[email protected]48d2b7c52014-06-27 01:16:5510167 }
10168
davidben095ebb52017-04-12 22:23:3410169 void ExpectConnection(int version) {
10170 EXPECT_EQ(1, delegate_.response_started_count());
10171 EXPECT_NE(0, delegate_.bytes_received());
10172 EXPECT_EQ(version, SSLConnectionStatusToVersion(
10173 request_->ssl_info().connection_status));
10174 }
10175
[email protected]48d2b7c52014-06-27 01:16:5510176 void ExpectFailure(int error) {
10177 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5010178 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5510179 }
10180
10181 private:
Ryan Sleevib8449e02018-07-15 04:31:0710182 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5510183 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4710184 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610185 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:5510186};
10187
davidbenb127ca82015-06-15 19:05:4210188// Tests the TLS 1.0 fallback doesn't happen.
10189TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5510190 SpawnedTestServer::SSLOptions ssl_options(
10191 SpawnedTestServer::SSLOptions::CERT_OK);
10192 ssl_options.tls_intolerant =
10193 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
10194
10195 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5510196 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4210197}
10198
davidben5a312152016-06-27 22:11:4710199// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5510200TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4210201 SpawnedTestServer::SSLOptions ssl_options(
10202 SpawnedTestServer::SSLOptions::CERT_OK);
10203 ssl_options.tls_intolerant =
10204 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
10205
10206 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5510207 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
10208}
10209
davidben095ebb52017-04-12 22:23:3410210// Tests that TLS 1.3 interference results in a dedicated error code.
10211TEST_F(HTTPSFallbackTest, TLSv1_3Interference) {
10212 SpawnedTestServer::SSLOptions ssl_options(
10213 SpawnedTestServer::SSLOptions::CERT_OK);
10214 ssl_options.tls_intolerant =
10215 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10216 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
10217
10218 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10219 ExpectFailure(ERR_SSL_VERSION_INTERFERENCE);
10220}
10221
10222// Tests that disabling TLS 1.3 leaves TLS 1.3 interference unnoticed.
10223TEST_F(HTTPSFallbackTest, TLSv1_3InterferenceDisableVersion) {
10224 SpawnedTestServer::SSLOptions ssl_options(
10225 SpawnedTestServer::SSLOptions::CERT_OK);
10226 ssl_options.tls_intolerant =
10227 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10228 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_2);
10229
10230 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10231 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_2);
10232}
10233
Bence Béky98447b12018-05-08 03:14:0110234class HTTPSSessionTest : public TestWithScopedTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:2410235 public:
fdorayf33fede2017-05-11 21:18:1010236 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5910237 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410238
10239 default_context_.set_network_delegate(&default_network_delegate_);
10240 default_context_.set_cert_verifier(&cert_verifier_);
10241 default_context_.Init();
10242 }
Chris Watkins7a41d3552017-12-01 02:13:2710243 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2410244
10245 protected:
10246 MockCertVerifier cert_verifier_;
10247 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
10248 TestURLRequestContext default_context_;
10249};
10250
10251// Tests that session resumption is not attempted if an invalid certificate
10252// is presented.
10253TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
10254 SpawnedTestServer::SSLOptions ssl_options;
10255 ssl_options.record_resume = true;
10256 SpawnedTestServer test_server(
10257 SpawnedTestServer::TYPE_HTTPS,
10258 ssl_options,
10259 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10260 ASSERT_TRUE(test_server.Start());
10261
Daniel McArdle3a663d62019-01-31 00:48:4710262 default_context_.http_transaction_factory()
10263 ->GetSession()
10264 ->ClearSSLSessionCache();
[email protected]a8fed1742013-12-27 02:14:2410265
10266 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5910267 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2410268 {
10269 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610270 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0410271 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1610272 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410273
[email protected]f7022f32014-08-21 16:32:1910274 r->Start();
10275 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410276
Wez2a31b222018-06-07 22:07:1510277 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410278
10279 EXPECT_EQ(1, d.response_started_count());
10280 }
10281
10282 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10283 CloseAllConnections();
10284
10285 // Now change the certificate to be acceptable (so that the response is
10286 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910287 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410288 {
10289 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610290 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610291 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10292 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410293
[email protected]f7022f32014-08-21 16:32:1910294 r->Start();
10295 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410296
Wez2a31b222018-06-07 22:07:1510297 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410298
[email protected]a8fed1742013-12-27 02:14:2410299 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0410300 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]a8fed1742013-12-27 02:14:2410301 }
10302}
10303
[email protected]dffe8242012-03-20 15:14:2710304// This the fingerprint of the "Testing CA" certificate used by the testserver.
10305// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5810306static const SHA256HashValue kOCSPTestCertFingerprint = {{
10307 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
10308 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
10309 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1510310}};
[email protected]dffe8242012-03-20 15:14:2710311
[email protected]51523f52013-07-31 21:57:2810312// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
10313// testserver.
mattm0b12a6f2016-11-29 19:57:1610314static const SHA256HashValue kOCSPTestCertSPKI = {{
10315 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
10316 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
10317 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
10318}};
[email protected]51523f52013-07-31 21:57:2810319
[email protected]dffe8242012-03-20 15:14:2710320// This is the policy OID contained in the certificates that testserver
10321// generates.
10322static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
10323
10324class HTTPSOCSPTest : public HTTPSRequestTest {
10325 public:
10326 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0910327 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0810328 ev_test_policy_(
10329 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
10330 kOCSPTestCertFingerprint,
10331 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0210332 }
10333
dcheng67be2b1f2014-10-27 21:47:2910334 void SetUp() override {
Ryan Sleevi8a9c9c12018-05-09 02:36:2310335 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
[email protected]ef2bf422012-05-11 03:27:0910336 context_.Init();
[email protected]dffe8242012-03-20 15:14:2710337
Ryan Sleevi24fe2682018-08-16 21:33:4610338 context_.cert_verifier()->SetConfig(GetCertVerifierConfig());
10339
[email protected]cba24642014-08-15 20:49:5910340 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2010341 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:4210342 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:5010343 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2710344
Matt Muellerfb271992018-01-30 18:10:4810345#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510346 SetGlobalCertNetFetcherForTesting(net::CreateCertNetFetcher(&context_));
10347#endif
10348
svaldez2135be52016-04-20 16:34:5310349#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0910350 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2710351#endif
10352 }
10353
dadrian612337a2016-07-20 22:36:5810354 void DoConnectionWithDelegate(
10355 const SpawnedTestServer::SSLOptions& ssl_options,
10356 TestDelegate* delegate,
10357 SSLInfo* out_ssl_info) {
10358 // Always overwrite |out_ssl_info|.
10359 out_ssl_info->Reset();
10360
[email protected]ce7d0cbc2013-05-03 18:57:2210361 SpawnedTestServer test_server(
10362 SpawnedTestServer::TYPE_HTTPS,
10363 ssl_options,
10364 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2710365 ASSERT_TRUE(test_server.Start());
10366
dadrian612337a2016-07-20 22:36:5810367 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1610368 std::unique_ptr<URLRequest> r(
10369 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
10370 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910371 r->Start();
[email protected]dffe8242012-03-20 15:14:2710372
Wez2a31b222018-06-07 22:07:1510373 delegate->RunUntilComplete();
dadrian612337a2016-07-20 22:36:5810374 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2710375
dadrian612337a2016-07-20 22:36:5810376 *out_ssl_info = r->ssl_info();
10377 }
10378
10379 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
10380 CertStatus* out_cert_status) {
10381 // Always overwrite |out_cert_status|.
10382 *out_cert_status = 0;
10383
10384 TestDelegate d;
10385 SSLInfo ssl_info;
10386 ASSERT_NO_FATAL_FAILURE(
10387 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
10388
10389 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2710390 }
10391
dcheng67be2b1f2014-10-27 21:47:2910392 ~HTTPSOCSPTest() override {
Matt Muellerfb271992018-01-30 18:10:4810393#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510394 ShutdownGlobalCertNetFetcher();
10395#endif
10396
svaldez2135be52016-04-20 16:34:5310397#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1810398 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2710399#endif
10400 }
10401
[email protected]a13234c2012-03-20 21:45:0210402 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4610403 // GetCertVerifierConfig() configures the URLRequestContext that will be used
10404 // for making connections to the testserver. This can be overridden in test
10405 // subclasses for different behaviour.
10406 virtual CertVerifier::Config GetCertVerifierConfig() {
10407 CertVerifier::Config config;
10408 config.enable_rev_checking = true;
10409 return config;
[email protected]a13234c2012-03-20 21:45:0210410 }
10411
danakj8522a25b2016-04-16 00:17:3610412 std::unique_ptr<ScopedTestRoot> test_root_;
Ryan Sleevib8449e02018-07-15 04:31:0710413 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]ef2bf422012-05-11 03:27:0910414 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610415 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2710416};
10417
[email protected]a13234c2012-03-20 21:45:0210418static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2010419#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0210420 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
10421 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0410422 // TODO(eroman): Should this also be the return value for
10423 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0210424 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
10425#else
10426 return 0;
10427#endif
10428}
10429
[email protected]3a86a712013-07-30 07:16:2010430// SystemSupportsHardFailRevocationChecking returns true iff the current
10431// operating system supports revocation checking and can distinguish between
10432// situations where a given certificate lacks any revocation information (eg:
10433// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
10434// revocation information cannot be obtained (eg: the CRL was unreachable).
10435// If it does not, then tests which rely on 'hard fail' behaviour should be
10436// skipped.
10437static bool SystemSupportsHardFailRevocationChecking() {
Eric Roman1b628daa2017-10-19 19:52:0410438#if defined(OS_WIN) || defined(USE_NSS_CERTS) || \
10439 defined(USE_BUILTIN_CERT_VERIFIER)
[email protected]3a86a712013-07-30 07:16:2010440 return true;
10441#else
10442 return false;
10443#endif
10444}
10445
[email protected]a13234c2012-03-20 21:45:0210446// SystemUsesChromiumEVMetadata returns true iff the current operating system
10447// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
10448// several tests are effected because our testing EV certificate won't be
10449// recognised as EV.
10450static bool SystemUsesChromiumEVMetadata() {
Eric Roman5f8d9d22017-10-17 02:32:5210451#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0110452 return true;
Eric Roman5f8d9d22017-10-17 02:32:5210453#else
10454 return false;
[email protected]05454a432012-03-20 20:04:0110455#endif
10456}
10457
mattmaf868e72016-09-23 23:25:2010458// Returns the expected CertStatus for tests that expect an online revocation
10459// check failure as a result of checking a test EV cert, which will not
10460// actually trigger an online revocation check on some platforms.
10461static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
10462 if (SystemUsesChromiumEVMetadata()) {
10463 return ExpectedCertStatusForFailedOnlineRevocationCheck();
10464 } else {
10465 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
10466 // be enabled, and thus there will not be a revocation check to fail.
10467 return 0u;
10468 }
10469}
10470
[email protected]b6f2de32012-08-17 04:35:0810471static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3910472#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0210473 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
10474 return false;
10475#else
10476 return true;
10477#endif
10478}
10479
davidbend1fb2f12014-11-08 02:51:0010480static bool SystemSupportsOCSPStapling() {
Eric Roman1b628daa2017-10-19 19:52:0410481#if defined(USE_NSS_CERTS) || defined(OS_WIN) || \
10482 defined(USE_BUILTIN_CERT_VERIFIER)
mathpc992e602015-10-21 20:34:0310483 return true;
mathpc992e602015-10-21 20:34:0310484#else
10485 return false;
10486#endif
davidbend1fb2f12014-11-08 02:51:0010487}
10488
[email protected]dffe8242012-03-20 15:14:2710489TEST_F(HTTPSOCSPTest, Valid) {
10490 if (!SystemSupportsOCSP()) {
10491 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10492 return;
10493 }
10494
[email protected]ce7d0cbc2013-05-03 18:57:2210495 SpawnedTestServer::SSLOptions ssl_options(
10496 SpawnedTestServer::SSLOptions::CERT_AUTO);
10497 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2710498
[email protected]924e9f92012-12-16 22:00:5310499 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210500 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710501
10502 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10503
[email protected]a13234c2012-03-20 21:45:0210504 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10505 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2710506
10507 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10508}
10509
10510TEST_F(HTTPSOCSPTest, Revoked) {
10511 if (!SystemSupportsOCSP()) {
10512 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10513 return;
10514 }
10515
[email protected]ce7d0cbc2013-05-03 18:57:2210516 SpawnedTestServer::SSLOptions ssl_options(
10517 SpawnedTestServer::SSLOptions::CERT_AUTO);
10518 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2710519
10520 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210521 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710522
[email protected]dffe8242012-03-20 15:14:2710523 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2710524 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10525 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10526}
10527
10528TEST_F(HTTPSOCSPTest, Invalid) {
10529 if (!SystemSupportsOCSP()) {
10530 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10531 return;
10532 }
10533
[email protected]ce7d0cbc2013-05-03 18:57:2210534 SpawnedTestServer::SSLOptions ssl_options(
10535 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810536 ssl_options.ocsp_status =
10537 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2710538
[email protected]924e9f92012-12-16 22:00:5310539 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210540 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710541
Eric Roman1b628daa2017-10-19 19:52:0410542#if defined(USE_BUILTIN_CERT_VERIFIER)
10543 // TODO(649017): This test uses soft-fail revocation checking, but returns an
10544 // invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
10545 // doesn't consider this a candidate for soft-fail (only considers
10546 // network-level failures as skippable).
10547 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
10548 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
10549#else
[email protected]a13234c2012-03-20 21:45:0210550 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2710551 cert_status & CERT_STATUS_ALL_ERRORS);
Eric Roman1b628daa2017-10-19 19:52:0410552#endif
[email protected]dffe8242012-03-20 15:14:2710553
10554 // Without a positive OCSP response, we shouldn't show the EV status.
10555 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10556 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10557}
[email protected]a13234c2012-03-20 21:45:0210558
Matt Mueller5339d862018-05-02 18:53:5710559TEST_F(HTTPSOCSPTest, IntermediateValid) {
10560 if (!SystemSupportsOCSP()) {
10561 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10562 return;
10563 }
10564
10565 SpawnedTestServer::SSLOptions ssl_options(
10566 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
10567 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10568 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10569
10570 CertStatus cert_status;
10571 DoConnection(ssl_options, &cert_status);
10572
10573 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10574
10575 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10576 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10577
10578 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10579}
10580
10581TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
10582 if (!SystemSupportsOCSP()) {
10583 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10584 return;
10585 }
10586
10587 SpawnedTestServer::SSLOptions ssl_options(
10588 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
10589 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10590 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10591 // Use an OCSP response for the intermediate that would be too old for a leaf
10592 // cert, but is still valid for an intermediate.
10593 ssl_options.ocsp_intermediate_date =
10594 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
10595
10596 CertStatus cert_status;
10597 DoConnection(ssl_options, &cert_status);
10598
10599 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10600
10601 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10602 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10603
10604 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10605}
10606
10607TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
10608 if (!SystemSupportsOCSP()) {
10609 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10610 return;
10611 }
10612
10613 SpawnedTestServer::SSLOptions ssl_options(
10614 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
10615 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10616 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10617 ssl_options.ocsp_intermediate_date =
10618 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
10619
10620 CertStatus cert_status;
10621 DoConnection(ssl_options, &cert_status);
10622
10623#if defined(USE_BUILTIN_CERT_VERIFIER)
10624 // The builtin verifier enforces the baseline requirements for max age of an
10625 // intermediate's OCSP response.
10626 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
10627 cert_status & CERT_STATUS_ALL_ERRORS);
10628 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
10629#else
10630 // The platform verifiers are more lenient.
10631 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10632 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10633 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10634#endif
10635 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10636}
10637
10638TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
10639 if (!SystemSupportsOCSP()) {
10640 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10641 return;
10642 }
10643
10644 SpawnedTestServer::SSLOptions ssl_options(
10645 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
10646 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10647 ssl_options.ocsp_intermediate_status =
10648 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
10649
10650 CertStatus cert_status;
10651 DoConnection(ssl_options, &cert_status);
10652
10653#if defined(OS_WIN)
10654 // TODO(mattm): why does CertVerifyProcWin accept this?
10655 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10656#else
10657 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10658#endif
10659 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
10660 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10661}
10662
davidbend1fb2f12014-11-08 02:51:0010663TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0310664 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0010665 LOG(WARNING)
10666 << "Skipping test because system doesn't support OCSP stapling";
10667 return;
10668 }
10669
10670 SpawnedTestServer::SSLOptions ssl_options(
10671 SpawnedTestServer::SSLOptions::CERT_AUTO);
10672 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10673 ssl_options.staple_ocsp_response = true;
10674 ssl_options.ocsp_server_unavailable = true;
10675
10676 CertStatus cert_status;
10677 DoConnection(ssl_options, &cert_status);
10678
10679 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10680
10681 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10682 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10683
10684 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10685}
10686
davidben6c3191b2014-11-21 22:38:0410687// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4810688#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0410689#define MAYBE_RevokedStapled DISABLED_RevokedStapled
10690#else
10691#define MAYBE_RevokedStapled RevokedStapled
10692#endif
10693TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0310694 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0010695 LOG(WARNING)
10696 << "Skipping test because system doesn't support OCSP stapling";
10697 return;
10698 }
10699
10700 SpawnedTestServer::SSLOptions ssl_options(
10701 SpawnedTestServer::SSLOptions::CERT_AUTO);
10702 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
10703 ssl_options.staple_ocsp_response = true;
10704 ssl_options.ocsp_server_unavailable = true;
10705
10706 CertStatus cert_status;
10707 DoConnection(ssl_options, &cert_status);
10708
10709 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10710 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10711 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10712}
10713
dadrian612337a2016-07-20 22:36:5810714static const struct OCSPVerifyTestData {
10715 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
10716 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
10717 OCSPVerifyResult::ResponseStatus response_status;
10718 bool has_revocation_status;
10719 OCSPRevocationStatus cert_status;
10720} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3110721 // 0
dadrian612337a2016-07-20 22:36:5810722 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10723 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10724 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10725 OCSPVerifyResult::PROVIDED,
10726 true,
10727 OCSPRevocationStatus::GOOD},
10728
Eric Roman8673b812017-09-20 18:57:3110729 // 1
dadrian612337a2016-07-20 22:36:5810730 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10731 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10732 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10733 OCSPVerifyResult::INVALID_DATE,
10734 false,
10735 OCSPRevocationStatus::UNKNOWN},
10736
Eric Roman8673b812017-09-20 18:57:3110737 // 2
dadrian612337a2016-07-20 22:36:5810738 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10739 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10740 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10741 OCSPVerifyResult::INVALID_DATE,
10742 false,
10743 OCSPRevocationStatus::UNKNOWN},
10744
Eric Roman8673b812017-09-20 18:57:3110745 // 3
dadrian612337a2016-07-20 22:36:5810746 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10747 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10748 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10749 OCSPVerifyResult::INVALID_DATE,
10750 false,
10751 OCSPRevocationStatus::UNKNOWN},
10752
Eric Roman8673b812017-09-20 18:57:3110753 // 4
dadrian612337a2016-07-20 22:36:5810754 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10755 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10756 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10757 OCSPVerifyResult::INVALID_DATE,
10758 false,
10759 OCSPRevocationStatus::UNKNOWN},
10760
Eric Roman8673b812017-09-20 18:57:3110761 // 5
dadrian612337a2016-07-20 22:36:5810762 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
10763 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10764 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10765 OCSPVerifyResult::ERROR_RESPONSE,
10766 false,
10767 OCSPRevocationStatus::UNKNOWN},
10768
Eric Roman8673b812017-09-20 18:57:3110769 // 6
dadrian612337a2016-07-20 22:36:5810770 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
10771 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10772 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10773 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
10774 false,
10775 OCSPRevocationStatus::UNKNOWN},
10776
Eric Roman8673b812017-09-20 18:57:3110777 // 7
dadrian612337a2016-07-20 22:36:5810778 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
10779 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10780 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10781 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
10782 false,
10783 OCSPRevocationStatus::UNKNOWN},
10784
Eric Roman8673b812017-09-20 18:57:3110785 // 8
dadrian612337a2016-07-20 22:36:5810786 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10787 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10788 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10789 OCSPVerifyResult::INVALID_DATE,
10790 false,
10791 OCSPRevocationStatus::UNKNOWN},
10792
Eric Roman8673b812017-09-20 18:57:3110793 // 9
dadrian612337a2016-07-20 22:36:5810794 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10795 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10796 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10797 OCSPVerifyResult::PROVIDED,
10798 true,
10799 OCSPRevocationStatus::UNKNOWN},
10800
Eric Roman8673b812017-09-20 18:57:3110801 // 10
dadrian612337a2016-07-20 22:36:5810802 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10803 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10804 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10805 OCSPVerifyResult::INVALID_DATE,
10806 false,
10807 OCSPRevocationStatus::UNKNOWN},
10808
Eric Roman8673b812017-09-20 18:57:3110809 // 11
dadrian612337a2016-07-20 22:36:5810810 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10811 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10812 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10813 OCSPVerifyResult::INVALID_DATE,
10814 false,
10815 OCSPRevocationStatus::UNKNOWN},
10816
Eric Roman8673b812017-09-20 18:57:3110817 // 12
dadrian612337a2016-07-20 22:36:5810818 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10819 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10820 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
10821 OCSPVerifyResult::BAD_PRODUCED_AT,
10822 false,
10823 OCSPRevocationStatus::UNKNOWN},
10824
Eric Roman8673b812017-09-20 18:57:3110825 // 13
dadrian612337a2016-07-20 22:36:5810826 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10827 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10828 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
10829 OCSPVerifyResult::BAD_PRODUCED_AT,
10830 false,
10831 OCSPRevocationStatus::UNKNOWN},
10832
Eric Roman8673b812017-09-20 18:57:3110833 // 14
dadrian612337a2016-07-20 22:36:5810834 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10835 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10836 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
10837 OCSPVerifyResult::BAD_PRODUCED_AT,
10838 false,
10839 OCSPRevocationStatus::UNKNOWN},
10840
Eric Roman8673b812017-09-20 18:57:3110841 // 15
dadrian612337a2016-07-20 22:36:5810842 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10843 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10844 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10845 OCSPVerifyResult::PROVIDED,
10846 true,
10847 OCSPRevocationStatus::GOOD},
10848
Eric Roman8673b812017-09-20 18:57:3110849 // 16
dadrian612337a2016-07-20 22:36:5810850 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10851 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
10852 {SpawnedTestServer::SSLOptions::OCSP_OK,
10853 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10854 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10855 OCSPVerifyResult::PROVIDED,
10856 true,
10857 OCSPRevocationStatus::GOOD},
10858
Eric Roman8673b812017-09-20 18:57:3110859 // 17
dadrian612337a2016-07-20 22:36:5810860 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10861 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
10862 {SpawnedTestServer::SSLOptions::OCSP_OK,
10863 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10864 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10865 OCSPVerifyResult::PROVIDED,
10866 true,
10867 OCSPRevocationStatus::GOOD},
10868
Eric Roman8673b812017-09-20 18:57:3110869 // 18
dadrian612337a2016-07-20 22:36:5810870 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10871 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
10872 {SpawnedTestServer::SSLOptions::OCSP_OK,
10873 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10874 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10875 OCSPVerifyResult::PROVIDED,
10876 true,
10877 OCSPRevocationStatus::GOOD},
10878
Eric Roman8673b812017-09-20 18:57:3110879 // 19
dadrian612337a2016-07-20 22:36:5810880 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10881 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
10882 {SpawnedTestServer::SSLOptions::OCSP_OK,
10883 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
10884 {SpawnedTestServer::SSLOptions::OCSP_OK,
10885 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10886 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10887 OCSPVerifyResult::INVALID_DATE,
10888 false,
10889 OCSPRevocationStatus::UNKNOWN},
10890
Eric Roman8673b812017-09-20 18:57:3110891 // 20
dadrian612337a2016-07-20 22:36:5810892 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10893 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10894 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10895 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10896 {SpawnedTestServer::SSLOptions::OCSP_OK,
10897 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10898 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10899 OCSPVerifyResult::PROVIDED,
10900 true,
10901 OCSPRevocationStatus::REVOKED},
10902
Eric Roman8673b812017-09-20 18:57:3110903 // 21
dadrian612337a2016-07-20 22:36:5810904 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10905 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10906 {SpawnedTestServer::SSLOptions::OCSP_OK,
10907 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10908 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10909 OCSPVerifyResult::PROVIDED,
10910 true,
10911 OCSPRevocationStatus::UNKNOWN},
10912
Eric Roman8673b812017-09-20 18:57:3110913 // 22
dadrian612337a2016-07-20 22:36:5810914 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10915 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10916 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10917 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
10918 {SpawnedTestServer::SSLOptions::OCSP_OK,
10919 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10920 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10921 OCSPVerifyResult::PROVIDED,
10922 true,
10923 OCSPRevocationStatus::UNKNOWN},
10924
Eric Roman8673b812017-09-20 18:57:3110925 // 23
dadrian612337a2016-07-20 22:36:5810926 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10927 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10928 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10929 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10930 false,
10931 OCSPRevocationStatus::UNKNOWN},
10932
Eric Roman8673b812017-09-20 18:57:3110933 // 24
dadrian612337a2016-07-20 22:36:5810934 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10935 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10936 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10937 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10938 false,
10939 OCSPRevocationStatus::UNKNOWN},
10940
Eric Roman8673b812017-09-20 18:57:3110941// These tests fail when using NSS for certificate verification, as NSS fails
10942// and doesn't return the partial path. As a result the OCSP checks being done
10943// at the CertVerifyProc layer cannot access the issuer certificate.
10944#if !defined(USE_NSS_CERTS)
10945 // 25
10946 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10947 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10948 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10949 OCSPVerifyResult::PROVIDED,
10950 true,
10951 OCSPRevocationStatus::REVOKED},
10952
10953 // 26
10954 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10955 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10956 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10957 OCSPVerifyResult::INVALID_DATE,
10958 false,
10959 OCSPRevocationStatus::UNKNOWN},
10960
10961 // 27
10962 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10963 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10964 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10965 OCSPVerifyResult::INVALID_DATE,
10966 false,
10967 OCSPRevocationStatus::UNKNOWN},
10968#endif
dadrian612337a2016-07-20 22:36:5810969};
10970
10971class HTTPSOCSPVerifyTest
10972 : public HTTPSOCSPTest,
10973 public testing::WithParamInterface<OCSPVerifyTestData> {};
10974
10975TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
10976 SpawnedTestServer::SSLOptions ssl_options(
10977 SpawnedTestServer::SSLOptions::CERT_AUTO);
10978 OCSPVerifyTestData test = GetParam();
10979
10980 ssl_options.ocsp_responses = test.ocsp_responses;
10981 ssl_options.ocsp_produced = test.ocsp_produced;
10982 ssl_options.staple_ocsp_response = true;
10983
10984 SSLInfo ssl_info;
10985 OCSPErrorTestDelegate delegate;
10986 ASSERT_NO_FATAL_FAILURE(
10987 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
10988
10989 // The SSLInfo must be extracted from |delegate| on error, due to how
10990 // URLRequest caches certificate errors.
10991 if (delegate.have_certificate_errors()) {
10992 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
10993 ssl_info = delegate.ssl_info();
10994 }
10995
10996 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
10997
10998 if (test.has_revocation_status)
10999 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
11000}
11001
Victor Costan8fb98f6f2019-02-01 17:08:2911002INSTANTIATE_TEST_SUITE_P(OCSPVerify,
11003 HTTPSOCSPVerifyTest,
11004 testing::ValuesIn(kOCSPVerifyData));
dadrian612337a2016-07-20 22:36:5811005
mattm0b12a6f2016-11-29 19:57:1611006class HTTPSAIATest : public HTTPSOCSPTest {
11007 public:
Ryan Sleevi24fe2682018-08-16 21:33:4611008 CertVerifier::Config GetCertVerifierConfig() override {
11009 CertVerifier::Config config;
11010 return config;
mattm0b12a6f2016-11-29 19:57:1611011 }
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
Ryan Sleevi5b4702a2018-04-06 22:23:5611022 // Unmark the certificate's OID as EV, which will disable revocation
11023 // checking.
11024 ev_test_policy_.reset();
11025
mattm0b12a6f2016-11-29 19:57:1611026 TestDelegate d;
11027 d.set_allow_certificate_errors(true);
11028 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611029 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11030 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611031
11032 r->Start();
11033 EXPECT_TRUE(r->is_pending());
11034
Wez2a31b222018-06-07 22:07:1511035 d.RunUntilComplete();
mattm0b12a6f2016-11-29 19:57:1611036
11037 EXPECT_EQ(1, d.response_started_count());
11038
11039 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4811040 EXPECT_EQ(OK, d.request_status());
11041 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11042 ASSERT_TRUE(r->ssl_info().cert);
11043 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611044 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3411045 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611046}
11047
[email protected]3a86a712013-07-30 07:16:2011048class HTTPSHardFailTest : public HTTPSOCSPTest {
11049 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611050 CertVerifier::Config GetCertVerifierConfig() override {
11051 CertVerifier::Config config;
11052 config.require_rev_checking_local_anchors = true;
11053 return config;
[email protected]3a86a712013-07-30 07:16:2011054 }
11055};
11056
[email protected]3a86a712013-07-30 07:16:2011057TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
11058 if (!SystemSupportsOCSP()) {
11059 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11060 return;
11061 }
11062
11063 if (!SystemSupportsHardFailRevocationChecking()) {
11064 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
11065 << "revocation checking";
11066 return;
11067 }
11068
11069 SpawnedTestServer::SSLOptions ssl_options(
11070 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811071 ssl_options.ocsp_status =
11072 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2011073
11074 CertStatus cert_status;
11075 DoConnection(ssl_options, &cert_status);
11076
Eric Roman1b628daa2017-10-19 19:52:0411077#if defined(USE_BUILTIN_CERT_VERIFIER)
11078 // TODO(crbug.com/649017): Should we consider invalid response as
11079 // affirmatively revoked?
11080 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11081 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11082#else
11083 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
11084#endif
[email protected]3a86a712013-07-30 07:16:2011085
11086 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0411087 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2011088 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11089}
11090
[email protected]a13234c2012-03-20 21:45:0211091class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
11092 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611093 CertVerifier::Config GetCertVerifierConfig() override {
11094 CertVerifier::Config config;
11095 return config;
[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
[email protected]924e9f92012-12-16 22:00:5311110 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211111 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211112
mattmaf868e72016-09-23 23:25:2011113 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211114 cert_status & CERT_STATUS_ALL_ERRORS);
11115
11116 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811117 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11118 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211119}
11120
[email protected]be0fff62013-08-29 23:37:4811121TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
11122 if (!SystemSupportsOCSP()) {
11123 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11124 return;
11125 }
11126
11127 SpawnedTestServer::SSLOptions ssl_options(
11128 SpawnedTestServer::SSLOptions::CERT_AUTO);
11129 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]be0fff62013-08-29 23:37:4811130
11131 CertStatus cert_status;
11132 DoConnection(ssl_options, &cert_status);
11133
mattm1a282f52016-11-10 21:49:4211134// Currently only works for Windows and OS X. When using NSS, it's not
11135// possible to determine whether the check failed because of actual
11136// revocation or because there was an OCSP failure.
11137#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4811138 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11139#else
11140 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11141#endif
11142
11143 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11144 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11145 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11146}
11147
[email protected]a13234c2012-03-20 21:45:0211148TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
11149 if (!SystemSupportsOCSP()) {
11150 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11151 return;
11152 }
11153
[email protected]ce7d0cbc2013-05-03 18:57:2211154 SpawnedTestServer::SSLOptions ssl_options(
11155 SpawnedTestServer::SSLOptions::CERT_AUTO);
11156 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0211157
11158 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211159 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211160
11161 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11162
11163 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11164 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0811165 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11166 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211167}
11168
11169TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
11170 if (!SystemSupportsOCSP()) {
11171 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11172 return;
11173 }
11174
[email protected]ce7d0cbc2013-05-03 18:57:2211175 SpawnedTestServer::SSLOptions ssl_options(
11176 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811177 ssl_options.ocsp_status =
11178 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211179 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11180 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11181 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211182
11183 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211184 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211185
mattmaf868e72016-09-23 23:25:2011186 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211187 cert_status & CERT_STATUS_ALL_ERRORS);
11188
11189 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811190 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11191 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211192}
11193
[email protected]51523f52013-07-31 21:57:2811194TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
11195 if (!SystemSupportsOCSP()) {
11196 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11197 return;
11198 }
11199
11200 SpawnedTestServer::SSLOptions ssl_options(
11201 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811202 ssl_options.ocsp_status =
11203 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211204 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11205 cert_verifier_config.crl_set =
11206 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {});
11207 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2811208
11209 CertStatus cert_status;
11210 DoConnection(ssl_options, &cert_status);
11211
11212 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
11213 // revocation check for EV.
11214 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11215 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11216 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11217 EXPECT_FALSE(
11218 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11219}
11220
11221TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
11222 if (!SystemSupportsOCSP()) {
11223 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11224 return;
11225 }
11226
[email protected]ce7d0cbc2013-05-03 18:57:2211227 SpawnedTestServer::SSLOptions ssl_options(
11228 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811229 ssl_options.ocsp_status =
11230 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211231 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11232 cert_verifier_config.crl_set = CRLSet::EmptyCRLSetForTesting();
11233 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211234
[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
11249class HTTPSCRLSetTest : public HTTPSOCSPTest {
11250 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611251 CertVerifier::Config GetCertVerifierConfig() override {
11252 CertVerifier::Config config;
11253 return config;
Ryan Sleevi5b4702a2018-04-06 22:23:5611254 }
11255
11256 void SetUp() override {
11257 HTTPSOCSPTest::SetUp();
11258
11259 // Unmark the certificate's OID as EV, which should disable revocation
11260 // checking (as per the user preference).
11261 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0211262 }
11263};
11264
11265TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2211266 SpawnedTestServer::SSLOptions ssl_options(
11267 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811268 ssl_options.ocsp_status =
11269 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211270 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11271 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11272 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211273
[email protected]924e9f92012-12-16 22:00:5311274 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211275 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211276
11277 // If we're not trying EV verification then, even if the CRLSet has expired,
11278 // we don't fall back to online revocation checks.
11279 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11280 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11281 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11282}
[email protected]51523f52013-07-31 21:57:2811283
Ryan Sleevi5b4702a2018-04-06 22:23:5611284TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
11285 // Test that when online revocation checking is disabled, and the leaf
11286 // certificate is not EV, that no revocation checking actually happens.
11287 if (!SystemSupportsOCSP()) {
11288 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11289 return;
11290 }
11291
11292 SpawnedTestServer::SSLOptions ssl_options(
11293 SpawnedTestServer::SSLOptions::CERT_AUTO);
11294 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Ryan Sleevib369d712018-08-20 16:43:2211295
11296 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11297 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11298 context_.cert_verifier()->SetConfig(cert_verifier_config);
Ryan Sleevi5b4702a2018-04-06 22:23:5611299
11300 CertStatus cert_status;
11301 DoConnection(ssl_options, &cert_status);
11302
11303 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11304
11305 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11306 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11307}
11308
[email protected]51523f52013-07-31 21:57:2811309TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2511310#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2811311 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11312 return;
11313#endif
11314
11315 SpawnedTestServer::SSLOptions ssl_options(
11316 SpawnedTestServer::SSLOptions::CERT_AUTO);
11317 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11318 ssl_options.cert_serial = 10;
Ryan Sleevib369d712018-08-20 16:43:2211319
11320 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11321 cert_verifier_config.crl_set =
11322 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {});
11323 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2811324
11325 CertStatus cert_status = 0;
11326 DoConnection(ssl_options, &cert_status);
11327
11328 // If the certificate is recorded as revoked in the CRLSet, that should be
11329 // reflected without online revocation checking.
11330 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11331 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5611332 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2811333}
Adam Langleyea6d6782017-12-05 23:57:3311334
11335TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
11336#if defined(OS_ANDROID)
11337 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11338 return;
11339#endif
11340
11341 SpawnedTestServer::SSLOptions ssl_options(
11342 SpawnedTestServer::SSLOptions::CERT_AUTO);
11343 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11344 static const char kCommonName[] = "Test CN";
11345 ssl_options.cert_common_name = kCommonName;
11346
11347 {
Ryan Sleevib369d712018-08-20 16:43:2211348 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11349 cert_verifier_config.crl_set =
11350 CRLSet::ForTesting(false, nullptr, "", kCommonName, {});
11351 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3311352
11353 CertStatus cert_status = 0;
11354 DoConnection(ssl_options, &cert_status);
11355
11356 // If the certificate is recorded as revoked in the CRLSet, that should be
11357 // reflected without online revocation checking.
11358 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11359 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5611360 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3311361 }
11362
11363 const uint8_t kTestServerSPKISHA256[32] = {
11364 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
11365 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
11366 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
11367 };
11368 const std::string spki_hash(
11369 reinterpret_cast<const char*>(kTestServerSPKISHA256),
11370 sizeof(kTestServerSPKISHA256));
11371
11372 {
Ryan Sleevib369d712018-08-20 16:43:2211373 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11374 cert_verifier_config.crl_set =
11375 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash});
11376 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3311377
11378 CertStatus cert_status = 0;
11379 DoConnection(ssl_options, &cert_status);
11380
11381 // When the correct SPKI hash is specified, the connection should succeed
11382 // even though the subject is listed in the CRLSet.
11383 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11384 }
11385}
[email protected]316c1e5e2012-09-12 15:17:4411386#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2711387
Sergey Ulanovc4580e72017-09-13 23:30:1111388#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
11389 !defined(OS_FUCHSIA)
11390// FTP uses a second TCP connection with the port number allocated dynamically
11391// on the server side, so it would be hard to make RemoteTestServer proxy FTP
11392// connections reliably. FTP tests are disabled on platforms that use
11393// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3111394class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1111395 public:
[email protected]d9fca99a2012-02-24 16:16:2011396 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0511397 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5511398 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4711399 // Can't use |default_context_|'s HostResolver to set up the
11400 // FTPTransactionFactory because it hasn't been created yet.
Ryan Sleevib8449e02018-07-15 04:31:0711401 default_context().set_host_resolver(&host_resolver_);
mmenke9f2ec60c2015-06-01 20:59:4711402 }
11403
11404 // URLRequestTest interface:
11405 void SetUpFactory() override {
11406 // Add FTP support to the default URLRequestContext.
11407 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0511408 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4711409 }
11410
11411 std::string GetTestFileContents() {
11412 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1911413 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4711414 path = path.Append(kTestFilePath);
11415 path = path.AppendASCII(kFtpTestFile);
11416 std::string contents;
11417 EXPECT_TRUE(base::ReadFileToString(path, &contents));
11418 return contents;
[email protected]95409e12010-08-17 20:07:1111419 }
11420
[email protected]b89ca032009-08-31 21:41:3111421 protected:
mmenke9f2ec60c2015-06-01 20:59:4711422 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4711423
tommycli59a63432015-11-06 00:10:5511424 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3111425};
11426
[email protected]d2a133182012-08-05 16:44:0811427// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0911428TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0811429 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0811430
11431 TestDelegate d;
11432 {
Ryan Sleevib8449e02018-07-15 04:31:0711433 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611434 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911435 r->Start();
11436 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0811437
Wez2a31b222018-06-07 22:07:1511438 d.RunUntilComplete();
[email protected]d2a133182012-08-05 16:44:0811439
[email protected]f7022f32014-08-21 16:32:1911440 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5011441 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0811442 }
11443}
11444
mmenke9f2ec60c2015-06-01 20:59:4711445TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5511446 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111447
[email protected]a25e90e2009-09-09 17:05:3711448 TestDelegate d;
11449 {
Ryan Sleevib8449e02018-07-15 04:31:0711450 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611451 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
11452 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911453 r->Start();
11454 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711455
Wez2a31b222018-06-07 22:07:1511456 d.RunUntilComplete();
[email protected]a25e90e2009-09-09 17:05:3711457
[email protected]f7022f32014-08-21 16:32:1911458 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711459 EXPECT_EQ(1, d.response_started_count());
11460 EXPECT_FALSE(d.received_data_before_response());
11461 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5511462 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911463 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511464 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911465 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:3711466 }
11467}
11468
mmenke9f2ec60c2015-06-01 20:59:4711469TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5511470 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111471
[email protected]dd265012009-01-08 20:45:2711472 TestDelegate d;
11473 {
Ryan Sleevib8449e02018-07-15 04:31:0711474 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611475 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
11476 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911477 r->Start();
11478 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711479
Wez2a31b222018-06-07 22:07:1511480 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711481
[email protected]f7022f32014-08-21 16:32:1911482 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711483 EXPECT_EQ(1, d.response_started_count());
11484 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711485 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511486 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911487 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511488 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911489 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:2711490 }
11491}
11492
Mike West80462a12018-11-27 16:05:0611493TEST_F(URLRequestTestFTP, FTPMimeType) {
11494 ASSERT_TRUE(ftp_test_server_.Start());
11495
11496 struct {
11497 const char* path;
11498 const char* mime;
11499 } test_cases[] = {
11500 {"/", "text/vnd.chromium.ftp-dir"},
11501 {kFtpTestFile, "application/octet-stream"},
11502 };
11503
11504 for (const auto test : test_cases) {
11505 TestDelegate d;
11506
11507 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
11508 ftp_test_server_.GetURL(test.path), DEFAULT_PRIORITY, &d,
11509 TRAFFIC_ANNOTATION_FOR_TESTS));
11510 r->Start();
11511 EXPECT_TRUE(r->is_pending());
11512
11513 d.RunUntilComplete();
11514
11515 std::string mime;
11516 r->GetMimeType(&mime);
11517 EXPECT_EQ(test.mime, mime);
11518 }
11519}
11520
mmenke9f2ec60c2015-06-01 20:59:4711521TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5511522 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111523
[email protected]dd265012009-01-08 20:45:2711524 TestDelegate d;
11525 {
Ryan Sleevib8449e02018-07-15 04:31:0711526 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511527 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11528 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611529 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911530 r->Start();
11531 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711532
Wez2a31b222018-06-07 22:07:1511533 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711534
[email protected]f7022f32014-08-21 16:32:1911535 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4711536 EXPECT_EQ(1, d.response_started_count());
11537 EXPECT_FALSE(d.received_data_before_response());
11538 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511539 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911540 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511541 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911542 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2511543
11544 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1911545 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2511546 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2711547 }
11548}
11549
mmenke9f2ec60c2015-06-01 20:59:4711550TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5511551 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111552
[email protected]dd265012009-01-08 20:45:2711553 TestDelegate d;
11554 {
Ryan Sleevib8449e02018-07-15 04:31:0711555 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511556 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11557 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611558 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911559 r->Start();
11560 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711561
Wez2a31b222018-06-07 22:07:1511562 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711563
[email protected]f7022f32014-08-21 16:32:1911564 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711565 EXPECT_EQ(1, d.response_started_count());
11566 EXPECT_FALSE(d.received_data_before_response());
11567 EXPECT_EQ(d.bytes_received(), 0);
11568 }
11569}
11570
mmenke9f2ec60c2015-06-01 20:59:4711571TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5511572 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111573
[email protected]8b8a197d2009-08-26 15:57:5811574 TestDelegate d;
11575 // Set correct login credentials. The delegate will be asked for them when
11576 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811577 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811578 {
Ryan Sleevib8449e02018-07-15 04:31:0711579 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511580 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11581 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611582 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911583 r->Start();
11584 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811585
Wez2a31b222018-06-07 22:07:1511586 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5811587
[email protected]f7022f32014-08-21 16:32:1911588 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811589 EXPECT_EQ(1, d.response_started_count());
11590 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711591 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811592 }
11593}
11594
mmenke9f2ec60c2015-06-01 20:59:4711595TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5511596 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111597
[email protected]dd265012009-01-08 20:45:2711598 TestDelegate d;
11599 {
Ryan Sleevib8449e02018-07-15 04:31:0711600 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511601 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
11602 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611603 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911604 r->Start();
11605 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711606
Wez2a31b222018-06-07 22:07:1511607 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711608
[email protected]f7022f32014-08-21 16:32:1911609 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711610 EXPECT_EQ(1, d.response_started_count());
11611 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711612 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2711613 }
11614}
[email protected]8b8a197d2009-08-26 15:57:5811615
mmenke9f2ec60c2015-06-01 20:59:4711616TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5511617 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111618
[email protected]8b8a197d2009-08-26 15:57:5811619 TestDelegate d;
11620 // Set correct login credentials. The delegate will be asked for them when
11621 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811622 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811623 {
Ryan Sleevib8449e02018-07-15 04:31:0711624 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511625 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
11626 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611627 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911628 r->Start();
11629 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811630
Wez2a31b222018-06-07 22:07:1511631 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5811632
[email protected]f7022f32014-08-21 16:32:1911633 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811634 EXPECT_EQ(1, d.response_started_count());
11635 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711636 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811637 }
11638}
[email protected]60a3df52009-09-22 16:13:2411639
mmenke9f2ec60c2015-06-01 20:59:4711640TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5511641 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111642
danakj8522a25b2016-04-16 00:17:3611643 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2411644 {
11645 // Pass correct login identity in the URL.
Ryan Sleevib8449e02018-07-15 04:31:0711646 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511647 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11648 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611649 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911650 r->Start();
11651 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411652
Wez2a31b222018-06-07 22:07:1511653 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2411654
[email protected]f7022f32014-08-21 16:32:1911655 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411656 EXPECT_EQ(1, d->response_started_count());
11657 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711658 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411659 }
11660
11661 d.reset(new TestDelegate);
11662 {
11663 // This request should use cached identity from previous request.
Ryan Sleevib8449e02018-07-15 04:31:0711664 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611665 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
11666 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911667 r->Start();
11668 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411669
Wez2a31b222018-06-07 22:07:1511670 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2411671
[email protected]f7022f32014-08-21 16:32:1911672 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411673 EXPECT_EQ(1, d->response_started_count());
11674 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711675 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411676 }
11677}
11678
mmenke9f2ec60c2015-06-01 20:59:4711679TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5511680 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111681
danakj8522a25b2016-04-16 00:17:3611682 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2411683 // Set correct login credentials. The delegate will be asked for them when
11684 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811685 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2411686 {
Ryan Sleevib8449e02018-07-15 04:31:0711687 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511688 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11689 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611690 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911691 r->Start();
11692 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411693
Wez2a31b222018-06-07 22:07:1511694 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2411695
[email protected]f7022f32014-08-21 16:32:1911696 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411697 EXPECT_EQ(1, d->response_started_count());
11698 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711699 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411700 }
11701
11702 // Use a new delegate without explicit credentials. The cached ones should be
11703 // used.
11704 d.reset(new TestDelegate);
11705 {
11706 // Don't pass wrong credentials in the URL, they would override valid cached
11707 // ones.
Ryan Sleevib8449e02018-07-15 04:31:0711708 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611709 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
11710 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911711 r->Start();
11712 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411713
Wez2a31b222018-06-07 22:07:1511714 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2411715
[email protected]f7022f32014-08-21 16:32:1911716 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411717 EXPECT_EQ(1, d->response_started_count());
11718 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711719 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411720 }
11721}
ricea3a1c71f2016-06-17 10:05:2611722
11723TEST_F(URLRequestTestFTP, RawBodyBytes) {
11724 ASSERT_TRUE(ftp_test_server_.Start());
11725
11726 TestDelegate d;
11727 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611728 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
11729 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2611730 req->Start();
Wez2a31b222018-06-07 22:07:1511731 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:2611732
11733 EXPECT_EQ(6, req->GetRawBodyBytes());
11734}
11735
brettwa1228ebb2016-10-28 03:51:3411736#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5111737
ttuttlec0c828492015-05-15 01:25:5511738TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
11739 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0711740 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611741 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5511742
11743 EXPECT_FALSE(req->response_info().network_accessed);
11744
11745 req->Start();
Wez2a31b222018-06-07 22:07:1511746 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5511747
11748 EXPECT_EQ(1, default_network_delegate_.completed_requests());
11749 EXPECT_FALSE(req->response_info().network_accessed);
11750}
11751
11752TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
11753 MockHostResolver host_resolver;
11754 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
11755 TestURLRequestContext context(true);
11756 context.set_network_delegate(&network_delegate);
11757 context.set_host_resolver(&host_resolver);
11758 host_resolver.rules()->AddSimulatedFailure("*");
11759 context.Init();
11760
11761 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1611762 std::unique_ptr<URLRequest> req(
11763 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
11764 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5511765
11766 EXPECT_FALSE(req->response_info().network_accessed);
11767
11768 req->Start();
Wez2a31b222018-06-07 22:07:1511769 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5511770 EXPECT_TRUE(req->response_info().network_accessed);
11771}
11772
mmenkeed0498b2015-12-08 23:20:4211773// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2211774// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4211775TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2211776 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0711777 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611778 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
11779 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2211780
danakj8522a25b2016-04-16 00:17:3611781 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2211782 req.get(), &default_network_delegate_,
11783 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4211784 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
11785 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2211786
11787 req->Start();
11788 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2211789 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5011790 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2211791 EXPECT_EQ(0, d.received_redirect_count());
11792}
11793
Andrey Kosyakov2e893e62017-08-31 17:00:5211794TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411795 ASSERT_TRUE(http_test_server()->Start());
11796 TestURLRequestContext context;
11797 GURL url(http_test_server()->GetURL("/cachetime"));
11798 TestDelegate delegate;
11799 HttpRequestHeaders extra_headers;
11800 extra_headers.SetHeader("X-Foo", "bar");
11801
11802 {
Andrey Kosyakov2e893e62017-08-31 17:00:5211803 HttpRawRequestHeaders raw_req_headers;
11804 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
11805
Andrey Kosyakov83a6eee2017-08-14 19:20:0411806 std::unique_ptr<URLRequest> r(context.CreateRequest(
11807 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11808 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5211809 r->SetRequestHeadersCallback(base::Bind(
11810 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
11811 r->SetResponseHeadersCallback(base::Bind(
11812 [](scoped_refptr<const HttpResponseHeaders>* left,
11813 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
11814 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411815 r->Start();
11816 while (!delegate.response_started_count())
11817 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5211818 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411819 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5211820 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411821 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211822 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411823 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211824 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
11825 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
11826 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
11827 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411828 }
11829 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411830 std::unique_ptr<URLRequest> r(context.CreateRequest(
11831 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11832 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5211833 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411834 FAIL() << "Callback should not be called unless request is sent";
11835 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5211836 r->SetResponseHeadersCallback(
11837 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
11838 FAIL() << "Callback should not be called unless request is sent";
11839 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411840 r->Start();
Wez2a31b222018-06-07 22:07:1511841 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0411842 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411843 }
11844}
11845
Andrey Kosyakov2e893e62017-08-31 17:00:5211846TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411847 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5211848 HttpRawRequestHeaders raw_req_headers;
11849 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
11850
Andrey Kosyakov83a6eee2017-08-14 19:20:0411851 TestURLRequestContext context;
11852 TestDelegate delegate;
11853 HttpRequestHeaders extra_headers;
11854 extra_headers.SetHeader("X-Foo", "bar");
Andrey Kosyakov83a6eee2017-08-14 19:20:0411855 GURL url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:0711856 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0411857 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11858 r->SetExtraRequestHeaders(extra_headers);
11859 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5211860 base::Unretained(&raw_req_headers)));
11861 r->SetResponseHeadersCallback(base::Bind(
11862 [](scoped_refptr<const HttpResponseHeaders>* left,
11863 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
11864 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411865 r->Start();
Wez0e717112018-06-18 23:09:2211866 delegate.RunUntilRedirect();
Andrey Kosyakov83a6eee2017-08-14 19:20:0411867
11868 ASSERT_EQ(1, delegate.received_redirect_count());
11869 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5211870 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411871 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211872 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411873 EXPECT_EQ("gzip, deflate", value);
11874 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5211875 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
11876 raw_req_headers.request_line());
11877 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
11878 EXPECT_EQ(302, raw_resp_headers->response_code());
11879 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411880
Andrey Kosyakov2e893e62017-08-31 17:00:5211881 raw_req_headers = HttpRawRequestHeaders();
11882 raw_resp_headers = nullptr;
Arthur Sonzognib8465ff72019-01-04 18:44:3511883 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
11884 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:1511885 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5211886 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411887 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211888 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411889 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211890 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
11891 raw_req_headers.request_line());
11892 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411893}
11894
Andrey Kosyakov2e893e62017-08-31 17:00:5211895TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411896 TestDelegate request_delegate;
11897
Ryan Sleevib8449e02018-07-15 04:31:0711898 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0411899 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
11900 TRAFFIC_ANNOTATION_FOR_TESTS));
11901 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
11902 FAIL() << "Callback should not be called unless request is sent";
11903 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5211904 r->SetResponseHeadersCallback(
11905 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
11906 FAIL() << "Callback should not be called unless request is sent";
11907 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411908 r->Start();
Wez2a31b222018-06-07 22:07:1511909 request_delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0411910 EXPECT_FALSE(r->is_pending());
11911}
11912
Andrey Kosyakov2e893e62017-08-31 17:00:5211913TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411914 ASSERT_TRUE(http_test_server()->Start());
11915 GURL url(http_test_server()->GetURL("/auth-basic"));
11916
11917 TestURLRequestContext context;
11918 TestDelegate delegate;
11919
11920 delegate.set_credentials(AuthCredentials(kUser, kSecret));
11921 HttpRequestHeaders extra_headers;
11922 extra_headers.SetHeader("X-Foo", "bar");
11923
Andrey Kosyakov2e893e62017-08-31 17:00:5211924 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
11925 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0411926
Andrey Kosyakov2e893e62017-08-31 17:00:5211927 using RespHeadersVector =
11928 std::vector<scoped_refptr<const HttpResponseHeaders>>;
11929 RespHeadersVector raw_resp_headers;
11930
11931 auto req_headers_callback = base::Bind(
11932 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
11933 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
11934 },
11935 &raw_req_headers);
11936 auto resp_headers_callback = base::Bind(
11937 [](RespHeadersVector* vec,
11938 scoped_refptr<const HttpResponseHeaders> headers) {
11939 vec->push_back(headers);
11940 },
11941 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0411942 std::unique_ptr<URLRequest> r(context.CreateRequest(
11943 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11944 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5211945 r->SetRequestHeadersCallback(req_headers_callback);
11946 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0411947 r->Start();
Wez2a31b222018-06-07 22:07:1511948 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0411949 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5211950 ASSERT_EQ(raw_req_headers.size(), 2u);
11951 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0411952 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5211953 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
11954 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411955 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211956 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
11957 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411958 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211959 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
11960 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
11961 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
11962 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
11963
11964 std::unique_ptr<URLRequest> r2(context.CreateRequest(
11965 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11966 r2->SetExtraRequestHeaders(extra_headers);
11967 r2->SetRequestHeadersCallback(req_headers_callback);
11968 r2->SetResponseHeadersCallback(resp_headers_callback);
11969 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
11970 r2->Start();
Wez2a31b222018-06-07 22:07:1511971 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5211972 EXPECT_FALSE(r2->is_pending());
11973 ASSERT_EQ(raw_req_headers.size(), 3u);
11974 ASSERT_EQ(raw_resp_headers.size(), 3u);
11975 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
11976 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
11977 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
11978 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411979}
11980
Andrey Kosyakov2e893e62017-08-31 17:00:5211981TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411982 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
11983 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0711984 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0411985 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11986 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5211987 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0411988 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5211989 r->SetResponseHeadersCallback(
11990 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
11991 FAIL() << "Callback should not be called for non-HTTP schemes";
11992 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411993 r->Start();
Wez2a31b222018-06-07 22:07:1511994 d.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0411995 EXPECT_FALSE(r->is_pending());
11996}
11997
Carlos ILaef65d62018-06-04 21:24:1311998TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
11999 TestDelegate d;
12000 BlockingNetworkDelegate network_delegate(
12001 BlockingNetworkDelegate::SYNCHRONOUS);
12002 const GURL kOriginalUrl("https://original.test");
12003 const GURL kRedirectUrl("http://redirect.test");
12004 network_delegate.set_redirect_url(kRedirectUrl);
12005 TestURLRequestContext context(true /* delay_initialization */);
12006 context.set_network_delegate(&network_delegate);
12007 context.Init();
12008
12009 std::unique_ptr<URLRequest> r(context.CreateRequest(
12010 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12011 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312012 r->Start();
Wez0e717112018-06-18 23:09:2212013 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312014 GURL::Replacements replacements;
12015 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12016 // was set.
12017 replacements.SetSchemeStr("https");
12018 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12019 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412020 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312021}
12022
12023TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
12024 TestDelegate d;
12025 BlockingNetworkDelegate network_delegate(
12026 BlockingNetworkDelegate::SYNCHRONOUS);
12027 const GURL kOriginalUrl("https://original.test");
12028 const GURL kRedirectUrl("http://redirect.test:80");
12029 network_delegate.set_redirect_url(kRedirectUrl);
12030 TestURLRequestContext context(true /* delay_initialization */);
12031 context.set_network_delegate(&network_delegate);
12032 context.Init();
12033
12034 std::unique_ptr<URLRequest> r(context.CreateRequest(
12035 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12036 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312037 r->Start();
Wez0e717112018-06-18 23:09:2212038 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312039 GURL::Replacements replacements;
12040 // The URL host should have not been changed.
12041 EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
12042 // The scheme should now be https, and the effective port should now be 443.
12043 EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
12044 EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
Carlos IL0d67fc72018-06-22 17:18:4412045 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312046}
12047
12048TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
12049 TestDelegate d;
12050 BlockingNetworkDelegate network_delegate(
12051 BlockingNetworkDelegate::SYNCHRONOUS);
12052 const GURL kOriginalUrl("https://original.test");
12053 const GURL kRedirectUrl("http://redirect.test:1234");
12054 network_delegate.set_redirect_url(kRedirectUrl);
12055 TestURLRequestContext context(true /* delay_initialization */);
12056 context.set_network_delegate(&network_delegate);
12057 context.Init();
12058
12059 std::unique_ptr<URLRequest> r(context.CreateRequest(
12060 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12061 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312062 r->Start();
Wez0e717112018-06-18 23:09:2212063 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312064 GURL::Replacements replacements;
12065 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12066 // was set, nonstandard port should not have been modified.
12067 replacements.SetSchemeStr("https");
12068 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12069 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412070 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312071}
12072
12073TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
12074 TestDelegate d;
12075 BlockingNetworkDelegate network_delegate(
12076 BlockingNetworkDelegate::SYNCHRONOUS);
12077 const GURL kOriginalUrl("https://original.test");
12078 const GURL kRedirectUrl("http://redirect.test");
12079 network_delegate.set_redirect_url(kRedirectUrl);
12080 TestURLRequestContext context(true /* delay_initialization */);
12081 context.set_network_delegate(&network_delegate);
12082 context.Init();
12083 std::unique_ptr<URLRequest> r(context.CreateRequest(
12084 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12085 r->set_upgrade_if_insecure(false);
Carlos ILaef65d62018-06-04 21:24:1312086 r->Start();
Wez0e717112018-06-18 23:09:2212087 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312088 // The redirect URL should not be changed if the upgrade_if_insecure flag is
12089 // not set.
12090 EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412091 EXPECT_FALSE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312092}
12093
Paul Jensen60e45532018-02-19 16:04:1812094// Test that URLRequests get properly tagged.
12095#if defined(OS_ANDROID)
12096TEST_F(URLRequestTestHTTP, TestTagging) {
12097 ASSERT_TRUE(http_test_server()->Start());
12098
12099 // The tag under which the system reports untagged traffic.
12100 static const int32_t UNTAGGED_TAG = 0;
12101
12102 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
12103
12104 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
12105 TestDelegate delegate;
Ryan Sleevib8449e02018-07-15 04:31:0712106 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Paul Jensen60e45532018-02-19 16:04:1812107 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
12108 TRAFFIC_ANNOTATION_FOR_TESTS));
12109 EXPECT_EQ(SocketTag(), req->socket_tag());
12110 req->Start();
Wez2a31b222018-06-07 22:07:1512111 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812112
12113 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
12114
12115 int32_t tag_val1 = 0x12345678;
12116 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
12117 old_traffic = GetTaggedBytes(tag_val1);
12118
12119 // Test specific tag value.
Ryan Sleevib8449e02018-07-15 04:31:0712120 req = default_context().CreateRequest(http_test_server()->GetURL("/"),
12121 DEFAULT_PRIORITY, &delegate,
12122 TRAFFIC_ANNOTATION_FOR_TESTS);
Paul Jensen60e45532018-02-19 16:04:1812123 req->set_socket_tag(tag1);
12124 EXPECT_EQ(tag1, req->socket_tag());
12125 req->Start();
Wez2a31b222018-06-07 22:07:1512126 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812127
12128 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
12129}
12130#endif
12131
[email protected]7461a402011-03-24 23:19:5112132} // namespace net