blob: eb1c015725c4d7094308418e9ec85fbfbefaf0c8 [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"
Aaron Tagliaboschi028009e2019-03-07 16:28:0656#include "net/base/layered_network_delegate.h"
initial.commit586acc5fe2008-07-26 22:42:5257#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2558#include "net/base/load_timing_info.h"
59#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0660#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5261#include "net/base/net_module.h"
Lily Houghton582d4622018-01-22 22:43:4062#include "net/base/proxy_server.h"
[email protected]2ca01e52013-10-31 22:05:1963#include "net/base/request_priority.h"
zhongyi18ddddd2017-02-03 19:06:3664#include "net/base/test_completion_callback.h"
[email protected]f288ef02012-12-15 20:28:2865#include "net/base/upload_bytes_element_reader.h"
66#include "net/base/upload_data_stream.h"
67#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4468#include "net/base/url_util.h"
Ryan Sleevib369d712018-08-20 16:43:2269#include "net/cert/crl_set.h"
rsleevid6de8302016-06-21 01:33:2070#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4771#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3672#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1173#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2474#include "net/cert/mock_cert_verifier.h"
zhongyi18ddddd2017-02-03 19:06:3675#include "net/cert/multi_log_ct_verifier.h"
eranmdcec9632016-10-10 14:16:1076#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1177#include "net/cert/test_root_certs.h"
[email protected]aa84a7e2012-03-15 21:29:0678#include "net/cookies/cookie_monster.h"
79#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5280#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5381#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3882#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5283#include "net/http/http_cache.h"
84#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1985#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2586#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2187#include "net/http/http_response_headers.h"
zhongyi18ddddd2017-02-03 19:06:3688#include "net/http/http_server_properties_impl.h"
[email protected]e50efea2014-03-24 18:41:0089#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0090#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1991#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5192#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4693#include "net/log/test_net_log_entry.h"
94#include "net/log/test_net_log_util.h"
Scott Violet0caaaf432018-03-24 00:43:5995#include "net/net_buildflags.h"
Lily Houghtonffe89daa02018-03-09 18:30:0396#include "net/proxy_resolution/proxy_resolution_service.h"
Ryan Hamiltona3ee93a72018-08-01 22:03:0897#include "net/quic/mock_crypto_client_stream_factory.h"
98#include "net/quic/quic_server_info.h"
zhongyi18ddddd2017-02-03 19:06:3699#include "net/socket/socket_test_util.h"
[email protected]c3456bb2011-12-12 22:22:19100#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:14101#include "net/ssl/channel_id_service.h"
David Benjamin76a40ad2018-02-24 22:22:08102#include "net/ssl/client_cert_identity_test_util.h"
nharperb7441ef2016-01-25 23:54:14103#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:57104#include "net/ssl/ssl_connection_status_flags.h"
David Benjamin76a40ad2018-02-24 22:22:08105#include "net/ssl/ssl_private_key.h"
tommycli59a63432015-11-06 00:10:55106#include "net/ssl/ssl_server_config.h"
[email protected]6e7845ae2013-03-29 21:48:11107#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:36108#include "net/test/embedded_test_server/embedded_test_server.h"
109#include "net/test/embedded_test_server/http_request.h"
110#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:01111#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21112#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43113#include "net/test/test_data_directory.h"
Bence Béky98447b12018-05-08 03:14:01114#include "net/test/test_with_scoped_task_environment.h"
mmenkefb18c772015-09-30 22:22:50115#include "net/test/url_request/url_request_failed_job.h"
Carlos ILaef65d62018-06-04 21:24:13116#include "net/test/url_request/url_request_mock_http_job.h"
rhalavatib7bd7c792017-04-27 05:25:16117#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34118#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43119#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52120#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50121#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14122#include "net/url_request/url_request_http_job.h"
Thiemo Nagel0793b9c532018-04-18 16:57:58123#include "net/url_request/url_request_http_job_histogram.h"
bengr1bf8e942014-11-07 01:36:50124#include "net/url_request/url_request_intercepting_job_factory.h"
125#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49126#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51127#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47128#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44129#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01130#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52131#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15132#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52133
Eric Romanefddd0a2017-10-10 02:14:25134#if defined(OS_FUCHSIA)
135#define USE_BUILTIN_CERT_VERIFIER
136#endif
137
brettwa1228ebb2016-10-28 03:51:34138#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55139#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29140#include "net/url_request/file_protocol_handler.h"
141#include "net/url_request/url_request_file_dir_job.h"
142#endif
143
brettwa1228ebb2016-10-28 03:51:34144#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47145#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29146#include "net/url_request/ftp_protocol_handler.h"
147#endif
148
[email protected]dffe8242012-03-20 15:14:27149#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48150#include "base/win/scoped_com_initializer.h"
[email protected]dffe8242012-03-20 15:14:27151#endif
152
mmenkefd9d15c2017-06-29 13:45:54153#if BUILDFLAG(ENABLE_REPORTING)
Julia Tuttlecba7d222018-02-23 19:37:27154#include "net/network_error_logging/network_error_logging_service.h"
Lily Chenfec60d92019-01-24 01:16:42155#include "net/network_error_logging/network_error_logging_test_util.h"
mmenkefd9d15c2017-06-29 13:45:54156#endif // BUILDFLAG(ENABLE_REPORTING)
157
Matt Muellerfb271992018-01-30 18:10:48158#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:25159#include "net/cert/cert_net_fetcher.h"
160#include "net/cert_net/cert_net_fetcher_impl.h"
161#endif
162
163#if defined(USE_NSS_CERTS)
164#include "net/cert_net/nss_ocsp.h"
165#endif
166
robpercival214763f2016-07-01 23:27:01167using net::test::IsError;
168using net::test::IsOk;
169
[email protected]ad65a3e2013-12-25 18:18:01170using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33171using base::Time;
halton.huoe4e45742014-12-08 07:55:46172using std::string;
[email protected]e1acf6f2008-10-27 20:43:33173
[email protected]7461a402011-03-24 23:19:51174namespace net {
175
initial.commit586acc5fe2008-07-26 22:42:52176namespace {
177
Martijn Croonenb1383da2017-10-11 11:56:35178namespace test_default {
179#include "net/http/transport_security_state_static_unittest_default.h"
xunjieli815ad5b2017-07-18 15:51:35180}
181
[email protected]42cba2fb2013-03-29 19:58:57182const base::string16 kChrome(ASCIIToUTF16("chrome"));
183const base::string16 kSecret(ASCIIToUTF16("secret"));
184const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44185
mmenke9f2ec60c2015-06-01 20:59:47186const base::FilePath::CharType kTestFilePath[] =
187 FILE_PATH_LITERAL("net/data/url_request_unittest");
188
Sergey Ulanovc4580e72017-09-13 23:30:11189#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
190 !defined(OS_FUCHSIA)
mmenke9f2ec60c2015-06-01 20:59:47191// Test file used in most FTP tests.
192const char kFtpTestFile[] = "BullRunSpeech.txt";
193#endif
194
[email protected]2bba3252013-04-08 19:50:59195// Tests load timing information in the case a fresh connection was used, with
196// no proxy.
[email protected]cba24642014-08-15 20:49:59197void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25198 int connect_timing_flags) {
199 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19200 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25201
202 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
203 EXPECT_FALSE(load_timing_info.request_start.is_null());
204
205 EXPECT_LE(load_timing_info.request_start,
206 load_timing_info.connect_timing.connect_start);
207 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
208 connect_timing_flags);
209 EXPECT_LE(load_timing_info.connect_timing.connect_end,
210 load_timing_info.send_start);
211 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38212 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
213 EXPECT_LE(load_timing_info.receive_headers_start,
214 load_timing_info.receive_headers_end);
[email protected]58e32bb2013-01-21 18:23:25215
[email protected]58e32bb2013-01-21 18:23:25216 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
217 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
218}
219
[email protected]2bba3252013-04-08 19:50:59220// Same as above, but with proxy times.
221void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59222 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59223 int connect_timing_flags) {
224 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19225 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59226
227 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
228 EXPECT_FALSE(load_timing_info.request_start.is_null());
229
230 EXPECT_LE(load_timing_info.request_start,
231 load_timing_info.proxy_resolve_start);
232 EXPECT_LE(load_timing_info.proxy_resolve_start,
233 load_timing_info.proxy_resolve_end);
234 EXPECT_LE(load_timing_info.proxy_resolve_end,
235 load_timing_info.connect_timing.connect_start);
236 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
237 connect_timing_flags);
238 EXPECT_LE(load_timing_info.connect_timing.connect_end,
239 load_timing_info.send_start);
240 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38241 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
242 EXPECT_LE(load_timing_info.receive_headers_start,
243 load_timing_info.receive_headers_end);
[email protected]2bba3252013-04-08 19:50:59244}
245
246// Same as above, but with a reused socket and proxy times.
247void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59248 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59249 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19250 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59251
252 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
253 EXPECT_FALSE(load_timing_info.request_start.is_null());
254
255 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
256
257 EXPECT_LE(load_timing_info.request_start,
258 load_timing_info.proxy_resolve_start);
259 EXPECT_LE(load_timing_info.proxy_resolve_start,
260 load_timing_info.proxy_resolve_end);
261 EXPECT_LE(load_timing_info.proxy_resolve_end,
262 load_timing_info.send_start);
263 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38264 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
265 EXPECT_LE(load_timing_info.receive_headers_start,
266 load_timing_info.receive_headers_end);
[email protected]2bba3252013-04-08 19:50:59267}
268
brettwa1228ebb2016-10-28 03:51:34269#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25270// Tests load timing information in the case of a cache hit, when no cache
271// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17272base::StringPiece TestNetResourceProvider(int key) {
273 return "header";
274}
275
276void FillBuffer(char* buffer, size_t len) {
277 static bool called = false;
278 if (!called) {
279 called = true;
280 int seed = static_cast<int>(Time::Now().ToInternalValue());
281 srand(seed);
282 }
283
284 for (size_t i = 0; i < len; i++) {
285 buffer[i] = static_cast<char>(rand());
286 if (!buffer[i])
287 buffer[i] = 'g';
288 }
289}
xunjielia6888202015-04-14 21:34:25290#endif
[email protected]e3a85452013-11-14 01:46:17291
[email protected]3b23a222013-05-15 21:33:25292void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59293 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25294 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19295 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25296
297 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
298 EXPECT_FALSE(load_timing_info.request_start.is_null());
299
300 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
301 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
302 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38303 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
304 EXPECT_LE(load_timing_info.receive_headers_start,
305 load_timing_info.receive_headers_end);
[email protected]3b23a222013-05-15 21:33:25306
307 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
308 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
309}
310
Sergey Ulanovc4580e72017-09-13 23:30:11311#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
312 !defined(OS_FUCHSIA)
[email protected]3b23a222013-05-15 21:33:25313// Tests load timing in the case that there is no HTTP response. This can be
314// used to test in the case of errors or non-HTTP requests.
315void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59316 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25317 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19318 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25319
320 // Only the request times should be non-null.
321 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
322 EXPECT_FALSE(load_timing_info.request_start.is_null());
323
324 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
325
326 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
327 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
328 EXPECT_TRUE(load_timing_info.send_start.is_null());
329 EXPECT_TRUE(load_timing_info.send_end.is_null());
Andrew Comminos1f2ff1cc2018-12-14 05:22:38330 EXPECT_TRUE(load_timing_info.receive_headers_start.is_null());
[email protected]58e32bb2013-01-21 18:23:25331 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
332}
xunjielia6888202015-04-14 21:34:25333#endif
[email protected]58e32bb2013-01-21 18:23:25334
mmenkefb18c772015-09-30 22:22:50335// Test power monitor source that can simulate entering suspend mode. Can't use
336// the one in base/ because it insists on bringing its own MessageLoop.
337class TestPowerMonitorSource : public base::PowerMonitorSource {
338 public:
Chris Watkins7a41d3552017-12-01 02:13:27339 TestPowerMonitorSource() = default;
340 ~TestPowerMonitorSource() override = default;
mmenkefb18c772015-09-30 22:22:50341
Colin Blundellc46597f2018-06-14 16:43:10342 void Shutdown() override {}
343
mmenkefb18c772015-09-30 22:22:50344 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
345
346 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
347
348 bool IsOnBatteryPowerImpl() override { return false; }
349
350 private:
351 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
352};
353
mmenkeed0498b2015-12-08 23:20:42354// Job that allows monitoring of its priority.
355class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
356 public:
357 // The latest priority of the job is always written to |request_priority_|.
358 PriorityMonitoringURLRequestJob(URLRequest* request,
359 NetworkDelegate* network_delegate,
360 RequestPriority* request_priority)
361 : URLRequestTestJob(request, network_delegate),
362 request_priority_(request_priority) {
363 *request_priority_ = DEFAULT_PRIORITY;
364 }
365
366 void SetPriority(RequestPriority priority) override {
367 *request_priority_ = priority;
368 URLRequestTestJob::SetPriority(priority);
369 }
370
371 private:
372 RequestPriority* const request_priority_;
373};
374
[email protected]71c64f62008-11-15 04:36:51375// Do a case-insensitive search through |haystack| for |needle|.
376bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50377 std::string::const_iterator it = std::search(
378 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
379 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51380 return it != haystack.end();
381}
382
danakj8522a25b2016-04-16 00:17:36383std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
384 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28385 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48386 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23387}
388
[email protected]96adadb2010-08-28 01:16:17389// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51390void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17391 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14392 uint16_t cipher_suite =
393 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29394 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17395}
396
[email protected]79e1fd62013-06-20 06:50:04397void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
398 const GURL& host_url) {
399 std::string sent_value;
400
401 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
402 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
403
404 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
405 EXPECT_EQ("keep-alive", sent_value);
406}
407
[email protected]dc5a5cf2012-09-26 02:49:30408// A network delegate that allows the user to choose a subset of request stages
409// to block in. When blocking, the delegate can do one of the following:
410// * synchronously return a pre-specified error code, or
411// * asynchronously return that value via an automatically called callback,
412// or
413// * block and wait for the user to do a callback.
414// Additionally, the user may also specify a redirect URL -- then each request
415// with the current URL different from the redirect target will be redirected
416// to that target, in the on-before-URL-request stage, independent of whether
417// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12418class BlockingNetworkDelegate : public TestNetworkDelegate {
419 public:
[email protected]dc5a5cf2012-09-26 02:49:30420 // Stages in which the delegate can block.
421 enum Stage {
[email protected]9045b8822012-01-13 20:35:35422 NOT_BLOCKED = 0,
423 ON_BEFORE_URL_REQUEST = 1 << 0,
424 ON_BEFORE_SEND_HEADERS = 1 << 1,
425 ON_HEADERS_RECEIVED = 1 << 2,
426 ON_AUTH_REQUIRED = 1 << 3
427 };
428
[email protected]dc5a5cf2012-09-26 02:49:30429 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59430 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30431 enum BlockMode {
432 SYNCHRONOUS, // No callback, returns specified return values.
433 AUTO_CALLBACK, // |this| posts a task to run the callback using the
434 // specified return codes.
435 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
436 // |auth_retval_| are ignored. In every blocking stage the
437 // message loop is quit.
438 };
439
440 // Creates a delegate which does not block at all.
441 explicit BlockingNetworkDelegate(BlockMode block_mode);
442
Wez2a31b222018-06-07 22:07:15443 // Runs the message loop until the delegate blocks.
444 void RunUntilBlocked();
445
[email protected]dc5a5cf2012-09-26 02:49:30446 // For users to trigger a callback returning |response|.
447 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
448 // Only call if |block_mode_| == USER_CALLBACK.
449 void DoCallback(int response);
450 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
451
452 // Setters.
453 void set_retval(int retval) {
454 ASSERT_NE(USER_CALLBACK, block_mode_);
455 ASSERT_NE(ERR_IO_PENDING, retval);
456 ASSERT_NE(OK, retval);
457 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35458 }
459
[email protected]dc5a5cf2012-09-26 02:49:30460 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
461 // |auth_credentials_| will be passed with the response.
462 void set_auth_retval(AuthRequiredResponse auth_retval) {
463 ASSERT_NE(USER_CALLBACK, block_mode_);
464 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
465 auth_retval_ = auth_retval;
466 }
467 void set_auth_credentials(const AuthCredentials& auth_credentials) {
468 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35469 }
470
[email protected]dc5a5cf2012-09-26 02:49:30471 void set_redirect_url(const GURL& url) {
472 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35473 }
474
[email protected]dc5a5cf2012-09-26 02:49:30475 void set_block_on(int block_on) {
476 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35477 }
478
[email protected]dc5a5cf2012-09-26 02:49:30479 // Allows the user to check in which state did we block.
480 Stage stage_blocked_for_callback() const {
481 EXPECT_EQ(USER_CALLBACK, block_mode_);
482 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35483 }
484
485 private:
Wez2a31b222018-06-07 22:07:15486 void OnBlocked();
487
David Benjamind1f287bf2018-06-12 01:57:20488 void RunCallback(int response, CompletionOnceCallback callback);
489 void RunAuthCallback(AuthRequiredResponse response, AuthCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30490
[email protected]9045b8822012-01-13 20:35:35491 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20492 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20493 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:20494 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35495
ryansturm2343cb62016-06-15 01:09:00496 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20497 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:00498 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35499
dchengb03027d2014-10-21 12:00:20500 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35501 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20502 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32503 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16504 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13505 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35506
dchengb03027d2014-10-21 12:00:20507 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35508 URLRequest* request,
509 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20510 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:13511 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35512
[email protected]dc5a5cf2012-09-26 02:49:30513 // Resets the callbacks and |stage_blocked_for_callback_|.
514 void Reset();
[email protected]9045b8822012-01-13 20:35:35515
[email protected]dc5a5cf2012-09-26 02:49:30516 // Checks whether we should block in |stage|. If yes, returns an error code
517 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
David Benjamind1f287bf2018-06-12 01:57:20518 int MaybeBlockStage(Stage stage, CompletionOnceCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30519
520 // Configuration parameters, can be adjusted by public methods:
521 const BlockMode block_mode_;
522
523 // Values returned on blocking stages when mode is SYNCHRONOUS or
524 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
525 int retval_; // To be returned in non-auth stages.
526 AuthRequiredResponse auth_retval_;
527
[email protected]5f714132014-03-26 10:41:16528 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30529 int block_on_; // Bit mask: in which stages to block.
530
531 // |auth_credentials_| will be copied to |*target_auth_credential_| on
532 // callback.
533 AuthCredentials auth_credentials_;
534 AuthCredentials* target_auth_credentials_;
535
536 // Internal variables, not set by not the user:
537 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
538 // USER_CALLBACK).
539 Stage stage_blocked_for_callback_;
540
541 // Callback objects stored during blocking stages.
David Benjamind1f287bf2018-06-12 01:57:20542 CompletionOnceCallback callback_;
[email protected]9045b8822012-01-13 20:35:35543 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30544
Wez2a31b222018-06-07 22:07:15545 // Closure to run to exit RunUntilBlocked().
546 base::OnceClosure on_blocked_;
547
[email protected]dc5a5cf2012-09-26 02:49:30548 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
549
550 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35551};
552
[email protected]dc5a5cf2012-09-26 02:49:30553BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
554 : block_mode_(block_mode),
555 retval_(OK),
556 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
557 block_on_(0),
Raul Tambre94493c652019-03-11 17:18:35558 target_auth_credentials_(nullptr),
[email protected]dc5a5cf2012-09-26 02:49:30559 stage_blocked_for_callback_(NOT_BLOCKED),
Raul Tambre94493c652019-03-11 17:18:35560 weak_factory_(this) {}
[email protected]dc5a5cf2012-09-26 02:49:30561
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) {
Raul Tambre94493c652019-03-11 17:18:35607 ASSERT_TRUE(target_auth_credentials_ != nullptr);
[email protected]dc5a5cf2012-09-26 02:49:30608 *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;
satoruxddac0442017-05-29 06:06:18895
896 // Adds |directory| to the access white list.
897 void AddToWhitelist(const base::FilePath& directory) {
898 whitelist_.insert(directory);
899 }
900
901 private:
902 // Returns true if |path| matches the white list.
903 bool OnCanAccessFileInternal(const base::FilePath& path) const {
904 for (const auto& directory : whitelist_) {
905 if (directory == path || directory.IsParent(path))
906 return true;
907 }
908 return false;
909 }
910
911 // Returns true only if both |original_path| and |absolute_path| match the
912 // white list.
913 bool OnCanAccessFile(const URLRequest& request,
914 const base::FilePath& original_path,
915 const base::FilePath& absolute_path) const override {
916 return (OnCanAccessFileInternal(original_path) &&
917 OnCanAccessFileInternal(absolute_path));
918 }
919
920 std::set<base::FilePath> whitelist_;
921
922 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
923};
924
[email protected]316c1e5e2012-09-12 15:17:44925TEST_F(URLRequestTest, AboutBlankTest) {
926 TestDelegate d;
927 {
rhalavatib7bd7c792017-04-27 05:25:16928 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:07929 default_context().CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
930 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44931
[email protected]f7022f32014-08-21 16:32:19932 r->Start();
933 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44934
Wez2a31b222018-06-07 22:07:15935 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44936
[email protected]f7022f32014-08-21 16:32:19937 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44938 EXPECT_FALSE(d.received_data_before_response());
939 EXPECT_EQ(d.bytes_received(), 0);
Tsuyoshi Horo01faed62019-02-20 22:11:37940 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
941 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04942
943 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19944 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44945 }
946}
947
948TEST_F(URLRequestTest, DataURLImageTest) {
949 TestDelegate d;
950 {
951 // Use our nice little Chrome logo.
Ryan Sleevib8449e02018-07-15 04:31:07952 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
danakj8522a25b2016-04-16 00:17:36953 GURL("data:image/png;base64,"
954 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
955 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
956 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
957 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
958 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
959 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
960 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
961 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
962 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
963 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
964 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
965 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
966 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
967 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
968 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
969 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
970 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
971 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
972 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16973 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44974
[email protected]f7022f32014-08-21 16:32:19975 r->Start();
976 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44977
Wez2a31b222018-06-07 22:07:15978 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44979
[email protected]f7022f32014-08-21 16:32:19980 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44981 EXPECT_FALSE(d.received_data_before_response());
982 EXPECT_EQ(d.bytes_received(), 911);
Tsuyoshi Horo01faed62019-02-20 22:11:37983 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
984 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04985
986 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19987 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44988 }
989}
990
brettwa1228ebb2016-10-28 03:51:34991#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44992TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51993 const char kTestFileContent[] = "Hello";
994 base::FilePath test_file;
995 ASSERT_NO_FATAL_FAILURE(
996 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04997
Sergey Ulanov2e49f492017-09-14 19:37:51998 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:44999
1000 TestDelegate d;
1001 {
Ryan Sleevib8449e02018-07-15 04:31:071002 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511003 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441004
[email protected]f7022f32014-08-21 16:32:191005 r->Start();
1006 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441007
Wez2a31b222018-06-07 22:07:151008 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441009
[email protected]f7022f32014-08-21 16:32:191010 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441011 EXPECT_EQ(1, d.response_started_count());
1012 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:511013 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
Tsuyoshi Horo01faed62019-02-20 22:11:371014 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
1015 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:041016
1017 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:191018 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:441019 }
1020}
1021
[email protected]ba40bb762012-12-17 07:11:041022TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:511023 const char kTestFileContent[] = "Hello";
1024 base::FilePath test_file;
1025 ASSERT_NO_FATAL_FAILURE(
1026 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
1027
1028 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:041029
1030 TestDelegate d;
1031 {
Ryan Sleevib8449e02018-07-15 04:31:071032 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511033 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:041034
[email protected]f7022f32014-08-21 16:32:191035 r->Start();
1036 EXPECT_TRUE(r->is_pending());
1037 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:041038 }
[email protected]79e1fd62013-06-20 06:50:041039 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:041040 // destroyed.
[email protected]255620da2013-08-19 13:14:291041 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041042}
1043
[email protected]316c1e5e2012-09-12 15:17:441044TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1045 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361046 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441047 FillBuffer(buffer.get(), buffer_size);
1048
Sergey Ulanov2e49f492017-09-14 19:37:511049 base::FilePath test_file;
1050 ASSERT_NO_FATAL_FAILURE(
1051 CreateTestFile(buffer.get(), buffer_size, &test_file));
1052 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441053
1054 const size_t first_byte_position = 500;
1055 const size_t last_byte_position = buffer_size - first_byte_position;
1056 const size_t content_length = last_byte_position - first_byte_position + 1;
1057 std::string partial_buffer_string(buffer.get() + first_byte_position,
1058 buffer.get() + last_byte_position + 1);
1059
1060 TestDelegate d;
1061 {
Ryan Sleevib8449e02018-07-15 04:31:071062 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161063 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441064
1065 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381066 headers.SetHeader(
1067 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591068 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381069 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191070 r->SetExtraRequestHeaders(headers);
1071 r->Start();
1072 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441073
Wez2a31b222018-06-07 22:07:151074 d.RunUntilComplete();
1075
[email protected]f7022f32014-08-21 16:32:191076 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441077 EXPECT_EQ(1, d.response_started_count());
1078 EXPECT_FALSE(d.received_data_before_response());
1079 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1080 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1081 EXPECT_TRUE(partial_buffer_string == d.data_received());
1082 }
[email protected]316c1e5e2012-09-12 15:17:441083}
1084
1085TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1086 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361087 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441088 FillBuffer(buffer.get(), buffer_size);
1089
Sergey Ulanov2e49f492017-09-14 19:37:511090 base::FilePath test_file;
1091 ASSERT_NO_FATAL_FAILURE(
1092 CreateTestFile(buffer.get(), buffer_size, &test_file));
1093 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441094
1095 const size_t first_byte_position = 500;
1096 const size_t last_byte_position = buffer_size - 1;
1097 const size_t content_length = last_byte_position - first_byte_position + 1;
1098 std::string partial_buffer_string(buffer.get() + first_byte_position,
1099 buffer.get() + last_byte_position + 1);
1100
1101 TestDelegate d;
1102 {
Ryan Sleevib8449e02018-07-15 04:31:071103 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161104 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441105
1106 HttpRequestHeaders headers;
1107 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591108 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381109 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191110 r->SetExtraRequestHeaders(headers);
1111 r->Start();
1112 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441113
[email protected]255620da2013-08-19 13:14:291114 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191115 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441116 EXPECT_EQ(1, d.response_started_count());
1117 EXPECT_FALSE(d.received_data_before_response());
1118 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1119 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1120 EXPECT_TRUE(partial_buffer_string == d.data_received());
1121 }
[email protected]316c1e5e2012-09-12 15:17:441122}
1123
1124TEST_F(URLRequestTest, FileTestMultipleRanges) {
1125 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361126 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441127 FillBuffer(buffer.get(), buffer_size);
1128
Sergey Ulanov2e49f492017-09-14 19:37:511129 base::FilePath test_file;
1130 ASSERT_NO_FATAL_FAILURE(
1131 CreateTestFile(buffer.get(), buffer_size, &test_file));
1132 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441133
1134 TestDelegate d;
1135 {
Ryan Sleevib8449e02018-07-15 04:31:071136 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161137 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441138
1139 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381140 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191141 r->SetExtraRequestHeaders(headers);
1142 r->Start();
1143 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441144
Wez2a31b222018-06-07 22:07:151145 d.RunUntilComplete();
1146
[email protected]316c1e5e2012-09-12 15:17:441147 EXPECT_TRUE(d.request_failed());
1148 }
[email protected]316c1e5e2012-09-12 15:17:441149}
1150
[email protected]3ca8b362013-11-11 22:18:071151TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511152 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071153 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511154 ASSERT_NO_FATAL_FAILURE(
1155 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1156
satoruxddac0442017-05-29 06:06:181157 // The directory part of the path returned from CreateTemporaryFileInDir()
1158 // can be slightly different from |absolute_temp_dir| on Windows.
1159 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1160 // Hence the test should use the directory name of |test_file|, rather than
1161 // |absolute_temp_dir|, for whitelisting.
1162 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591163 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071164 {
1165 TestDelegate d;
satoruxddac0442017-05-29 06:06:181166 CookieBlockingNetworkDelegate network_delegate;
1167 network_delegate.AddToWhitelist(real_temp_dir);
Ryan Sleevib8449e02018-07-15 04:31:071168 default_context().set_network_delegate(&network_delegate);
1169 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161170 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191171 r->Start();
Wez2a31b222018-06-07 22:07:151172 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181173 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071174 EXPECT_FALSE(d.request_failed());
1175 EXPECT_EQ(test_data, d.data_received());
1176 }
1177
1178 {
1179 TestDelegate d;
satoruxddac0442017-05-29 06:06:181180 CookieBlockingNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:071181 default_context().set_network_delegate(&network_delegate);
1182 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161183 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191184 r->Start();
Wez2a31b222018-06-07 22:07:151185 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181186 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071187 EXPECT_TRUE(d.request_failed());
1188 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181189 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071190 }
1191}
1192
Wez35539132018-07-17 11:26:051193#if defined(OS_POSIX) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181194
1195TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511196 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181197 // Get an absolute path since temp_dir can contain a symbolic link.
1198 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511199 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181200
1201 // Create a good directory (will be whitelisted) and a good file.
1202 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1203 ASSERT_TRUE(base::CreateDirectory(good_dir));
1204 base::FilePath good_file;
1205 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1206 std::string good_data("good");
1207 base::WriteFile(good_file, good_data.data(), good_data.size());
1208 // See the comment in AllowFileURLs() for why this is done.
1209 base::FilePath real_good_dir = good_file.DirName();
1210
1211 // Create a bad directory (will not be whitelisted) and a bad file.
1212 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1213 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1214 base::FilePath bad_file;
1215 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1216 std::string bad_data("bad");
1217 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1218
1219 // This symlink will point to the good file. Access to the symlink will be
1220 // allowed as both the symlink and the destination file are in the same
1221 // good directory.
1222 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1223 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1224 GURL good_file_url = FilePathToFileURL(good_symlink);
1225 // This symlink will point to the bad file. Even though the symlink is in
1226 // the good directory, access to the symlink will be rejected since it
1227 // points to the bad file.
1228 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1229 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1230 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1231
1232 CookieBlockingNetworkDelegate network_delegate;
1233 network_delegate.AddToWhitelist(real_good_dir);
1234 {
1235 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071236 default_context().set_network_delegate(&network_delegate);
1237 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371238 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181239 r->Start();
Wez2a31b222018-06-07 22:07:151240 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181241 // good_file_url should be allowed.
1242 EXPECT_FALSE(d.request_failed());
1243 EXPECT_EQ(good_data, d.data_received());
1244 }
1245
1246 {
1247 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071248 default_context().set_network_delegate(&network_delegate);
1249 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371250 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181251 r->Start();
Wez2a31b222018-06-07 22:07:151252 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181253 // bad_file_url should be rejected.
1254 EXPECT_TRUE(d.request_failed());
1255 EXPECT_EQ("", d.data_received());
1256 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1257 }
1258}
1259
1260TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511261 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181262 // Get an absolute path since temp_dir can contain a symbolic link.
1263 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511264 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181265
1266 // Create a good directory (will be whitelisted).
1267 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1268 ASSERT_TRUE(base::CreateDirectory(good_dir));
1269
1270 // Create a bad directory (will not be whitelisted).
1271 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1272 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1273
1274 // This symlink will point to the good directory. Access to the symlink
1275 // will be allowed as the symlink is in the good dir that'll be white
1276 // listed.
1277 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1278 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1279 GURL good_file_url = FilePathToFileURL(good_symlink);
1280 // This symlink will point to the bad directory. Even though the symlink is
1281 // in the good directory, access to the symlink will be rejected since it
1282 // points to the bad directory.
1283 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1284 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1285 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1286
1287 CookieBlockingNetworkDelegate network_delegate;
1288 network_delegate.AddToWhitelist(good_dir);
1289 {
1290 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071291 default_context().set_network_delegate(&network_delegate);
1292 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371293 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181294 r->Start();
Wez2a31b222018-06-07 22:07:151295 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181296 // good_file_url should be allowed.
1297 EXPECT_FALSE(d.request_failed());
1298 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1299 }
1300
1301 {
1302 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071303 default_context().set_network_delegate(&network_delegate);
1304 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371305 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181306 r->Start();
Wez2a31b222018-06-07 22:07:151307 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181308 // bad_file_url should be rejected.
1309 EXPECT_TRUE(d.request_failed());
1310 EXPECT_EQ("", d.data_received());
1311 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1312 }
1313}
1314
Wez35539132018-07-17 11:26:051315#endif // defined(OS_POSIX)
[email protected]316c1e5e2012-09-12 15:17:441316
1317TEST_F(URLRequestTest, FileDirCancelTest) {
1318 // Put in mock resource provider.
1319 NetModule::SetResourceProvider(TestNetResourceProvider);
1320
1321 TestDelegate d;
1322 {
[email protected]6cdfd7f2013-02-08 20:40:151323 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:191324 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
[email protected]316c1e5e2012-09-12 15:17:441325 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1326 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1327
Ryan Sleevib8449e02018-07-15 04:31:071328 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161329 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1330 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191331 req->Start();
1332 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441333
1334 d.set_cancel_in_received_data_pending(true);
1335
Wez2a31b222018-06-07 22:07:151336 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441337 }
1338
1339 // Take out mock resource provider.
Raul Tambre94493c652019-03-11 17:18:351340 NetModule::SetResourceProvider(nullptr);
[email protected]316c1e5e2012-09-12 15:17:441341}
1342
[email protected]5f9581402013-10-30 13:08:321343TEST_F(URLRequestTest, FileDirOutputSanity) {
1344 // Verify the general sanity of the the output of the file:
1345 // directory lister by checking for the output of a known existing
1346 // file.
1347 const char sentinel_name[] = "filedir-sentinel";
1348
1349 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191350 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471351 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321352
1353 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161354 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071355 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1356 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191357 req->Start();
Wez2a31b222018-06-07 22:07:151358 d.RunUntilComplete();
[email protected]5f9581402013-10-30 13:08:321359
1360 // Generate entry for the sentinel file.
1361 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581362 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491363 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321364 EXPECT_GT(info.size, 0);
1365 std::string sentinel_output = GetDirectoryListingEntry(
1366 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181367 std::string(sentinel_name), false /* is_dir */, info.size,
1368
[email protected]5f9581402013-10-30 13:08:321369 info.last_modified);
1370
1371 ASSERT_LT(0, d.bytes_received());
1372 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501373 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321374 // Check for the entry generated for the "sentinel" file.
1375 const std::string& data = d.data_received();
1376 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1377}
1378
[email protected]316c1e5e2012-09-12 15:17:441379TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1380 // There is an implicit redirect when loading a file path that matches a
1381 // directory and does not end with a slash. Ensure that following such
1382 // redirects does not crash. See http://crbug.com/18686.
1383
[email protected]6cdfd7f2013-02-08 20:40:151384 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191385 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471386 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441387
1388 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161389 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071390 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1391 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191392 req->Start();
Wez2a31b222018-06-07 22:07:151393 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441394
1395 ASSERT_EQ(1, d.received_redirect_count());
1396 ASSERT_LT(0, d.bytes_received());
1397 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501398 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441399}
1400
1401#if defined(OS_WIN)
1402// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1403TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1404 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071405 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161406 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191407 req->Start();
Wez2a31b222018-06-07 22:07:151408 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441409
1410 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501411 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441412}
[email protected]5ecf7cb282014-05-11 01:49:551413#endif // defined(OS_WIN)
1414
brettwa1228ebb2016-10-28 03:51:341415#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551416
1417TEST_F(URLRequestTest, InvalidUrlTest) {
1418 TestDelegate d;
1419 {
rhalavatib7bd7c792017-04-27 05:25:161420 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:071421 default_context().CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1422 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551423
[email protected]f7022f32014-08-21 16:32:191424 r->Start();
1425 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551426
Wez2a31b222018-06-07 22:07:151427 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551428 EXPECT_TRUE(d.request_failed());
1429 }
1430}
1431
jochen0e3b3a62014-09-16 18:31:231432TEST_F(URLRequestTest, InvalidReferrerTest) {
1433 TestURLRequestContext context;
1434 TestNetworkDelegate network_delegate;
1435 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1436 context.set_network_delegate(&network_delegate);
1437 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361438 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161439 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1440 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231441 req->SetReferrer("https://somewhere.com/");
1442
1443 req->Start();
Wez2a31b222018-06-07 22:07:151444 d.RunUntilComplete();
jochen0e3b3a62014-09-16 18:31:231445 EXPECT_TRUE(d.request_failed());
1446}
1447
[email protected]5ecf7cb282014-05-11 01:49:551448#if defined(OS_WIN)
1449TEST_F(URLRequestTest, ResolveShortcutTest) {
1450 base::FilePath app_path;
Avi Drissman5c80d832018-05-01 17:01:191451 base::PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471452 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551453 app_path = app_path.AppendASCII("with-headers.html");
1454
jdoerrie6312bf62019-02-01 22:03:421455 base::string16 lnk_path = app_path.value() + FILE_PATH_LITERAL(".lnk");
[email protected]5ecf7cb282014-05-11 01:49:551456
1457 base::win::ScopedCOMInitializer com_initializer;
1458
1459 // Temporarily create a shortcut for test
1460 {
Robert Liaoc88f99d12017-10-17 21:48:331461 Microsoft::WRL::ComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161462 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
Raul Tambre94493c652019-03-11 17:18:351463 CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
Robert Liaoc88f99d12017-10-17 21:48:331464 Microsoft::WRL::ComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001465 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
jdoerriebacc1962019-02-07 13:39:221466 EXPECT_TRUE(SUCCEEDED(shell->SetPath(base::as_wcstr(app_path.value()))));
[email protected]5ecf7cb282014-05-11 01:49:551467 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
jdoerriebacc1962019-02-07 13:39:221468 EXPECT_TRUE(SUCCEEDED(persist->Save(base::as_wcstr(lnk_path), TRUE)));
[email protected]5ecf7cb282014-05-11 01:49:551469 }
1470
1471 TestDelegate d;
1472 {
Ryan Sleevib8449e02018-07-15 04:31:071473 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161474 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1475 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551476
[email protected]f7022f32014-08-21 16:32:191477 r->Start();
1478 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551479
Wez2a31b222018-06-07 22:07:151480 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551481
1482 WIN32_FILE_ATTRIBUTE_DATA data;
jdoerriebacc1962019-02-07 13:39:221483 GetFileAttributesEx(base::as_wcstr(app_path.value()), GetFileExInfoStandard,
jdoerrie6312bf62019-02-01 22:03:421484 &data);
jdoerriebacc1962019-02-07 13:39:221485 HANDLE file = CreateFile(base::as_wcstr(app_path.value()), GENERIC_READ,
Raul Tambre94493c652019-03-11 17:18:351486 FILE_SHARE_READ, nullptr, OPEN_EXISTING,
1487 FILE_ATTRIBUTE_NORMAL, nullptr);
[email protected]5ecf7cb282014-05-11 01:49:551488 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361489 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551490 DWORD read_size;
1491 BOOL result;
Raul Tambre94493c652019-03-11 17:18:351492 result =
1493 ReadFile(file, buffer.get(), data.nFileSizeLow, &read_size, nullptr);
[email protected]5ecf7cb282014-05-11 01:49:551494 std::string content(buffer.get(), read_size);
1495 CloseHandle(file);
1496
[email protected]f7022f32014-08-21 16:32:191497 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551498 EXPECT_EQ(1, d.received_redirect_count());
1499 EXPECT_EQ(content, d.data_received());
1500 }
1501
1502 // Clean the shortcut
jdoerriebacc1962019-02-07 13:39:221503 DeleteFile(base::as_wcstr(lnk_path));
[email protected]5ecf7cb282014-05-11 01:49:551504}
1505#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441506
1507// Custom URLRequestJobs for use with interceptor tests
1508class RestartTestJob : public URLRequestTestJob {
1509 public:
1510 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1511 : URLRequestTestJob(request, network_delegate, true) {}
1512 protected:
dchengb03027d2014-10-21 12:00:201513 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441514 private:
Chris Watkins7a41d3552017-12-01 02:13:271515 ~RestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441516};
1517
1518class CancelTestJob : public URLRequestTestJob {
1519 public:
1520 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1521 : URLRequestTestJob(request, network_delegate, true) {}
1522 protected:
dchengb03027d2014-10-21 12:00:201523 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441524 private:
Chris Watkins7a41d3552017-12-01 02:13:271525 ~CancelTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441526};
1527
1528class CancelThenRestartTestJob : public URLRequestTestJob {
1529 public:
1530 explicit CancelThenRestartTestJob(URLRequest* request,
1531 NetworkDelegate* network_delegate)
1532 : URLRequestTestJob(request, network_delegate, true) {
1533 }
1534 protected:
dchengb03027d2014-10-21 12:00:201535 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441536 request_->Cancel();
1537 this->NotifyRestartRequired();
1538 }
1539 private:
Chris Watkins7a41d3552017-12-01 02:13:271540 ~CancelThenRestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441541};
1542
bengr1bf8e942014-11-07 01:36:501543// An Interceptor for use with interceptor tests.
1544class MockURLRequestInterceptor : public URLRequestInterceptor {
1545 public:
1546 // Static getters for canned response header and data strings.
1547 static std::string ok_data() {
1548 return URLRequestTestJob::test_data_1();
1549 }
1550
1551 static std::string ok_headers() {
1552 return URLRequestTestJob::test_headers();
1553 }
1554
1555 static std::string redirect_data() {
1556 return std::string();
1557 }
1558
1559 static std::string redirect_headers() {
1560 return URLRequestTestJob::test_redirect_headers();
1561 }
1562
1563 static std::string error_data() {
1564 return std::string("ohhh nooooo mr. bill!");
1565 }
1566
1567 static std::string error_headers() {
1568 return URLRequestTestJob::test_error_headers();
1569 }
1570
1571 MockURLRequestInterceptor()
1572 : intercept_main_request_(false), restart_main_request_(false),
1573 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1574 simulate_main_network_error_(false),
1575 intercept_redirect_(false), cancel_redirect_request_(false),
1576 intercept_final_response_(false), cancel_final_request_(false),
1577 use_url_request_http_job_(false),
1578 did_intercept_main_(false), did_restart_main_(false),
1579 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1580 did_simulate_error_main_(false),
1581 did_intercept_redirect_(false), did_cancel_redirect_(false),
1582 did_intercept_final_(false), did_cancel_final_(false) {
1583 }
1584
Chris Watkins7a41d3552017-12-01 02:13:271585 ~MockURLRequestInterceptor() override = default;
bengr1bf8e942014-11-07 01:36:501586
1587 // URLRequestInterceptor implementation:
1588 URLRequestJob* MaybeInterceptRequest(
1589 URLRequest* request,
1590 NetworkDelegate* network_delegate) const override {
1591 if (restart_main_request_) {
1592 restart_main_request_ = false;
1593 did_restart_main_ = true;
1594 return new RestartTestJob(request, network_delegate);
1595 }
1596 if (cancel_main_request_) {
1597 cancel_main_request_ = false;
1598 did_cancel_main_ = true;
1599 return new CancelTestJob(request, network_delegate);
1600 }
1601 if (cancel_then_restart_main_request_) {
1602 cancel_then_restart_main_request_ = false;
1603 did_cancel_then_restart_main_ = true;
1604 return new CancelThenRestartTestJob(request, network_delegate);
1605 }
1606 if (simulate_main_network_error_) {
1607 simulate_main_network_error_ = false;
1608 did_simulate_error_main_ = true;
1609 if (use_url_request_http_job_) {
1610 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1611 }
1612 // This job will result in error since the requested URL is not one of the
1613 // URLs supported by these tests.
1614 return new URLRequestTestJob(request, network_delegate, true);
1615 }
1616 if (!intercept_main_request_)
1617 return nullptr;
1618 intercept_main_request_ = false;
1619 did_intercept_main_ = true;
1620 URLRequestTestJob* job = new URLRequestTestJob(request,
1621 network_delegate,
1622 main_headers_,
1623 main_data_,
1624 true);
1625 job->set_load_timing_info(main_request_load_timing_info_);
1626 return job;
1627 }
1628
1629 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1630 NetworkDelegate* network_delegate,
1631 const GURL& location) const override {
1632 if (cancel_redirect_request_) {
1633 cancel_redirect_request_ = false;
1634 did_cancel_redirect_ = true;
1635 return new CancelTestJob(request, network_delegate);
1636 }
1637 if (!intercept_redirect_)
1638 return nullptr;
1639 intercept_redirect_ = false;
1640 did_intercept_redirect_ = true;
1641 if (use_url_request_http_job_) {
1642 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1643 }
1644 return new URLRequestTestJob(request,
1645 network_delegate,
1646 redirect_headers_,
1647 redirect_data_,
1648 true);
1649 }
1650
1651 URLRequestJob* MaybeInterceptResponse(
1652 URLRequest* request,
1653 NetworkDelegate* network_delegate) const override {
1654 if (cancel_final_request_) {
1655 cancel_final_request_ = false;
1656 did_cancel_final_ = true;
1657 return new CancelTestJob(request, network_delegate);
1658 }
1659 if (!intercept_final_response_)
1660 return nullptr;
1661 intercept_final_response_ = false;
1662 did_intercept_final_ = true;
1663 if (use_url_request_http_job_) {
1664 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1665 }
1666 return new URLRequestTestJob(request,
1667 network_delegate,
1668 final_headers_,
1669 final_data_,
1670 true);
1671 }
1672
1673 void set_intercept_main_request(bool intercept_main_request) {
1674 intercept_main_request_ = intercept_main_request;
1675 }
1676
1677 void set_main_headers(const std::string& main_headers) {
1678 main_headers_ = main_headers;
1679 }
1680
1681 void set_main_data(const std::string& main_data) {
1682 main_data_ = main_data;
1683 }
1684
1685 void set_main_request_load_timing_info(
1686 const LoadTimingInfo& main_request_load_timing_info) {
1687 main_request_load_timing_info_ = main_request_load_timing_info;
1688 }
1689
1690 void set_restart_main_request(bool restart_main_request) {
1691 restart_main_request_ = restart_main_request;
1692 }
1693
1694 void set_cancel_main_request(bool cancel_main_request) {
1695 cancel_main_request_ = cancel_main_request;
1696 }
1697
1698 void set_cancel_then_restart_main_request(
1699 bool cancel_then_restart_main_request) {
1700 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1701 }
1702
1703 void set_simulate_main_network_error(bool simulate_main_network_error) {
1704 simulate_main_network_error_ = simulate_main_network_error;
1705 }
1706
1707 void set_intercept_redirect(bool intercept_redirect) {
1708 intercept_redirect_ = intercept_redirect;
1709 }
1710
1711 void set_redirect_headers(const std::string& redirect_headers) {
1712 redirect_headers_ = redirect_headers;
1713 }
1714
1715 void set_redirect_data(const std::string& redirect_data) {
1716 redirect_data_ = redirect_data;
1717 }
1718
1719 void set_cancel_redirect_request(bool cancel_redirect_request) {
1720 cancel_redirect_request_ = cancel_redirect_request;
1721 }
1722
1723 void set_intercept_final_response(bool intercept_final_response) {
1724 intercept_final_response_ = intercept_final_response;
1725 }
1726
1727 void set_final_headers(const std::string& final_headers) {
1728 final_headers_ = final_headers;
1729 }
1730
1731 void set_final_data(const std::string& final_data) {
1732 final_data_ = final_data;
1733 }
1734
1735 void set_cancel_final_request(bool cancel_final_request) {
1736 cancel_final_request_ = cancel_final_request;
1737 }
1738
1739 void set_use_url_request_http_job(bool use_url_request_http_job) {
1740 use_url_request_http_job_ = use_url_request_http_job;
1741 }
1742
1743 bool did_intercept_main() const {
1744 return did_intercept_main_;
1745 }
1746
1747 bool did_restart_main() const {
1748 return did_restart_main_;
1749 }
1750
1751 bool did_cancel_main() const {
1752 return did_cancel_main_;
1753 }
1754
1755 bool did_cancel_then_restart_main() const {
1756 return did_cancel_then_restart_main_;
1757 }
1758
1759 bool did_simulate_error_main() const {
1760 return did_simulate_error_main_;
1761 }
1762
1763 bool did_intercept_redirect() const {
1764 return did_intercept_redirect_;
1765 }
1766
1767 bool did_cancel_redirect() const {
1768 return did_cancel_redirect_;
1769 }
1770
1771 bool did_intercept_final() const {
1772 return did_intercept_final_;
1773 }
1774
1775 bool did_cancel_final() const {
1776 return did_cancel_final_;
1777 }
1778
1779 private:
1780 // Indicate whether to intercept the main request, and if so specify the
1781 // response to return and the LoadTimingInfo to use.
1782 mutable bool intercept_main_request_;
1783 mutable std::string main_headers_;
1784 mutable std::string main_data_;
1785 mutable LoadTimingInfo main_request_load_timing_info_;
1786
1787 // These indicate actions that can be taken within MaybeInterceptRequest.
1788 mutable bool restart_main_request_;
1789 mutable bool cancel_main_request_;
1790 mutable bool cancel_then_restart_main_request_;
1791 mutable bool simulate_main_network_error_;
1792
1793 // Indicate whether to intercept redirects, and if so specify the response to
1794 // return.
1795 mutable bool intercept_redirect_;
1796 mutable std::string redirect_headers_;
1797 mutable std::string redirect_data_;
1798
1799 // Cancel the request within MaybeInterceptRedirect.
1800 mutable bool cancel_redirect_request_;
1801
1802 // Indicate whether to intercept the final response, and if so specify the
1803 // response to return.
1804 mutable bool intercept_final_response_;
1805 mutable std::string final_headers_;
1806 mutable std::string final_data_;
1807
1808 // Cancel the final request within MaybeInterceptResponse.
1809 mutable bool cancel_final_request_;
1810
1811 // Instruct the interceptor to use a real URLRequestHTTPJob.
1812 mutable bool use_url_request_http_job_;
1813
1814 // These indicate if the interceptor did something or not.
1815 mutable bool did_intercept_main_;
1816 mutable bool did_restart_main_;
1817 mutable bool did_cancel_main_;
1818 mutable bool did_cancel_then_restart_main_;
1819 mutable bool did_simulate_error_main_;
1820 mutable bool did_intercept_redirect_;
1821 mutable bool did_cancel_redirect_;
1822 mutable bool did_intercept_final_;
1823 mutable bool did_cancel_final_;
1824};
1825
1826// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1827class URLRequestInterceptorTest : public URLRequestTest {
1828 public:
Raul Tambre94493c652019-03-11 17:18:351829 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:501830
1831 ~URLRequestInterceptorTest() override {
1832 // URLRequestJobs may post clean-up tasks on destruction.
1833 base::RunLoop().RunUntilIdle();
1834 }
1835
1836 void SetUpFactory() override {
1837 interceptor_ = new MockURLRequestInterceptor();
1838 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361839 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501840 }
1841
1842 MockURLRequestInterceptor* interceptor() const {
1843 return interceptor_;
1844 }
1845
1846 private:
1847 MockURLRequestInterceptor* interceptor_;
1848};
1849
1850TEST_F(URLRequestInterceptorTest, Intercept) {
1851 // Intercept the main request and respond with a simple response.
1852 interceptor()->set_intercept_main_request(true);
1853 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1854 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591855 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361856 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161857 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1858 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501859 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1860 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1861 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091862 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041863 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1864 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501865 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191866 req->Start();
Wez2a31b222018-06-07 22:07:151867 d.RunUntilComplete();
[email protected]2bba3252013-04-08 19:50:591868
bengr1bf8e942014-11-07 01:36:501869 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091870 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501871 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1872 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591873
bengr1bf8e942014-11-07 01:36:501874 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501875 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501876 EXPECT_EQ(200, req->response_headers()->response_code());
1877 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1878 EXPECT_EQ(1, d.response_started_count());
1879 EXPECT_EQ(0, d.received_redirect_count());
1880}
[email protected]2bba3252013-04-08 19:50:591881
bengr1bf8e942014-11-07 01:36:501882TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1883 // Intercept the main request and respond with a redirect.
1884 interceptor()->set_intercept_main_request(true);
1885 interceptor()->set_main_headers(
1886 MockURLRequestInterceptor::redirect_headers());
1887 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1888
1889 // Intercept that redirect and respond with a final OK response.
1890 interceptor()->set_intercept_redirect(true);
1891 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1892 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1893
1894 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361895 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161896 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1897 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501898 req->set_method("GET");
1899 req->Start();
Wez2a31b222018-06-07 22:07:151900 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501901
1902 // Check that the interceptor got called as expected.
1903 EXPECT_TRUE(interceptor()->did_intercept_main());
1904 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1905
1906 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501907 int status = d.request_status();
1908 EXPECT_EQ(OK, status);
1909 if (status == OK)
bengr1bf8e942014-11-07 01:36:501910 EXPECT_EQ(200, req->response_headers()->response_code());
1911
1912 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1913 EXPECT_EQ(1, d.response_started_count());
1914 EXPECT_EQ(0, d.received_redirect_count());
1915}
1916
1917TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1918 // Intercept the main request to generate a server error response.
1919 interceptor()->set_intercept_main_request(true);
1920 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1921 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1922
1923 // Intercept that error and respond with an OK response.
1924 interceptor()->set_intercept_final_response(true);
1925 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1926 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1927
1928 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361929 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161930 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1931 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501932 req->set_method("GET");
1933 req->Start();
Wez2a31b222018-06-07 22:07:151934 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501935
1936 // Check that the interceptor got called as expected.
1937 EXPECT_TRUE(interceptor()->did_intercept_main());
1938 EXPECT_TRUE(interceptor()->did_intercept_final());
1939
1940 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501941 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501942 EXPECT_EQ(200, req->response_headers()->response_code());
1943 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1944 EXPECT_EQ(1, d.response_started_count());
1945 EXPECT_EQ(0, d.received_redirect_count());
1946}
1947
1948TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1949 // Intercept the main request to simulate a network error.
1950 interceptor()->set_simulate_main_network_error(true);
1951
1952 // Intercept that error and respond with an OK response.
1953 interceptor()->set_intercept_final_response(true);
1954 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1955 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1956
1957 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361958 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161959 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1960 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501961 req->set_method("GET");
1962 req->Start();
Wez2a31b222018-06-07 22:07:151963 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501964
1965 // Check that the interceptor got called as expected.
1966 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1967 EXPECT_TRUE(interceptor()->did_intercept_final());
1968
1969 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501970 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501971 EXPECT_EQ(200, req->response_headers()->response_code());
1972 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1973 EXPECT_EQ(1, d.response_started_count());
1974 EXPECT_EQ(0, d.received_redirect_count());
1975}
1976
1977TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1978 // Restart the main request.
1979 interceptor()->set_restart_main_request(true);
1980
1981 // then intercept the new main request and respond with an OK response
1982 interceptor()->set_intercept_main_request(true);
1983 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1984 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1985
1986 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361987 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161988 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1989 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501990 req->set_method("GET");
1991 req->Start();
Wez2a31b222018-06-07 22:07:151992 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501993
1994 // Check that the interceptor got called as expected.
1995 EXPECT_TRUE(interceptor()->did_restart_main());
1996 EXPECT_TRUE(interceptor()->did_intercept_main());
1997
1998 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501999 int status = d.request_status();
2000 EXPECT_EQ(OK, status);
2001 if (status == OK)
bengr1bf8e942014-11-07 01:36:502002 EXPECT_EQ(200, req->response_headers()->response_code());
2003
2004 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2005 EXPECT_EQ(1, d.response_started_count());
2006 EXPECT_EQ(0, d.received_redirect_count());
2007}
2008
2009TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
2010 // Intercept the main request and cancel from within the restarted job.
2011 interceptor()->set_cancel_main_request(true);
2012
2013 // Set up to intercept the final response and override it with an OK response.
2014 interceptor()->set_intercept_final_response(true);
2015 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2016 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2017
2018 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362019 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162020 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2021 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502022 req->set_method("GET");
2023 req->Start();
Wez2a31b222018-06-07 22:07:152024 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502025
2026 // Check that the interceptor got called as expected.
2027 EXPECT_TRUE(interceptor()->did_cancel_main());
2028 EXPECT_FALSE(interceptor()->did_intercept_final());
2029
2030 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502031 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502032}
2033
2034TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2035 // Intercept the main request and respond with a redirect.
2036 interceptor()->set_intercept_main_request(true);
2037 interceptor()->set_main_headers(
2038 MockURLRequestInterceptor::redirect_headers());
2039 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2040
2041 // Intercept the redirect and cancel from within that job.
2042 interceptor()->set_cancel_redirect_request(true);
2043
2044 // Set up to intercept the final response and override it with an OK response.
2045 interceptor()->set_intercept_final_response(true);
2046 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2047 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2048
2049 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362050 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162051 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2052 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502053 req->set_method("GET");
2054 req->Start();
Wez2a31b222018-06-07 22:07:152055 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502056
2057 // Check that the interceptor got called as expected.
2058 EXPECT_TRUE(interceptor()->did_intercept_main());
2059 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2060 EXPECT_FALSE(interceptor()->did_intercept_final());
2061
2062 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502063 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502064}
2065
2066TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2067 // Intercept the main request to simulate a network error.
2068 interceptor()->set_simulate_main_network_error(true);
2069
2070 // Set up to intercept final the response and cancel from within that job.
2071 interceptor()->set_cancel_final_request(true);
2072
2073 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362074 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162075 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2076 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502077 req->set_method("GET");
2078 req->Start();
Wez2a31b222018-06-07 22:07:152079 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502080
2081 // Check that the interceptor got called as expected.
2082 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2083 EXPECT_TRUE(interceptor()->did_cancel_final());
2084
2085 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502086 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502087}
2088
2089TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2090 // Intercept the main request and cancel then restart from within that job.
2091 interceptor()->set_cancel_then_restart_main_request(true);
2092
2093 // Set up to intercept the final response and override it with an OK response.
2094 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502095 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2096 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502097
2098 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362099 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162100 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2101 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502102 req->set_method("GET");
2103 req->Start();
Wez2a31b222018-06-07 22:07:152104 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502105
2106 // Check that the interceptor got called as expected.
2107 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2108 EXPECT_FALSE(interceptor()->did_intercept_final());
2109
2110 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502111 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592112}
2113
2114// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2115// reused. |connect_time_flags| is used to indicate if there should be dns
2116// or SSL times, and |used_proxy| is used for proxy times.
2117LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2118 int connect_time_flags,
2119 bool used_proxy) {
2120 LoadTimingInfo load_timing;
2121 load_timing.socket_log_id = 1;
2122
2123 if (used_proxy) {
2124 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2125 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2126 }
2127
2128 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2129 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2130 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2131 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2132 }
2133 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2134 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2135 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2136 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2137 }
2138 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2139
2140 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2141 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382142 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2143 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592144 return load_timing;
2145}
2146
2147// Same as above, but in the case of a reused socket.
2148LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2149 bool used_proxy) {
2150 LoadTimingInfo load_timing;
2151 load_timing.socket_log_id = 1;
2152 load_timing.socket_reused = true;
2153
2154 if (used_proxy) {
2155 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2156 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2157 }
2158
2159 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2160 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382161 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2162 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592163 return load_timing;
2164}
2165
bengr1bf8e942014-11-07 01:36:502166LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2167 const LoadTimingInfo& job_load_timing,
2168 const URLRequestContext& context,
2169 MockURLRequestInterceptor* interceptor) {
2170 interceptor->set_intercept_main_request(true);
2171 interceptor->set_main_request_load_timing_info(job_load_timing);
2172 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162173 std::unique_ptr<URLRequest> req(
2174 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2175 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502176 req->Start();
Wez2a31b222018-06-07 22:07:152177 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502178
2179 LoadTimingInfo resulting_load_timing;
2180 req->GetLoadTimingInfo(&resulting_load_timing);
2181
2182 // None of these should be modified by the URLRequest.
2183 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2184 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2185 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2186 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382187 EXPECT_EQ(job_load_timing.receive_headers_start,
2188 resulting_load_timing.receive_headers_start);
bengr1bf8e942014-11-07 01:36:502189 EXPECT_EQ(job_load_timing.receive_headers_end,
2190 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572191 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2192 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502193
2194 return resulting_load_timing;
2195}
2196
[email protected]2bba3252013-04-08 19:50:592197// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502198TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592199 base::TimeTicks now = base::TimeTicks::Now();
2200 LoadTimingInfo job_load_timing =
2201 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2202
[email protected]2ca01e52013-10-31 22:05:192203 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502204 RunURLRequestInterceptorLoadTimingTest(
2205 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592206
2207 // Nothing should have been changed by the URLRequest.
2208 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2209 load_timing_result.proxy_resolve_start);
2210 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2211 load_timing_result.proxy_resolve_end);
2212 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2213 load_timing_result.connect_timing.dns_start);
2214 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2215 load_timing_result.connect_timing.dns_end);
2216 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2217 load_timing_result.connect_timing.connect_start);
2218 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2219 load_timing_result.connect_timing.connect_end);
2220 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2221 load_timing_result.connect_timing.ssl_start);
2222 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2223 load_timing_result.connect_timing.ssl_end);
2224
2225 // Redundant sanity check.
2226 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2227}
2228
2229// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502230TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592231 base::TimeTicks now = base::TimeTicks::Now();
2232 LoadTimingInfo job_load_timing =
2233 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2234
[email protected]2ca01e52013-10-31 22:05:192235 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502236 RunURLRequestInterceptorLoadTimingTest(
2237 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592238
2239 // Nothing should have been changed by the URLRequest.
2240 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2241 load_timing_result.proxy_resolve_start);
2242 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2243 load_timing_result.proxy_resolve_end);
2244 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2245 load_timing_result.connect_timing.dns_start);
2246 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2247 load_timing_result.connect_timing.dns_end);
2248 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2249 load_timing_result.connect_timing.connect_start);
2250 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2251 load_timing_result.connect_timing.connect_end);
2252 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2253 load_timing_result.connect_timing.ssl_start);
2254 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2255 load_timing_result.connect_timing.ssl_end);
2256
2257 // Redundant sanity check.
2258 TestLoadTimingNotReusedWithProxy(load_timing_result,
2259 CONNECT_TIMING_HAS_SSL_TIMES);
2260}
2261
2262// Make sure that URLRequest correctly adjusts proxy times when they're before
2263// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102264// the case of reusing a SPDY session. The connected socket is not considered
2265// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592266//
2267// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502268TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592269 base::TimeTicks now = base::TimeTicks::Now();
2270 LoadTimingInfo job_load_timing =
2271 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2272 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2273 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2274 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2275 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2276 job_load_timing.connect_timing.connect_start =
2277 now - base::TimeDelta::FromDays(2);
2278 job_load_timing.connect_timing.connect_end =
2279 now - base::TimeDelta::FromDays(1);
2280
[email protected]2ca01e52013-10-31 22:05:192281 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502282 RunURLRequestInterceptorLoadTimingTest(
2283 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592284
2285 // Proxy times, connect times, and DNS times should all be replaced with
2286 // request_start.
2287 EXPECT_EQ(load_timing_result.request_start,
2288 load_timing_result.proxy_resolve_start);
2289 EXPECT_EQ(load_timing_result.request_start,
2290 load_timing_result.proxy_resolve_end);
2291 EXPECT_EQ(load_timing_result.request_start,
2292 load_timing_result.connect_timing.dns_start);
2293 EXPECT_EQ(load_timing_result.request_start,
2294 load_timing_result.connect_timing.dns_end);
2295 EXPECT_EQ(load_timing_result.request_start,
2296 load_timing_result.connect_timing.connect_start);
2297 EXPECT_EQ(load_timing_result.request_start,
2298 load_timing_result.connect_timing.connect_end);
2299
2300 // Other times should have been left null.
2301 TestLoadTimingNotReusedWithProxy(load_timing_result,
2302 CONNECT_TIMING_HAS_DNS_TIMES);
2303}
2304
2305// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502306TEST_F(URLRequestInterceptorTest,
2307 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592308 base::TimeTicks now = base::TimeTicks::Now();
2309 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2310 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2311 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2312
[email protected]2ca01e52013-10-31 22:05:192313 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502314 RunURLRequestInterceptorLoadTimingTest(
2315 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592316
2317 // Proxy times and connect times should all be replaced with request_start.
2318 EXPECT_EQ(load_timing_result.request_start,
2319 load_timing_result.proxy_resolve_start);
2320 EXPECT_EQ(load_timing_result.request_start,
2321 load_timing_result.proxy_resolve_end);
2322
2323 // Other times should have been left null.
2324 TestLoadTimingReusedWithProxy(load_timing_result);
2325}
2326
2327// Make sure that URLRequest correctly adjusts connect times when they're before
2328// |request_start|, due to reusing a connected socket. The connected socket is
2329// not considered reused in this test (May be a preconnect).
2330//
2331// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502332TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592333 base::TimeTicks now = base::TimeTicks::Now();
2334 LoadTimingInfo job_load_timing =
2335 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2336 job_load_timing.connect_timing.connect_start =
2337 now - base::TimeDelta::FromDays(1);
2338 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2339 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2340 job_load_timing.connect_timing.connect_end =
2341 now - base::TimeDelta::FromDays(4);
2342
[email protected]2ca01e52013-10-31 22:05:192343 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502344 RunURLRequestInterceptorLoadTimingTest(
2345 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592346
2347 // Connect times, and SSL times should be replaced with request_start.
2348 EXPECT_EQ(load_timing_result.request_start,
2349 load_timing_result.connect_timing.connect_start);
2350 EXPECT_EQ(load_timing_result.request_start,
2351 load_timing_result.connect_timing.ssl_start);
2352 EXPECT_EQ(load_timing_result.request_start,
2353 load_timing_result.connect_timing.ssl_end);
2354 EXPECT_EQ(load_timing_result.request_start,
2355 load_timing_result.connect_timing.connect_end);
2356
2357 // Other times should have been left null.
2358 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2359}
2360
2361// Make sure that URLRequest correctly adjusts connect times when they're before
2362// |request_start|, due to reusing a connected socket in the case that there
2363// are also proxy times. The connected socket is not considered reused in this
2364// test (May be a preconnect).
2365//
2366// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502367TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592368 base::TimeTicks now = base::TimeTicks::Now();
2369 LoadTimingInfo job_load_timing =
2370 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2371 job_load_timing.connect_timing.connect_start =
2372 now - base::TimeDelta::FromDays(1);
2373 job_load_timing.connect_timing.connect_end =
2374 now - base::TimeDelta::FromDays(2);
2375
[email protected]2ca01e52013-10-31 22:05:192376 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502377 RunURLRequestInterceptorLoadTimingTest(
2378 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592379
2380 // Connect times should be replaced with proxy_resolve_end.
2381 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2382 load_timing_result.connect_timing.connect_start);
2383 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2384 load_timing_result.connect_timing.connect_end);
2385
2386 // Other times should have been left null.
2387 TestLoadTimingNotReusedWithProxy(load_timing_result,
2388 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2389}
2390
[email protected]316c1e5e2012-09-12 15:17:442391// Check that two different URL requests have different identifiers.
2392TEST_F(URLRequestTest, Identifiers) {
2393 TestDelegate d;
2394 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362395 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162396 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2397 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362398 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162399 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2400 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442401
mmenke19378d22014-09-09 04:12:592402 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442403}
2404
blundellb8163592f2015-12-16 14:22:422405#if defined(OS_IOS)
2406// TODO(droger): Check that a failure to connect to the proxy is reported to
2407// the network delegate. crbug.com/496743
2408#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2409#else
2410#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2411#endif
2412TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442413 MockHostResolver host_resolver;
2414 host_resolver.rules()->AddSimulatedFailure("*");
2415
[email protected]ceefd7fd2012-11-29 00:36:242416 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442417 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2418
2419 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362420 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162421 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2422 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192423 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442424
[email protected]f7022f32014-08-21 16:32:192425 req->Start();
Wez2a31b222018-06-07 22:07:152426 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442427
2428 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152429 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472430 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502431 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442432
2433 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012434 EXPECT_THAT(network_delegate.last_error(),
2435 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442436 EXPECT_EQ(1, network_delegate.completed_requests());
2437}
2438
[email protected]cba24642014-08-15 20:49:592439// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442440// content is empty.
2441TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2442 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072443 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162444 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192445 req->Start();
Wez2a31b222018-06-07 22:07:152446 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442447 EXPECT_EQ("", d.data_received());
2448 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2449}
2450
[email protected]5033ab82013-03-22 20:17:462451// Make sure that SetPriority actually sets the URLRequest's priority
2452// correctly, both before and after start.
2453TEST_F(URLRequestTest, SetPriorityBasic) {
2454 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072455 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162456 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2457 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192458 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462459
[email protected]f7022f32014-08-21 16:32:192460 req->SetPriority(LOW);
2461 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462462
[email protected]f7022f32014-08-21 16:32:192463 req->Start();
2464 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462465
[email protected]f7022f32014-08-21 16:32:192466 req->SetPriority(MEDIUM);
2467 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462468}
2469
2470// Make sure that URLRequest calls SetPriority on a job before calling
2471// Start on it.
2472TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2473 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072474 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162475 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2476 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192477 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462478
mmenkeed0498b2015-12-08 23:20:422479 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362480 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422481 req.get(), &default_network_delegate_, &job_priority));
2482 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2483 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462484
[email protected]f7022f32014-08-21 16:32:192485 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462486
[email protected]f7022f32014-08-21 16:32:192487 req->Start();
mmenkeed0498b2015-12-08 23:20:422488 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462489}
2490
2491// Make sure that URLRequest passes on its priority updates to its
2492// job.
2493TEST_F(URLRequestTest, SetJobPriority) {
2494 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072495 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162496 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2497 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462498
mmenkeed0498b2015-12-08 23:20:422499 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362500 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422501 req.get(), &default_network_delegate_, &job_priority));
2502 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462503
[email protected]f7022f32014-08-21 16:32:192504 req->SetPriority(LOW);
2505 req->Start();
mmenkeed0498b2015-12-08 23:20:422506 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462507
[email protected]f7022f32014-08-21 16:32:192508 req->SetPriority(MEDIUM);
2509 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422510 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462511}
2512
[email protected]bb1c4662013-11-14 00:00:072513// Setting the IGNORE_LIMITS load flag should be okay if the priority
2514// is MAXIMUM_PRIORITY.
2515TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2516 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072517 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162518 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2519 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192520 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072521
mmenkeed0498b2015-12-08 23:20:422522 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362523 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422524 req.get(), &default_network_delegate_, &job_priority));
2525 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072526
[email protected]f7022f32014-08-21 16:32:192527 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2528 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072529
[email protected]f7022f32014-08-21 16:32:192530 req->SetPriority(MAXIMUM_PRIORITY);
2531 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072532
[email protected]f7022f32014-08-21 16:32:192533 req->Start();
2534 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422535 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072536}
2537
nick5d570de92015-05-04 20:16:162538namespace {
2539
2540// Less verbose way of running a simple testserver for the tests below.
David Benjamin42116f62017-11-20 21:45:392541class HttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442542 public:
David Benjamin42116f62017-11-20 21:45:392543 explicit HttpTestServer(const base::FilePath& document_root) {
tommycli59a63432015-11-06 00:10:552544 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272545 }
tommycli59a63432015-11-06 00:10:552546
David Benjamin42116f62017-11-20 21:45:392547 HttpTestServer() { AddDefaultHandlers(base::FilePath()); }
tommycli59a63432015-11-06 00:10:552548};
tommyclieae5f75f2015-11-05 19:07:272549
nick5d570de92015-05-04 20:16:162550} // namespace
2551
[email protected]f2f31b32013-01-16 23:24:092552TEST_F(URLRequestTest, DelayedCookieCallback) {
David Benjamin42116f62017-11-20 21:45:392553 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442554 ASSERT_TRUE(test_server.Start());
2555
2556 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362557 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502558 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442559
2560 // Set up a cookie.
2561 {
2562 TestNetworkDelegate network_delegate;
2563 context.set_network_delegate(&network_delegate);
2564 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362565 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552566 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162567 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192568 req->Start();
Wez2a31b222018-06-07 22:07:152569 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442570 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2571 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2572 EXPECT_EQ(1, network_delegate.set_cookie_count());
2573 }
2574
2575 // Verify that the cookie is set.
2576 {
2577 TestNetworkDelegate network_delegate;
2578 context.set_network_delegate(&network_delegate);
2579 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362580 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162581 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2582 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192583 req->Start();
Wez2a31b222018-06-07 22:07:152584 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442585
2586 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2587 != std::string::npos);
2588 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2589 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2590 }
2591}
2592
Aaron Tagliaboschi028009e2019-03-07 16:28:062593class FilteringTestLayeredNetworkDelegate : public LayeredNetworkDelegate {
2594 public:
2595 FilteringTestLayeredNetworkDelegate(
2596 std::unique_ptr<NetworkDelegate> network_delegate)
2597 : LayeredNetworkDelegate(std::move((network_delegate))),
2598 set_cookie_called_count_(0),
2599 blocked_set_cookie_count_(0) {}
2600 ~FilteringTestLayeredNetworkDelegate() override = default;
2601
2602 bool OnCanSetCookieInternal(const URLRequest& request,
2603 const net::CanonicalCookie& cookie,
2604 CookieOptions* options,
2605 bool allowed_from_caller) override {
2606 // Filter out cookies with the same name as |cookie_name_filter_| and
2607 // combine with |allowed_from_caller|.
2608 bool allowed =
2609 allowed_from_caller && !(cookie.Name() == cookie_name_filter_);
2610
2611 ++set_cookie_called_count_;
2612
2613 if (!allowed)
2614 ++blocked_set_cookie_count_;
2615
2616 return allowed;
2617 }
2618
2619 void SetCookieFilter(std::string filter) {
2620 cookie_name_filter_ = std::move(filter);
2621 }
2622
2623 int set_cookie_called_count() { return set_cookie_called_count_; }
2624
2625 int blocked_set_cookie_count() { return blocked_set_cookie_count_; }
2626
2627 void ResetSetCookieCalledCount() { set_cookie_called_count_ = 0; }
2628
2629 void ResetBlockedSetCookieCount() { blocked_set_cookie_count_ = 0; }
2630
2631 private:
2632 std::string cookie_name_filter_;
2633 int set_cookie_called_count_;
2634 int blocked_set_cookie_count_;
2635};
2636
2637TEST_F(URLRequestTest, DelayedCookieCallbackAsync) {
2638 HttpTestServer test_server;
2639 ASSERT_TRUE(test_server.Start());
2640
2641 TestURLRequestContext async_context;
2642 std::unique_ptr<DelayedCookieMonster> delayed_cm =
2643 std::make_unique<DelayedCookieMonster>();
2644 async_context.set_cookie_store(delayed_cm.get());
2645 FilteringTestLayeredNetworkDelegate async_filter_network_delegate(
2646 std::make_unique<TestNetworkDelegate>());
2647 async_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
2648 async_context.set_network_delegate(&async_filter_network_delegate);
2649 TestDelegate async_delegate;
2650
2651 TestURLRequestContext sync_context;
2652 std::unique_ptr<CookieMonster> cm =
2653 std::make_unique<CookieMonster>(nullptr, nullptr, nullptr);
2654 sync_context.set_cookie_store(cm.get());
2655 FilteringTestLayeredNetworkDelegate sync_filter_network_delegate(
2656 std::make_unique<TestNetworkDelegate>());
2657 sync_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
2658 sync_context.set_network_delegate(&sync_filter_network_delegate);
2659 TestDelegate sync_delegate;
2660
2661 // Add a secure cookie so we can try to set an insecure cookie and have
2662 // SetCanonicalCookie (and therefore SetCookieWithOptions) fail.
2663 GURL::Replacements replace_scheme;
2664 replace_scheme.SetSchemeStr("https");
2665 GURL url = test_server.base_url().ReplaceComponents(replace_scheme);
2666
2667 delayed_cm->SetCookieWithOptionsAsync(url, "AlreadySetCookie=1;Secure",
2668 CookieOptions(),
2669 CookieStore::SetCookiesCallback());
2670 cm->SetCookieWithOptionsAsync(url, "AlreadySetCookie=1;Secure",
2671 CookieOptions(),
2672 CookieStore::SetCookiesCallback());
2673
2674 std::vector<std::string> cookie_lines(
2675 {// Fails on CanonicalCookie::Create for trying to create a secure cookie
2676 // on an insecure host.
2677 "CookieNotSet=1;Secure",
2678 // Fail in FilteringTestLayeredNetworkDelegate::CanGetCookie.
2679 "CookieBlockedOnCanGetCookie=1",
2680 // Fails in SetCanonicalCookie for trying to overwrite a secure cookie
2681 // with an insecure cookie.
2682 "AlreadySetCookie=1",
2683 // Succeeds and added cookie to store. Delayed (which makes the callback
2684 // run asynchronously) in DelayedCookieMonster.
2685 "CookieSet=1"});
2686
2687 for (auto first_cookie_line : cookie_lines) {
2688 for (auto second_cookie_line : cookie_lines) {
2689 // Run with the delayed cookie monster.
2690 std::unique_ptr<URLRequest> request = async_context.CreateRequest(
2691 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2692 second_cookie_line),
2693 DEFAULT_PRIORITY, &async_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2694
2695 request->Start();
2696 async_delegate.RunUntilComplete();
2697 EXPECT_THAT(async_delegate.request_status(), IsOk());
2698
2699 // Run with the regular cookie monster.
2700 request = sync_context.CreateRequest(
2701 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2702 second_cookie_line),
2703 DEFAULT_PRIORITY, &sync_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2704
2705 request->Start();
2706 sync_delegate.RunUntilComplete();
2707 EXPECT_THAT(sync_delegate.request_status(), IsOk());
2708
2709 int expected_set_cookie_count = 0;
2710 int expected_blocked_cookie_count = 0;
2711
2712 if (first_cookie_line != "CookieNotSet=1;Secure")
2713 ++expected_set_cookie_count;
2714 if (second_cookie_line != "CookieNotSet=1;Secure")
2715 ++expected_set_cookie_count;
2716
2717 if (first_cookie_line == "CookieBlockedOnCanGetCookie=1")
2718 ++expected_blocked_cookie_count;
2719 if (second_cookie_line == "CookieBlockedOnCanGetCookie=1")
2720 ++expected_blocked_cookie_count;
2721
2722 EXPECT_EQ(expected_set_cookie_count,
2723 async_filter_network_delegate.set_cookie_called_count());
2724 EXPECT_EQ(expected_blocked_cookie_count,
2725 async_filter_network_delegate.blocked_set_cookie_count());
2726
2727 EXPECT_EQ(expected_set_cookie_count,
2728 sync_filter_network_delegate.set_cookie_called_count());
2729 EXPECT_EQ(expected_blocked_cookie_count,
2730 sync_filter_network_delegate.blocked_set_cookie_count());
2731
2732 async_filter_network_delegate.ResetSetCookieCalledCount();
2733 async_filter_network_delegate.ResetBlockedSetCookieCount();
2734
2735 sync_filter_network_delegate.ResetSetCookieCalledCount();
2736 sync_filter_network_delegate.ResetBlockedSetCookieCount();
2737 }
2738 }
2739}
2740
[email protected]f2f31b32013-01-16 23:24:092741TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392742 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442743 ASSERT_TRUE(test_server.Start());
2744
2745 // Set up a cookie.
2746 {
2747 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072748 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442749 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072750 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552751 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162752 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192753 req->Start();
Wez2a31b222018-06-07 22:07:152754 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442755 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2756 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2757 }
2758
2759 // Verify that the cookie is set.
2760 {
2761 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072762 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442763 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072764 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162765 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2766 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192767 req->Start();
Wez2a31b222018-06-07 22:07:152768 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442769
2770 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2771 != std::string::npos);
2772 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2773 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2774 }
2775
2776 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2777 {
2778 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072779 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442780 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072781 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162782 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2783 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192784 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2785 req->Start();
Wez2a31b222018-06-07 22:07:152786 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442787
2788 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2789 == std::string::npos);
2790
2791 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2792 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2793 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2794 }
2795}
2796
2797TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392798 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442799 ASSERT_TRUE(test_server.Start());
2800
2801 // Set up a cookie.
2802 {
2803 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072804 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442805 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072806 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552807 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162808 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192809 req->Start();
Wez2a31b222018-06-07 22:07:152810 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442811
2812 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2813 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2814 EXPECT_EQ(1, network_delegate.set_cookie_count());
2815 }
2816
2817 // Try to set-up another cookie and update the previous cookie.
2818 {
2819 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072820 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442821 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072822 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552823 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162824 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192825 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2826 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442827
Wez2a31b222018-06-07 22:07:152828 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442829
2830 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2831 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2832 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2833 EXPECT_EQ(0, network_delegate.set_cookie_count());
2834 }
2835
2836 // Verify the cookies weren't saved or updated.
2837 {
2838 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072839 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442840 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072841 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162842 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2843 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192844 req->Start();
Wez2a31b222018-06-07 22:07:152845 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442846
2847 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2848 == std::string::npos);
2849 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2850 != std::string::npos);
2851
2852 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2853 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2854 EXPECT_EQ(0, network_delegate.set_cookie_count());
2855 }
2856}
2857
2858TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392859 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442860 ASSERT_TRUE(test_server.Start());
2861
2862 // Set up a cookie.
2863 {
2864 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072865 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442866 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072867 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552868 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162869 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192870 req->Start();
Wez2a31b222018-06-07 22:07:152871 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442872
2873 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2874 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2875 }
2876
2877 // Verify that the cookie is set.
2878 {
2879 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072880 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442881 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072882 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162883 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2884 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192885 req->Start();
Wez2a31b222018-06-07 22:07:152886 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442887
2888 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2889 != std::string::npos);
2890
2891 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2892 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182893 TestNetLogEntry::List entries;
2894 net_log_.GetEntries(&entries);
2895 for (const auto& entry : entries) {
2896 EXPECT_NE(entry.type,
2897 NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE);
2898 }
[email protected]316c1e5e2012-09-12 15:17:442899 }
2900
2901 // Verify that the cookie isn't sent.
2902 {
2903 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072904 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442905 TestDelegate d;
2906 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:072907 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162908 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2909 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192910 req->Start();
Wez2a31b222018-06-07 22:07:152911 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442912
2913 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2914 == std::string::npos);
2915
[email protected]22e045f2013-09-20 03:54:032916 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442917 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182918 TestNetLogEntry::List entries;
2919 net_log_.GetEntries(&entries);
2920 ExpectLogContainsSomewhereAfter(
2921 entries, 0, NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE,
2922 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442923 }
2924}
2925
marqf14fff8d2015-12-02 15:52:292926// TODO(crbug.com/564656) This test is flaky on iOS.
2927#if defined(OS_IOS)
2928#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2929#else
2930#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2931#endif
[email protected]316c1e5e2012-09-12 15:17:442932TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
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());
Helen Li830d5708d62018-08-22 16:29:182949 TestNetLogEntry::List entries;
2950 net_log_.GetEntries(&entries);
2951 for (const auto& entry : entries) {
2952 EXPECT_NE(entry.type,
2953 NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE);
2954 }
[email protected]316c1e5e2012-09-12 15:17:442955 }
2956
2957 // Try to set-up another cookie and update the previous cookie.
2958 {
2959 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072960 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442961 TestDelegate d;
2962 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:072963 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552964 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162965 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192966 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442967
Wez2a31b222018-06-07 22:07:152968 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442969
2970 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2971 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182972 TestNetLogEntry::List entries;
2973 net_log_.GetEntries(&entries);
2974 ExpectLogContainsSomewhereAfter(
2975 entries, 0, NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE,
2976 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442977 }
2978
2979 // Verify the cookies weren't saved or updated.
2980 {
2981 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072982 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442983 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072984 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162985 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2986 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192987 req->Start();
Wez2a31b222018-06-07 22:07:152988 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442989
2990 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2991 == std::string::npos);
2992 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2993 != std::string::npos);
2994
2995 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2996 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2997 }
2998}
2999
3000TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:393001 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443002 ASSERT_TRUE(test_server.Start());
3003
3004 // Set up an empty cookie.
3005 {
3006 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073007 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443008 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073009 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163010 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
3011 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193012 req->Start();
Wez2a31b222018-06-07 22:07:153013 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443014
3015 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3016 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3017 EXPECT_EQ(0, network_delegate.set_cookie_count());
3018 }
3019}
3020
3021TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393022 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443023 ASSERT_TRUE(test_server.Start());
3024
3025 // Set up a cookie.
3026 {
3027 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073028 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443029 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073030 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553031 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163032 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193033 req->Start();
Wez2a31b222018-06-07 22:07:153034 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443035
3036 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3037 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3038 }
3039
3040 // Verify that the cookie is set.
3041 {
3042 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073043 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443044 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073045 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163046 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3047 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193048 req->Start();
Wez2a31b222018-06-07 22:07:153049 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443050
3051 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
3052 != std::string::npos);
3053
3054 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3055 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3056 }
3057
3058 // Verify that the cookie isn't sent.
3059 {
3060 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073061 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443062 TestDelegate d;
3063 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:073064 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163065 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3066 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193067 req->Start();
Wez2a31b222018-06-07 22:07:153068 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443069
3070 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
3071 == std::string::npos);
3072
[email protected]22e045f2013-09-20 03:54:033073 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:443074 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3075 }
3076}
3077
3078TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393079 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443080 ASSERT_TRUE(test_server.Start());
3081
3082 // Set up a cookie.
3083 {
3084 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073085 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443086 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073087 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553088 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163089 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193090 req->Start();
Wez2a31b222018-06-07 22:07:153091 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443092
3093 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3094 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3095 }
3096
3097 // Try to set-up another cookie and update the previous cookie.
3098 {
3099 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073100 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443101 TestDelegate d;
3102 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:073103 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553104 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:163105 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193106 req->Start();
[email protected]316c1e5e2012-09-12 15:17:443107
Wez2a31b222018-06-07 22:07:153108 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443109
3110 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3111 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
3112 }
3113
3114 // Verify the cookies weren't saved or updated.
3115 {
3116 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073117 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443118 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073119 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163120 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3121 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193122 req->Start();
Wez2a31b222018-06-07 22:07:153123 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443124
3125 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
3126 == std::string::npos);
3127 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
3128 != std::string::npos);
3129
3130 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3131 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3132 }
3133}
3134
mkwstc5fa7762016-03-28 09:28:233135TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:393136 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:263137 ASSERT_TRUE(test_server.Start());
3138
mkwst202534e32016-01-15 16:07:153139 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073140 default_context().set_network_delegate(&network_delegate);
mkwst202534e32016-01-15 16:07:153141
mkwstf71d0bd2016-03-21 14:15:243142 const std::string kHost = "example.test";
3143 const std::string kSubHost = "subdomain.example.test";
3144 const std::string kCrossHost = "cross-origin.test";
3145
3146 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:263147 {
mkwst3f3daac2015-02-26 20:15:263148 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073149 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
mkwstf71d0bd2016-03-21 14:15:243150 test_server.GetURL(kHost,
3151 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3152 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:163153 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst3f3daac2015-02-26 20:15:263154 req->Start();
Wez2a31b222018-06-07 22:07:153155 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263156 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3157 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:243158 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:263159 }
3160
mkwstf71d0bd2016-03-21 14:15:243161 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:263162 {
mkwst3f3daac2015-02-26 20:15:263163 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073164 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163165 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3166 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463167 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463168 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263169 req->Start();
Wez2a31b222018-06-07 22:07:153170 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263171
mkwstf71d0bd2016-03-21 14:15:243172 EXPECT_NE(std::string::npos,
3173 d.data_received().find("StrictSameSiteCookie=1"));
3174 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263175 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3176 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3177 }
3178
clamyfd58ca072016-12-21 17:18:323179 // Verify that both cookies are sent when the request has no initiator (can
3180 // happen for main frame browser-initiated navigations).
3181 {
3182 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073183 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163184 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3185 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463186 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:323187 req->Start();
Wez2a31b222018-06-07 22:07:153188 d.RunUntilComplete();
clamyfd58ca072016-12-21 17:18:323189
3190 EXPECT_NE(std::string::npos,
3191 d.data_received().find("StrictSameSiteCookie=1"));
3192 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3193 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3194 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3195 }
3196
mkwstf71d0bd2016-03-21 14:15:243197 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263198 {
mkwst3f3daac2015-02-26 20:15:263199 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073200 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163201 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3202 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463203 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463204 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153205 req->Start();
Wez2a31b222018-06-07 22:07:153206 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153207
mkwstf71d0bd2016-03-21 14:15:243208 EXPECT_NE(std::string::npos,
3209 d.data_received().find("StrictSameSiteCookie=1"));
3210 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153211 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3212 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3213 }
3214
mkwstf71d0bd2016-03-21 14:15:243215 // Verify that neither cookie is not sent for cross-site requests.
3216 {
3217 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073218 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163219 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3220 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463221 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463222 req->set_initiator(
3223 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243224 req->Start();
Wez2a31b222018-06-07 22:07:153225 d.RunUntilComplete();
mkwstf71d0bd2016-03-21 14:15:243226
3227 EXPECT_EQ(std::string::npos,
3228 d.data_received().find("StrictSameSiteCookie=1"));
3229 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3230 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3231 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3232 }
3233
3234 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153235 // method is "safe".
3236 {
3237 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073238 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163239 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3240 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463241 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463242 req->set_initiator(
3243 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243244 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153245 req->Start();
Wez2a31b222018-06-07 22:07:153246 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153247
mkwstf71d0bd2016-03-21 14:15:243248 EXPECT_EQ(std::string::npos,
3249 d.data_received().find("StrictSameSiteCookie=1"));
3250 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153251 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3252 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3253 }
3254
mkwstf71d0bd2016-03-21 14:15:243255 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153256 // method is unsafe (e.g. POST).
3257 {
3258 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073259 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163260 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3261 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463262 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463263 req->set_initiator(
3264 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153265 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263266 req->Start();
Wez2a31b222018-06-07 22:07:153267 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263268
mkwstf71d0bd2016-03-21 14:15:243269 EXPECT_EQ(std::string::npos,
3270 d.data_received().find("StrictSameSiteCookie=1"));
3271 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263272 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3273 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3274 }
3275}
3276
estark557a5eb82015-12-01 22:57:103277// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363278TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553279 EmbeddedTestServer http_server;
3280 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363281 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553282 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3283 https_server.AddDefaultHandlers(
3284 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3285 ASSERT_TRUE(http_server.Start());
3286 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363287
estarkb15166b2015-12-18 16:56:383288 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363289 TestURLRequestContext context(true);
3290 context.set_network_delegate(&network_delegate);
3291 context.Init();
3292
estarkb15166b2015-12-18 16:56:383293 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363294 {
3295 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363296 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103297 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163298 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363299 req->Start();
Wez2a31b222018-06-07 22:07:153300 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363301 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3302 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3303 }
3304
3305 // Verify that the cookie is not set.
3306 {
3307 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363308 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163309 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3310 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363311 req->Start();
Wez2a31b222018-06-07 22:07:153312 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363313
jww79aceda2015-12-07 01:56:343314 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3315 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363316 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3317 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3318 }
3319}
3320
estarkb15166b2015-12-18 16:56:383321TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553322 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3323 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363324 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553325 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363326
3327 TestNetworkDelegate network_delegate;
3328 TestURLRequestContext context(true);
3329 context.set_network_delegate(&network_delegate);
3330 context.Init();
3331
estarkb15166b2015-12-18 16:56:383332 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363333 {
3334 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163335 std::unique_ptr<URLRequest> req(context.CreateRequest(
3336 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3337 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363338 req->Start();
Wez2a31b222018-06-07 22:07:153339 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583340 EXPECT_EQ(0, network_delegate.set_cookie_count());
estarkcd39c11f2015-10-19 19:46:363341 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3342 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3343 }
3344
3345 // Verify that the cookie is not set.
3346 {
3347 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363348 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163349 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3350 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363351 req->Start();
Wez2a31b222018-06-07 22:07:153352 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363353
jww79aceda2015-12-07 01:56:343354 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363355 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3356 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3357 }
3358}
3359
estarkb15166b2015-12-18 16:56:383360TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553361 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3362 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363363 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553364 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363365
estarkb15166b2015-12-18 16:56:383366 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363367 TestURLRequestContext context(true);
3368 context.set_network_delegate(&network_delegate);
3369 context.Init();
3370
estarkb15166b2015-12-18 16:56:383371 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363372 {
3373 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363374 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103375 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163376 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363377 req->Start();
Wez2a31b222018-06-07 22:07:153378 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363379 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3380 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3381 }
3382
3383 // Verify that the cookie is set.
3384 {
3385 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363386 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163387 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3388 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363389 req->Start();
Wez2a31b222018-06-07 22:07:153390 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363391
jww79aceda2015-12-07 01:56:343392 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3393 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3394 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3395 }
3396}
3397
3398// Tests that secure cookies can't be set on non-secure origins if strict secure
3399// cookies are enabled.
3400TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3401 EmbeddedTestServer http_server;
3402 http_server.AddDefaultHandlers(
3403 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3404 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3405 https_server.AddDefaultHandlers(
3406 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3407 ASSERT_TRUE(http_server.Start());
3408 ASSERT_TRUE(https_server.Start());
3409
Matt Menkebe9b6eb2018-10-18 12:11:443410 TestNetworkDelegate network_delegate;
jww79aceda2015-12-07 01:56:343411 TestURLRequestContext context(true);
3412 context.set_network_delegate(&network_delegate);
3413 context.Init();
3414
3415 // Try to set a Secure cookie, with experimental features enabled.
3416 {
3417 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363418 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343419 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163420 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343421 req->Start();
Wez2a31b222018-06-07 22:07:153422 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343423 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3424 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3425 }
3426
3427 // Verify that the cookie is not set.
3428 {
3429 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363430 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163431 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3432 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343433 req->Start();
Wez2a31b222018-06-07 22:07:153434 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343435
3436 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3437 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3438 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3439 }
3440}
3441
Thiemo Nagel0793b9c532018-04-18 16:57:583442// The parameter is true for same-site and false for cross-site requests.
3443class URLRequestTestParameterizedSameSite
3444 : public URLRequestTest,
3445 public ::testing::WithParamInterface<bool> {
3446 protected:
3447 URLRequestTestParameterizedSameSite() {
3448 auto params = std::make_unique<HttpNetworkSession::Params>();
3449 params->ignore_certificate_errors = true;
3450 context_.set_http_network_session_params(std::move(params));
3451 context_.set_network_delegate(&network_delegate_);
3452 https_server_.AddDefaultHandlers(
3453 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3454 EXPECT_TRUE(https_server_.Start());
3455 }
3456
3457 // To be called after configuration of |context_| has been finalized.
3458 void InitContext() { context_.Init(); }
3459
3460 const std::string kHost_ = "example.test";
3461 const std::string kCrossHost_ = "cross-site.test";
3462 TestURLRequestContext context_{true};
3463 TestNetworkDelegate network_delegate_;
3464 base::HistogramTester histograms_;
3465 EmbeddedTestServer https_server_{EmbeddedTestServer::TYPE_HTTPS};
3466};
3467
Victor Costan8fb98f6f2019-02-01 17:08:293468INSTANTIATE_TEST_SUITE_P(URLRequestTest,
3469 URLRequestTestParameterizedSameSite,
3470 ::testing::Bool());
Thiemo Nagel0793b9c532018-04-18 16:57:583471
3472TEST_P(URLRequestTestParameterizedSameSite, CookieAgeMetrics) {
3473 const bool same_site = GetParam();
3474 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3475 InitContext();
3476
Mike West86149882017-07-28 10:41:493477 EmbeddedTestServer http_server;
3478 http_server.AddDefaultHandlers(
3479 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
Thiemo Nagel23e0b322018-04-18 12:46:543480 ASSERT_TRUE(http_server.Start());
3481
Thiemo Nagel0793b9c532018-04-18 16:57:583482 // Set two test cookies.
Thiemo Nagel23e0b322018-04-18 12:46:543483 {
3484 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583485 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3486 http_server.GetURL(kHost_, "/set-cookie?cookie=value&cookie2=value2"),
Thiemo Nagel23e0b322018-04-18 12:46:543487 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3488 req->Start();
Wez2a31b222018-06-07 22:07:153489 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583490 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3491 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3492 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3493 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3494 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 0);
3495 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3496 0);
3497 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3498 0);
3499 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3500 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 0);
Thiemo Nagel23e0b322018-04-18 12:46:543501 }
3502
Thiemo Nagel0793b9c532018-04-18 16:57:583503 // Make a secure request.
Thiemo Nagel23e0b322018-04-18 12:46:543504 {
3505 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583506 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3507 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3508 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3509 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103510 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583511 url::Origin::Create(https_server_.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103512 req->Start();
Wez2a31b222018-06-07 22:07:153513 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583514 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3515 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3516 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3517 !same_site);
3518 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3519 same_site);
3520 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3521 0);
3522 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3523 0);
3524 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3525 same_site ? 0 : 2);
3526 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3527 same_site ? 2 : 0);
3528 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3529 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
Mohsen Izadiad6f7592018-04-18 15:57:103530 }
3531
Thiemo Nagel0793b9c532018-04-18 16:57:583532 // Make a non-secure request.
Mohsen Izadiad6f7592018-04-18 15:57:103533 {
3534 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583535 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3536 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
Mohsen Izadiad6f7592018-04-18 15:57:103537 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel0793b9c532018-04-18 16:57:583538 req->set_site_for_cookies(http_server.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103539 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583540 url::Origin::Create(http_server.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103541 req->Start();
Wez2a31b222018-06-07 22:07:153542 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583543 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest",
3544 !same_site);
3545 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest",
3546 same_site);
3547 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3548 !same_site);
3549 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3550 same_site);
3551 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3552 same_site ? 0 : 2);
3553 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3554 same_site ? 2 : 0);
3555 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3556 same_site ? 0 : 2);
3557 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3558 same_site ? 2 : 0);
3559 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3560 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
3561 }
3562}
3563
3564// Cookies with secure attribute (no HSTS) --> k1pSecureAttribute
3565TEST_P(URLRequestTestParameterizedSameSite,
3566 CookieNetworkSecurityMetricSecureAttribute) {
3567 const bool same_site = GetParam();
3568 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3569 InitContext();
3570
3571 // Set cookies.
3572 {
3573 TestDelegate d;
3574 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3575 https_server_.GetURL(kHost_,
3576 "/set-cookie?session-cookie=value;Secure&"
3577 "longlived-cookie=value;Secure;domain=" +
3578 kHost_ + ";Max-Age=360000"),
3579 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3580 req->Start();
Wez2a31b222018-06-07 22:07:153581 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583582 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3583 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3584 }
3585
3586 // Verify that the cookies fall into the correct metrics bucket.
3587 {
3588 TestDelegate d;
3589 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3590 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3591 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3592 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3593 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3594 req->Start();
Wez2a31b222018-06-07 22:07:153595 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583596 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3597 // Static cast of boolean required for MSVC 1911.
3598 histograms_.ExpectBucketCount(
3599 "Cookie.NetworkSecurity",
3600 static_cast<int>(CookieNetworkSecurity::k1pSecureAttribute) |
3601 static_cast<int>(!same_site),
3602 2);
3603 }
3604}
3605
3606// Short-lived host cookie --> k1pHSTSHostCookie
3607TEST_P(URLRequestTestParameterizedSameSite,
3608 CookieNetworkSecurityMetricShortlivedHostCookie) {
3609 const bool same_site = GetParam();
3610 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3611
3612 TransportSecurityState transport_security_state;
3613 transport_security_state.AddHSTS(
3614 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3615 false /* include_subdomains */);
3616 context_.set_transport_security_state(&transport_security_state);
3617 InitContext();
3618
3619 // Set cookie.
3620 {
3621 TestDelegate d;
3622 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3623 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;Max-Age=3600"),
3624 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3625 req->Start();
Wez2a31b222018-06-07 22:07:153626 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583627 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3628 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3629 }
3630
3631 // Verify that the cookie falls into the correct metrics bucket.
3632 {
3633 TestDelegate d;
3634 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3635 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3636 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3637 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3638 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3639 req->Start();
Wez2a31b222018-06-07 22:07:153640 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583641 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3642 // Static cast of boolean required for MSVC 1911.
3643 histograms_.ExpectBucketCount(
3644 "Cookie.NetworkSecurity",
3645 static_cast<int>(CookieNetworkSecurity::k1pHSTSHostCookie) |
3646 static_cast<int>(!same_site),
3647 1);
3648 }
3649}
3650
3651// Long-lived (either due to expiry or due to being a session cookie) host
3652// cookies --> k1pExpiringHSTSHostCookie
3653TEST_P(URLRequestTestParameterizedSameSite,
3654 CookieNetworkSecurityMetricLonglivedHostCookie) {
3655 const bool same_site = GetParam();
3656 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3657
3658 TransportSecurityState transport_security_state;
3659 transport_security_state.AddHSTS(
3660 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3661 false /* include_subdomains */);
3662 context_.set_transport_security_state(&transport_security_state);
3663 InitContext();
3664
3665 // Set cookies.
3666 {
3667 TestDelegate d;
3668 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3669 https_server_.GetURL(kHost_,
3670 "/set-cookie?session-cookie=value&"
3671 "longlived-cookie=value;Max-Age=360000"),
3672 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3673 req->Start();
Wez2a31b222018-06-07 22:07:153674 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583675 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3676 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3677 }
3678
3679 // Verify that the cookies fall into the correct metrics bucket.
3680 {
3681 TestDelegate d;
3682 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3683 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3684 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3685 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3686 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3687 req->Start();
Wez2a31b222018-06-07 22:07:153688 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583689 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3690 // Static cast of boolean required for MSVC 1911.
3691 histograms_.ExpectBucketCount(
3692 "Cookie.NetworkSecurity",
3693 static_cast<int>(CookieNetworkSecurity::k1pExpiringHSTSHostCookie) |
3694 static_cast<int>(!same_site),
3695 2);
3696 }
3697}
3698
3699// Domain cookie with HSTS subdomains with cookie expiry before HSTS expiry -->
3700// k1pHSTSSubdomainsIncluded
3701TEST_P(URLRequestTestParameterizedSameSite,
3702 CookieNetworkSecurityMetricShortlivedDomainCookie) {
3703 const bool same_site = GetParam();
3704 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3705
3706 TransportSecurityState transport_security_state;
3707 transport_security_state.AddHSTS(
3708 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3709 true /* include_subdomains */);
3710 context_.set_transport_security_state(&transport_security_state);
3711 InitContext();
3712
3713 // Set cookie.
3714 {
3715 TestDelegate d;
3716 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3717 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3718 kHost_ + ";Max-Age=3600"),
3719 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3720 req->Start();
Wez2a31b222018-06-07 22:07:153721 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583722 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3723 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3724 }
3725
3726 // Verify that the cookie falls into the correct metrics bucket.
3727 {
3728 TestDelegate d;
3729 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3730 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3731 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3732 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3733 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3734 req->Start();
Wez2a31b222018-06-07 22:07:153735 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583736 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3737 // Static cast of boolean required for MSVC 1911.
3738 histograms_.ExpectBucketCount(
3739 "Cookie.NetworkSecurity",
3740 static_cast<int>(CookieNetworkSecurity::k1pHSTSSubdomainsIncluded) |
3741 static_cast<int>(!same_site),
3742 1);
3743 }
3744}
3745
3746// Long-lived (either due to expiry or due to being a session cookie) domain
3747// cookies with HSTS subdomains --> k1pExpiringHSTSSubdomainsIncluded
3748TEST_P(URLRequestTestParameterizedSameSite,
3749 CookieNetworkSecurityMetricLonglivedDomainCookie) {
3750 const bool same_site = GetParam();
3751 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3752
3753 TransportSecurityState transport_security_state;
3754 transport_security_state.AddHSTS(
3755 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3756 true /* include_subdomains */);
3757 context_.set_transport_security_state(&transport_security_state);
3758 InitContext();
3759
3760 // Set cookies.
3761 {
3762 TestDelegate d;
3763 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3764 https_server_.GetURL(
3765 kHost_, "/set-cookie?session-cookie=value;domain=" + kHost_ + "&" +
3766 "longlived-cookie=value;domain=" + kHost_ +
3767 ";Max-Age=360000"),
3768 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3769 req->Start();
Wez2a31b222018-06-07 22:07:153770 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583771 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3772 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3773 }
3774
3775 // Verify that the cookies fall into the correct metrics bucket.
3776 {
3777 TestDelegate d;
3778 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3779 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3780 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3781 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3782 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3783 req->Start();
Wez2a31b222018-06-07 22:07:153784 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583785 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3786 // Static cast of boolean required for MSVC 1911.
3787 histograms_.ExpectBucketCount(
3788 "Cookie.NetworkSecurity",
3789 static_cast<int>(
3790 CookieNetworkSecurity::k1pExpiringHSTSSubdomainsIncluded) |
3791 static_cast<int>(!same_site),
3792 2);
3793 }
3794}
3795
3796// Domain cookie with HSTS subdomains not included --> k1pHSTSSpoofable
3797TEST_P(URLRequestTestParameterizedSameSite,
3798 CookieNetworkSecurityMetricSpoofableDomainCookie) {
3799 const bool same_site = GetParam();
3800 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3801
3802 TransportSecurityState transport_security_state;
3803 transport_security_state.AddHSTS(
3804 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3805 false /* include_subdomains */);
3806 context_.set_transport_security_state(&transport_security_state);
3807 InitContext();
3808
3809 // Set cookie.
3810 {
3811 TestDelegate d;
3812 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3813 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3814 kHost_ + ";Max-Age=3600"),
3815 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3816 req->Start();
Wez2a31b222018-06-07 22:07:153817 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583818 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3819 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3820 }
3821
3822 // Verify that the cookie falls into the correct metrics bucket.
3823 {
3824 TestDelegate d;
3825 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3826 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3827 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3828 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3829 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3830 req->Start();
Wez2a31b222018-06-07 22:07:153831 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583832 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3833 // Static cast of boolean required for MSVC 1911.
3834 histograms_.ExpectBucketCount(
3835 "Cookie.NetworkSecurity",
3836 static_cast<int>(CookieNetworkSecurity::k1pHSTSSpoofable) |
3837 static_cast<int>(!same_site),
3838 1);
3839 }
3840}
3841
3842// Cookie without HSTS --> k1p(Non)SecureConnection
3843TEST_P(URLRequestTestParameterizedSameSite, CookieNetworkSecurityMetricNoHSTS) {
3844 const bool same_site = GetParam();
3845 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3846 InitContext();
3847
3848 EmbeddedTestServer http_server;
3849 http_server.AddDefaultHandlers(
3850 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3851 ASSERT_TRUE(http_server.Start());
3852
3853 // Set cookies.
3854 {
3855 TestDelegate d;
3856 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3857 https_server_.GetURL(kHost_,
3858 "/set-cookie?cookie=value;domain=" + kHost_ +
3859 ";Max-Age=3600&host-cookie=value"),
3860 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3861 req->Start();
Wez2a31b222018-06-07 22:07:153862 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583863 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3864 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3865 }
3866
3867 // Verify that the cookie falls into the correct metrics bucket.
3868 {
3869 TestDelegate d;
3870 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3871 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3872 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3873 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3874 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3875 req->Start();
Wez2a31b222018-06-07 22:07:153876 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583877 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3878 // Static cast of boolean required for MSVC 1911.
3879 histograms_.ExpectBucketCount(
3880 "Cookie.NetworkSecurity",
3881 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3882 static_cast<int>(!same_site),
3883 2);
3884 }
3885
3886 // Verify that the cookie falls into the correct metrics bucket.
3887 {
3888 TestDelegate d;
3889 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3890 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3891 TRAFFIC_ANNOTATION_FOR_TESTS));
3892 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3893 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3894 req->Start();
Wez2a31b222018-06-07 22:07:153895 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583896 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 4);
3897 // Static cast of boolean required for MSVC 1911.
3898 histograms_.ExpectBucketCount(
3899 "Cookie.NetworkSecurity",
3900 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3901 static_cast<int>(!same_site),
3902 2);
3903 // Static cast of boolean required for MSVC 1911.
3904 histograms_.ExpectBucketCount(
3905 "Cookie.NetworkSecurity",
3906 static_cast<int>(CookieNetworkSecurity::k1pNonsecureConnection) |
3907 static_cast<int>(!same_site),
3908 2);
Mike West86149882017-07-28 10:41:493909 }
3910}
3911
mmenkefb18c772015-09-30 22:22:503912// Tests that a request is cancelled while entering suspend mode. Uses mocks
3913// rather than a spawned test server because the connection used to talk to
3914// the test server is affected by entering suspend mode on Android.
3915TEST_F(URLRequestTest, CancelOnSuspend) {
3916 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363917 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503918
3919 URLRequestFailedJob::AddUrlHandler();
3920
3921 TestDelegate d;
3922 // Request that just hangs.
3923 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
Ryan Sleevib8449e02018-07-15 04:31:073924 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163925 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mmenkefb18c772015-09-30 22:22:503926 r->Start();
3927
3928 power_monitor_source->Suspend();
3929 // Wait for the suspend notification to cause the request to fail.
Wez2a31b222018-06-07 22:07:153930 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:503931 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503932 EXPECT_TRUE(d.request_failed());
3933 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3934
3935 URLRequestFilter::GetInstance()->ClearHandlers();
3936
3937 // Shouldn't be needed, but just in case.
3938 power_monitor_source->Resume();
3939}
3940
[email protected]5095cd72012-11-01 10:29:163941// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3942// value for the |fixed_date| argument given to the constructor.
3943class FixedDateNetworkDelegate : public TestNetworkDelegate {
3944 public:
3945 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3946 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:273947 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:163948
[email protected]cba24642014-08-15 20:49:593949 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203950 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593951 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:203952 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:593953 const HttpResponseHeaders* original_response_headers,
3954 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133955 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163956
3957 private:
3958 std::string fixed_date_;
3959
3960 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3961};
3962
3963int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593964 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:203965 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:593966 const HttpResponseHeaders* original_response_headers,
3967 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163968 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593969 HttpResponseHeaders* new_response_headers =
3970 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163971
3972 new_response_headers->RemoveHeader("Date");
3973 new_response_headers->AddHeader("Date: " + fixed_date_);
3974
3975 *override_response_headers = new_response_headers;
David Benjamind1f287bf2018-06-12 01:57:203976 return TestNetworkDelegate::OnHeadersReceived(
3977 request, std::move(callback), original_response_headers,
3978 override_response_headers, allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163979}
3980
3981// Test that cookie expiration times are adjusted for server/client clock
3982// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3983// headers by defaulting to GMT. (crbug.com/135131)
3984TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:393985 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:163986 ASSERT_TRUE(test_server.Start());
3987
3988 // Set up an expired cookie.
3989 {
3990 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073991 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:163992 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073993 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193994 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553995 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163996 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193997 req->Start();
Wez2a31b222018-06-07 22:07:153998 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163999 }
4000 // Verify that the cookie is not set.
4001 {
4002 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074003 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164004 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074005 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164006 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4007 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194008 req->Start();
Wez2a31b222018-06-07 22:07:154009 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164010
4011 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
4012 }
4013 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
4014 {
4015 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
Ryan Sleevib8449e02018-07-15 04:31:074016 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164017 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074018 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194019 test_server.GetURL(
tommycli59a63432015-11-06 00:10:554020 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:164021 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194022 req->Start();
Wez2a31b222018-06-07 22:07:154023 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164024 }
4025 // Verify that the cookie is set.
4026 {
4027 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074028 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164029 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074030 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164031 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4032 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194033 req->Start();
Wez2a31b222018-06-07 22:07:154034 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164035
4036 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
4037 }
4038}
4039
4040
[email protected]316c1e5e2012-09-12 15:17:444041// Check that it is impossible to change the referrer in the extra headers of
4042// an URLRequest.
4043TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:394044 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:444045 ASSERT_TRUE(test_server.Start());
4046
4047 // If extra headers contain referer and the request contains a referer,
4048 // only the latter shall be respected.
4049 {
4050 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074051 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164052 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4053 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194054 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:444055
4056 HttpRequestHeaders headers;
4057 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194058 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:444059
[email protected]f7022f32014-08-21 16:32:194060 req->Start();
Wez2a31b222018-06-07 22:07:154061 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444062
4063 EXPECT_EQ("http://foo.com/", d.data_received());
4064 }
4065
4066 // If extra headers contain a referer but the request does not, no referer
4067 // shall be sent in the header.
4068 {
4069 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074070 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164071 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4072 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:444073
4074 HttpRequestHeaders headers;
4075 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194076 req->SetExtraRequestHeaders(headers);
4077 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:444078
[email protected]f7022f32014-08-21 16:32:194079 req->Start();
Wez2a31b222018-06-07 22:07:154080 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444081
4082 EXPECT_EQ("None", d.data_received());
4083 }
4084}
4085
[email protected]b89290212009-08-14 22:37:354086class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:114087 public:
mmenke9f2ec60c2015-06-01 20:59:474088 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:114089
[email protected]b89290212009-08-14 22:37:354090 protected:
[email protected]21184962011-10-26 00:50:304091 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
4092 // |request_method| is the method to use for the initial request.
4093 // |redirect_method| is the method that is expected to be used for the second
4094 // request, after redirection.
4095 // If |include_data| is true, data is uploaded with the request. The
4096 // response body is expected to match it exactly, if and only if
4097 // |request_method| == |redirect_method|.
4098 void HTTPRedirectMethodTest(const GURL& redirect_url,
4099 const std::string& request_method,
4100 const std::string& redirect_method,
4101 bool include_data) {
4102 static const char kData[] = "hello world";
4103 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074104 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164105 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194106 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:304107 if (include_data) {
mmenkecbc2b712014-10-09 20:29:074108 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:304109 HttpRequestHeaders headers;
4110 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244111 base::NumberToString(base::size(kData) - 1));
svaldez5b3a8972015-10-09 23:23:544112 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:194113 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:304114 }
[email protected]f7022f32014-08-21 16:32:194115 req->Start();
Wez2a31b222018-06-07 22:07:154116 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194117 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:504118 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:304119 if (include_data) {
4120 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:544121 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4122 HttpRequestHeaders::kContentLength));
4123 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4124 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304125 EXPECT_EQ(kData, d.data_received());
4126 } else {
svaldez5b3a8972015-10-09 23:23:544127 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4128 HttpRequestHeaders::kContentLength));
4129 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4130 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304131 EXPECT_NE(kData, d.data_received());
4132 }
4133 }
4134 if (HasFailure())
4135 LOG(WARNING) << "Request method was: " << request_method;
4136 }
4137
Alex Clarke1e08882b32017-10-06 14:22:404138 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
4139 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:514140 // |request_method| is the method to use for the initial request.
4141 // |redirect_method| is the method that is expected to be used for the second
4142 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:404143 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:514144 // redirection. If empty, expects that there will be no Origin header.
4145 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
4146 const std::string& request_method,
4147 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:404148 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:514149 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074150 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164151 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:514152 req->set_method(request_method);
4153 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
4154 redirect_url.GetOrigin().spec(), false);
4155 req->Start();
4156
Wez2a31b222018-06-07 22:07:154157 d.RunUntilComplete();
jww5fe460ff2015-03-28 00:22:514158
4159 EXPECT_EQ(redirect_method, req->method());
4160 // Note that there is no check for request success here because, for
4161 // purposes of testing, the request very well may fail. For example, if the
4162 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
4163 // origin, there is not an HTTPS server in this unit test framework, so the
4164 // request would fail. However, that's fine, as long as the request headers
4165 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:404166 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:514167 EXPECT_FALSE(
4168 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
4169 } else {
4170 std::string origin_header;
4171 EXPECT_TRUE(req->extra_request_headers().GetHeader(
4172 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:404173 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:514174 }
4175 }
4176
[email protected]762d2db2010-01-11 19:03:014177 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:014178 const int kMsgSize = 20000; // multiple of 10
4179 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:484180 char* uploadBytes = new char[kMsgSize+1];
4181 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:014182 char marker = 'a';
4183 for (int idx = 0; idx < kMsgSize/10; idx++) {
4184 memcpy(ptr, "----------", 10);
4185 ptr += 10;
4186 if (idx % 100 == 0) {
4187 ptr--;
4188 *ptr++ = marker;
4189 if (++marker > 'z')
4190 marker = 'a';
4191 }
4192 }
4193 uploadBytes[kMsgSize] = '\0';
4194
[email protected]762d2db2010-01-11 19:03:014195 for (int i = 0; i < kIterations; ++i) {
4196 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074197 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164198 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
4199 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194200 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:014201
mmenkecbc2b712014-10-09 20:29:074202 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:014203
[email protected]f7022f32014-08-21 16:32:194204 r->Start();
4205 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:014206
Wez2a31b222018-06-07 22:07:154207 d.RunUntilComplete();
[email protected]762d2db2010-01-11 19:03:014208
maksim.sisovb53724b52016-09-16 05:30:504209 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
4210 << d.request_status();
[email protected]762d2db2010-01-11 19:03:014211
4212 EXPECT_FALSE(d.received_data_before_response());
4213 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:014214 }
4215 delete[] uploadBytes;
4216 }
4217
[email protected]ede03212012-09-07 12:52:264218 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:344219 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074220 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:554221 test_server_.GetURL("/set-many-cookies?" +
Raul Tambre8c1981d2019-02-08 02:22:264222 base::NumberToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:164223 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:344224
[email protected]f7022f32014-08-21 16:32:194225 r->Start();
4226 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:344227
Wez2a31b222018-06-07 22:07:154228 d.RunUntilComplete();
[email protected]263163f2012-06-14 22:40:344229
maksim.sisovb53724b52016-09-16 05:30:504230 if (d.request_status() != OK) {
4231 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
4232 return false;
4233 }
[email protected]263163f2012-06-14 22:40:344234
maksim.sisovb53724b52016-09-16 05:30:504235 return true;
[email protected]263163f2012-06-14 22:40:344236 }
4237
David Benjamin42116f62017-11-20 21:45:394238 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:504239
tommycli59a63432015-11-06 00:10:554240 private:
David Benjamin42116f62017-11-20 21:45:394241 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:354242};
4243
tommycli59a63432015-11-06 00:10:554244namespace {
4245
danakj8522a25b2016-04-16 00:17:364246std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:554247 const test_server::HttpRequest& request) {
4248 if (request.headers.find("Host") == request.headers.end() ||
4249 request.headers.at("Host") != "www.redirect.com" ||
4250 request.method != test_server::METHOD_CONNECT) {
4251 return nullptr;
4252 }
4253
danakj8522a25b2016-04-16 00:17:364254 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554255 new test_server::BasicHttpResponse);
4256 http_response->set_code(HTTP_FOUND);
4257 http_response->AddCustomHeader("Location",
4258 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:484259 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554260}
4261
nharperb7441ef2016-01-25 23:54:144262class TestSSLConfigService : public SSLConfigService {
4263 public:
Nick Harper2243e8002018-09-28 20:33:264264 TestSSLConfigService()
4265 : min_version_(kDefaultSSLVersionMin),
davidben095ebb52017-04-12 22:23:344266 max_version_(kDefaultSSLVersionMax) {}
Ryan Sleevib8449e02018-07-15 04:31:074267 ~TestSSLConfigService() override = default;
nharperb7441ef2016-01-25 23:54:144268
davidben095ebb52017-04-12 22:23:344269 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:144270 void set_min_version(uint16_t version) { min_version_ = version; }
4271
nharperb7441ef2016-01-25 23:54:144272 // SSLConfigService:
4273 void GetSSLConfig(SSLConfig* config) override {
4274 *config = SSLConfig();
davidben095ebb52017-04-12 22:23:344275 config->version_min = min_version_;
4276 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:144277 }
4278
Nick Harper89bc7212018-07-31 19:07:574279 bool CanShareConnectionWithClientCerts(
4280 const std::string& hostname) const override {
4281 return false;
4282 }
4283
nharperb7441ef2016-01-25 23:54:144284 private:
nharperb7441ef2016-01-25 23:54:144285 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:344286 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:144287};
4288
Nick Harper89bc7212018-07-31 19:07:574289} // namespace
4290
nharperb7441ef2016-01-25 23:54:144291// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114292// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:554293// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:114294// follow.
[email protected]f2f31b32013-01-16 23:24:094295TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:554296 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124297 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:554298 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114299
[email protected]ceefd7fd2012-11-29 00:36:244300 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044301 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554302 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504303
[email protected]d1ec59082009-02-11 02:48:154304 TestDelegate d;
4305 {
danakj8522a25b2016-04-16 00:17:364306 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164307 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4308 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194309 r->Start();
4310 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:154311
Wez2a31b222018-06-07 22:07:154312 d.RunUntilComplete();
[email protected]d1ec59082009-02-11 02:48:154313
[email protected]d8fc4722014-06-13 13:17:154314 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474315 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504316 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084317 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:154318 // We should not have followed the redirect.
4319 EXPECT_EQ(0, d.received_redirect_count());
4320 }
4321}
4322
[email protected]8202d0c2011-02-23 08:31:144323// This is the same as the previous test, but checks that the network delegate
4324// registers the error.
[email protected]c044616e2013-02-20 02:01:264325TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554326 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144327
[email protected]ceefd7fd2012-11-29 00:36:244328 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044329 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554330 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504331
[email protected]8202d0c2011-02-23 08:31:144332 TestDelegate d;
4333 {
danakj8522a25b2016-04-16 00:17:364334 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164335 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4336 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194337 r->Start();
4338 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144339
Wez2a31b222018-06-07 22:07:154340 d.RunUntilComplete();
[email protected]8202d0c2011-02-23 08:31:144341
[email protected]d8fc4722014-06-13 13:17:154342 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474343 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:144344 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504345 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144346 // We should not have followed the redirect.
4347 EXPECT_EQ(0, d.received_redirect_count());
4348
4349 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014350 EXPECT_THAT(network_delegate.last_error(),
4351 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144352 }
4353}
4354
[email protected]dc5a5cf2012-09-26 02:49:304355// Tests that we can block and asynchronously return OK in various stages.
4356TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4357 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4358 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4359 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4360 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4361 };
Avi Drissman4365a4782018-12-28 19:26:244362 static const size_t blocking_stages_length = base::size(blocking_stages);
[email protected]dc5a5cf2012-09-26 02:49:304363
tommycli59a63432015-11-06 00:10:554364 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304365
4366 TestDelegate d;
4367 BlockingNetworkDelegate network_delegate(
4368 BlockingNetworkDelegate::USER_CALLBACK);
4369 network_delegate.set_block_on(
4370 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4371 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4372 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4373
4374 TestURLRequestContext context(true);
4375 context.set_network_delegate(&network_delegate);
4376 context.Init();
4377
4378 {
danakj8522a25b2016-04-16 00:17:364379 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164380 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4381 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304382
[email protected]f7022f32014-08-21 16:32:194383 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304384 for (size_t i = 0; i < blocking_stages_length; ++i) {
Wez2a31b222018-06-07 22:07:154385 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304386 EXPECT_EQ(blocking_stages[i],
4387 network_delegate.stage_blocked_for_callback());
4388 network_delegate.DoCallback(OK);
4389 }
Wez2a31b222018-06-07 22:07:154390 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194391 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504392 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304393 EXPECT_EQ(1, network_delegate.created_requests());
4394 EXPECT_EQ(0, network_delegate.destroyed_requests());
4395 }
4396 EXPECT_EQ(1, network_delegate.destroyed_requests());
4397}
4398
[email protected]4c76d7c2011-04-15 19:14:124399// Tests that the network delegate can block and cancel a request.
4400TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554401 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124402
4403 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304404 BlockingNetworkDelegate network_delegate(
4405 BlockingNetworkDelegate::AUTO_CALLBACK);
4406 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4407 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124408
[email protected]d5a4dd62012-05-23 01:41:044409 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554410 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504411
[email protected]4c76d7c2011-04-15 19:14:124412 {
rhalavatib7bd7c792017-04-27 05:25:164413 std::unique_ptr<URLRequest> r(
4414 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4415 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124416
[email protected]f7022f32014-08-21 16:32:194417 r->Start();
Wez2a31b222018-06-07 22:07:154418 d.RunUntilComplete();
[email protected]4c76d7c2011-04-15 19:14:124419
[email protected]d8fc4722014-06-13 13:17:154420 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474421 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504422 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124423 EXPECT_EQ(1, network_delegate.created_requests());
4424 EXPECT_EQ(0, network_delegate.destroyed_requests());
4425 }
4426 EXPECT_EQ(1, network_delegate.destroyed_requests());
4427}
4428
[email protected]b4438d32012-09-27 06:15:304429// Helper function for NetworkDelegateCancelRequestAsynchronously and
4430// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4431// delegate operating in |block_mode| and a request for |url|. It blocks the
4432// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4433void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4434 BlockingNetworkDelegate::Stage stage,
4435 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364436 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304437 BlockingNetworkDelegate network_delegate(block_mode);
4438 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4439 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364440
[email protected]b4438d32012-09-27 06:15:304441 TestURLRequestContext context(true);
4442 context.set_network_delegate(&network_delegate);
4443 context.Init();
[email protected]3cd384c602011-08-31 16:12:364444
4445 {
rhalavatib7bd7c792017-04-27 05:25:164446 std::unique_ptr<URLRequest> r(context.CreateRequest(
4447 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364448
[email protected]f7022f32014-08-21 16:32:194449 r->Start();
Wez2a31b222018-06-07 22:07:154450 d.RunUntilComplete();
[email protected]3cd384c602011-08-31 16:12:364451
[email protected]d8fc4722014-06-13 13:17:154452 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474453 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4454 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4455 EXPECT_FALSE(r->proxy_server().is_valid());
4456 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4457 EXPECT_TRUE(r->proxy_server().is_direct());
4458 } else {
4459 NOTREACHED();
4460 }
maksim.sisovb53724b52016-09-16 05:30:504461 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364462 EXPECT_EQ(1, network_delegate.created_requests());
4463 EXPECT_EQ(0, network_delegate.destroyed_requests());
4464 }
4465 EXPECT_EQ(1, network_delegate.destroyed_requests());
4466}
4467
[email protected]b4438d32012-09-27 06:15:304468// The following 3 tests check that the network delegate can cancel a request
4469// synchronously in various stages of the request.
4470TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554471 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304472 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4473 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554474 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304475}
4476
4477TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554478 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304479 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4480 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554481 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304482}
4483
4484TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554485 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304486 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4487 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554488 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304489}
4490
4491// The following 3 tests check that the network delegate can cancel a request
4492// asynchronously in various stages of the request.
4493TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554494 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304495 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4496 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554497 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304498}
4499
4500TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554501 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304502 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4503 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554504 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304505}
4506
4507TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554508 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304509 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4510 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554511 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304512}
4513
[email protected]4c76d7c2011-04-15 19:14:124514// Tests that the network delegate can block and redirect a request to a new
4515// URL.
4516TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554517 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124518
4519 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304520 BlockingNetworkDelegate network_delegate(
4521 BlockingNetworkDelegate::AUTO_CALLBACK);
4522 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
Eric Romanda790f92018-11-07 19:17:154523 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]4c76d7c2011-04-15 19:14:124524 network_delegate.set_redirect_url(redirect_url);
4525
[email protected]d5a4dd62012-05-23 01:41:044526 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554527 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504528
[email protected]4c76d7c2011-04-15 19:14:124529 {
Eric Romanda790f92018-11-07 19:17:154530 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164531 std::unique_ptr<URLRequest> r(context.CreateRequest(
4532 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124533
[email protected]6be6fa92014-08-06 23:44:564534 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194535 r->Start();
Wez0e717112018-06-18 23:09:224536 d.RunUntilRedirect();
[email protected]4c76d7c2011-04-15 19:14:124537
[email protected]6be6fa92014-08-06 23:44:564538 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194539 EXPECT_EQ(307, r->GetResponseCode());
4540 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564541 std::string location;
Raul Tambre94493c652019-03-11 17:18:354542 ASSERT_TRUE(
4543 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564544 EXPECT_EQ(redirect_url, GURL(location));
4545
4546 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354547 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4548 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154549 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:504550 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474551 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4552 http_test_server()->host_port_pair()),
4553 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094554 // before_send_headers_with_proxy_count only increments for headers sent
4555 // through an untunneled proxy.
4556 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554557 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4558 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274559
maksim.sisovb53724b52016-09-16 05:30:504560 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194561 EXPECT_EQ(redirect_url, r->url());
4562 EXPECT_EQ(original_url, r->original_url());
4563 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124564 EXPECT_EQ(1, network_delegate.created_requests());
4565 EXPECT_EQ(0, network_delegate.destroyed_requests());
4566 }
4567 EXPECT_EQ(1, network_delegate.destroyed_requests());
4568}
4569
[email protected]b813ed72012-04-05 08:21:364570// Tests that the network delegate can block and redirect a request to a new
4571// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4572TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554573 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364574
4575 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304576 BlockingNetworkDelegate network_delegate(
4577 BlockingNetworkDelegate::SYNCHRONOUS);
Eric Romanda790f92018-11-07 19:17:154578 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]b813ed72012-04-05 08:21:364579 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364580
[email protected]d5a4dd62012-05-23 01:41:044581 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554582 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364583
4584 {
Eric Romanda790f92018-11-07 19:17:154585 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164586 std::unique_ptr<URLRequest> r(context.CreateRequest(
4587 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364588
[email protected]6be6fa92014-08-06 23:44:564589 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194590 r->Start();
Wez0e717112018-06-18 23:09:224591 d.RunUntilRedirect();
[email protected]b813ed72012-04-05 08:21:364592
[email protected]6be6fa92014-08-06 23:44:564593 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194594 EXPECT_EQ(307, r->GetResponseCode());
4595 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564596 std::string location;
Raul Tambre94493c652019-03-11 17:18:354597 ASSERT_TRUE(
4598 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564599 EXPECT_EQ(redirect_url, GURL(location));
4600
4601 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354602 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4603 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154604 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564605
maksim.sisovb53724b52016-09-16 05:30:504606 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474607 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4608 http_test_server()->host_port_pair()),
4609 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094610 // before_send_headers_with_proxy_count only increments for headers sent
4611 // through an untunneled proxy.
4612 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554613 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4614 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504615 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194616 EXPECT_EQ(redirect_url, r->url());
4617 EXPECT_EQ(original_url, r->original_url());
4618 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364619 EXPECT_EQ(1, network_delegate.created_requests());
4620 EXPECT_EQ(0, network_delegate.destroyed_requests());
4621 }
4622 EXPECT_EQ(1, network_delegate.destroyed_requests());
4623}
4624
[email protected]3c5ca8c2011-09-29 01:14:514625// Tests that redirects caused by the network delegate preserve POST data.
4626TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554627 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514628
4629 const char kData[] = "hello world";
4630
4631 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304632 BlockingNetworkDelegate network_delegate(
4633 BlockingNetworkDelegate::AUTO_CALLBACK);
4634 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554635 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514636 network_delegate.set_redirect_url(redirect_url);
4637
[email protected]ef2bf422012-05-11 03:27:094638 TestURLRequestContext context(true);
4639 context.set_network_delegate(&network_delegate);
4640 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514641
4642 {
tommycli59a63432015-11-06 00:10:554643 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164644 std::unique_ptr<URLRequest> r(context.CreateRequest(
4645 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194646 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074647 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514648 HttpRequestHeaders headers;
4649 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244650 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194651 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564652
4653 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194654 r->Start();
Wez0e717112018-06-18 23:09:224655 d.RunUntilRedirect();
[email protected]3c5ca8c2011-09-29 01:14:514656
[email protected]6be6fa92014-08-06 23:44:564657 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194658 EXPECT_EQ(307, r->GetResponseCode());
4659 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564660 std::string location;
Raul Tambre94493c652019-03-11 17:18:354661 ASSERT_TRUE(
4662 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564663 EXPECT_EQ(redirect_url, GURL(location));
4664
4665 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354666 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4667 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154668 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564669
maksim.sisovb53724b52016-09-16 05:30:504670 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194671 EXPECT_EQ(redirect_url, r->url());
4672 EXPECT_EQ(original_url, r->original_url());
4673 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514674 EXPECT_EQ(1, network_delegate.created_requests());
4675 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194676 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514677 EXPECT_EQ(kData, d.data_received());
4678 }
4679 EXPECT_EQ(1, network_delegate.destroyed_requests());
4680}
4681
[email protected]5f714132014-03-26 10:41:164682// Tests that the network delegate can block and redirect a request to a new
4683// URL during OnHeadersReceived.
4684TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554685 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164686
4687 TestDelegate d;
4688 BlockingNetworkDelegate network_delegate(
4689 BlockingNetworkDelegate::AUTO_CALLBACK);
4690 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
Eric Romanda790f92018-11-07 19:17:154691 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]5f714132014-03-26 10:41:164692 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4693
4694 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554695 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164696
4697 {
Eric Romanda790f92018-11-07 19:17:154698 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164699 std::unique_ptr<URLRequest> r(context.CreateRequest(
4700 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164701
[email protected]f7022f32014-08-21 16:32:194702 r->Start();
Wez2a31b222018-06-07 22:07:154703 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:164704
maksim.sisovb53724b52016-09-16 05:30:504705 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474706 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4707 http_test_server()->host_port_pair()),
4708 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094709 // before_send_headers_with_proxy_count only increments for headers sent
4710 // through an untunneled proxy.
4711 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554712 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4713 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194714
maksim.sisovb53724b52016-09-16 05:30:504715 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194716 EXPECT_EQ(redirect_url, r->url());
4717 EXPECT_EQ(original_url, r->original_url());
4718 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164719 EXPECT_EQ(2, network_delegate.created_requests());
4720 EXPECT_EQ(0, network_delegate.destroyed_requests());
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 taking no action. This indicates that the NetworkDelegate does not want to
4727// handle the challenge, and is passing the buck along to the
4728// URLRequest::Delegate.
4729TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554730 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364731
4732 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304733 BlockingNetworkDelegate network_delegate(
4734 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364735
[email protected]ef2bf422012-05-11 03:27:094736 TestURLRequestContext context(true);
4737 context.set_network_delegate(&network_delegate);
4738 context.Init();
[email protected]c2911d72011-10-03 22:16:364739
[email protected]f3cf9802011-10-28 18:44:584740 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364741
4742 {
tommycli59a63432015-11-06 00:10:554743 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164744 std::unique_ptr<URLRequest> r(context.CreateRequest(
4745 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194746 r->Start();
[email protected]79e1fd62013-06-20 06:50:044747
Wez2a31b222018-06-07 22:07:154748 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044749
maksim.sisovb53724b52016-09-16 05:30:504750 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194751 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044752 EXPECT_TRUE(d.auth_required_called());
4753 EXPECT_EQ(1, network_delegate.created_requests());
4754 EXPECT_EQ(0, network_delegate.destroyed_requests());
4755 }
4756 EXPECT_EQ(1, network_delegate.destroyed_requests());
4757}
4758
4759TEST_F(URLRequestTestHTTP,
4760 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554761 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044762
4763 TestDelegate d;
4764 BlockingNetworkDelegate network_delegate(
4765 BlockingNetworkDelegate::SYNCHRONOUS);
4766
4767 TestURLRequestContext context(true);
4768 context.set_network_delegate(&network_delegate);
4769 context.Init();
4770
4771 d.set_credentials(AuthCredentials(kUser, kSecret));
4772
4773 {
tommycli59a63432015-11-06 00:10:554774 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164775 std::unique_ptr<URLRequest> r(context.CreateRequest(
4776 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194777 r->Start();
[email protected]79e1fd62013-06-20 06:50:044778
Wez2a31b222018-06-07 22:07:154779 d.RunUntilComplete();
shivanisha8061c4202017-06-13 23:35:524780
[email protected]79e1fd62013-06-20 06:50:044781 {
4782 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194783 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524784 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044785 }
4786
maksim.sisovb53724b52016-09-16 05:30:504787 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194788 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364789 EXPECT_TRUE(d.auth_required_called());
4790 EXPECT_EQ(1, network_delegate.created_requests());
4791 EXPECT_EQ(0, network_delegate.destroyed_requests());
4792 }
4793 EXPECT_EQ(1, network_delegate.destroyed_requests());
4794}
4795
4796// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404797// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364798TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554799 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364800
4801 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304802 BlockingNetworkDelegate network_delegate(
4803 BlockingNetworkDelegate::SYNCHRONOUS);
4804 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364805 network_delegate.set_auth_retval(
4806 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4807
[email protected]f3cf9802011-10-28 18:44:584808 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364809
[email protected]ef2bf422012-05-11 03:27:094810 TestURLRequestContext context(true);
4811 context.set_network_delegate(&network_delegate);
4812 context.Init();
[email protected]c2911d72011-10-03 22:16:364813
4814 {
tommycli59a63432015-11-06 00:10:554815 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164816 std::unique_ptr<URLRequest> r(context.CreateRequest(
4817 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194818 r->Start();
Wez2a31b222018-06-07 22:07:154819 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364820
maksim.sisovb53724b52016-09-16 05:30:504821 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194822 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364823 EXPECT_FALSE(d.auth_required_called());
4824 EXPECT_EQ(1, network_delegate.created_requests());
4825 EXPECT_EQ(0, network_delegate.destroyed_requests());
4826 }
4827 EXPECT_EQ(1, network_delegate.destroyed_requests());
4828}
4829
[email protected]79e1fd62013-06-20 06:50:044830// Same as above, but also tests that GetFullRequestHeaders returns the proper
4831// headers (for the first or second request) when called at the proper times.
4832TEST_F(URLRequestTestHTTP,
4833 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554834 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044835
4836 TestDelegate d;
4837 BlockingNetworkDelegate network_delegate(
4838 BlockingNetworkDelegate::SYNCHRONOUS);
4839 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4840 network_delegate.set_auth_retval(
4841 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4842
4843 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4844
4845 TestURLRequestContext context(true);
4846 context.set_network_delegate(&network_delegate);
4847 context.Init();
4848
4849 {
tommycli59a63432015-11-06 00:10:554850 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164851 std::unique_ptr<URLRequest> r(context.CreateRequest(
4852 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194853 r->Start();
Wez2a31b222018-06-07 22:07:154854 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044855
maksim.sisovb53724b52016-09-16 05:30:504856 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194857 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044858 EXPECT_FALSE(d.auth_required_called());
4859 EXPECT_EQ(1, network_delegate.created_requests());
4860 EXPECT_EQ(0, network_delegate.destroyed_requests());
4861
4862 {
4863 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194864 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044865 EXPECT_TRUE(headers.HasHeader("Authorization"));
4866 }
4867 }
4868 EXPECT_EQ(1, network_delegate.destroyed_requests());
4869}
4870
[email protected]c2911d72011-10-03 22:16:364871// Tests that the network delegate can synchronously complete OnAuthRequired
4872// by cancelling authentication.
4873TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554874 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364875
4876 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304877 BlockingNetworkDelegate network_delegate(
4878 BlockingNetworkDelegate::SYNCHRONOUS);
4879 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364880 network_delegate.set_auth_retval(
4881 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4882
[email protected]ef2bf422012-05-11 03:27:094883 TestURLRequestContext context(true);
4884 context.set_network_delegate(&network_delegate);
4885 context.Init();
[email protected]c2911d72011-10-03 22:16:364886
4887 {
tommycli59a63432015-11-06 00:10:554888 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164889 std::unique_ptr<URLRequest> r(context.CreateRequest(
4890 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194891 r->Start();
Wez2a31b222018-06-07 22:07:154892 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364893
maksim.sisovb53724b52016-09-16 05:30:504894 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194895 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364896 EXPECT_FALSE(d.auth_required_called());
4897 EXPECT_EQ(1, network_delegate.created_requests());
4898 EXPECT_EQ(0, network_delegate.destroyed_requests());
4899 }
4900 EXPECT_EQ(1, network_delegate.destroyed_requests());
4901}
4902
4903// Tests that the network delegate can asynchronously complete OnAuthRequired
4904// by taking no action. This indicates that the NetworkDelegate does not want
4905// to handle the challenge, and is passing the buck along to the
4906// URLRequest::Delegate.
4907TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554908 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364909
4910 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304911 BlockingNetworkDelegate network_delegate(
4912 BlockingNetworkDelegate::AUTO_CALLBACK);
4913 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364914
[email protected]ef2bf422012-05-11 03:27:094915 TestURLRequestContext context(true);
4916 context.set_network_delegate(&network_delegate);
4917 context.Init();
[email protected]c2911d72011-10-03 22:16:364918
[email protected]f3cf9802011-10-28 18:44:584919 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364920
4921 {
tommycli59a63432015-11-06 00:10:554922 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164923 std::unique_ptr<URLRequest> r(context.CreateRequest(
4924 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194925 r->Start();
Wez2a31b222018-06-07 22:07:154926 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364927
maksim.sisovb53724b52016-09-16 05:30:504928 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194929 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364930 EXPECT_TRUE(d.auth_required_called());
4931 EXPECT_EQ(1, network_delegate.created_requests());
4932 EXPECT_EQ(0, network_delegate.destroyed_requests());
4933 }
4934 EXPECT_EQ(1, network_delegate.destroyed_requests());
4935}
4936
4937// Tests that the network delegate can asynchronously complete OnAuthRequired
4938// by setting credentials.
4939TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554940 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364941
4942 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304943 BlockingNetworkDelegate network_delegate(
4944 BlockingNetworkDelegate::AUTO_CALLBACK);
4945 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364946 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364947 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4948
[email protected]f3cf9802011-10-28 18:44:584949 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364950 network_delegate.set_auth_credentials(auth_credentials);
4951
[email protected]ef2bf422012-05-11 03:27:094952 TestURLRequestContext context(true);
4953 context.set_network_delegate(&network_delegate);
4954 context.Init();
[email protected]c2911d72011-10-03 22:16:364955
4956 {
tommycli59a63432015-11-06 00:10:554957 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164958 std::unique_ptr<URLRequest> r(context.CreateRequest(
4959 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194960 r->Start();
Wez2a31b222018-06-07 22:07:154961 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364962
maksim.sisovb53724b52016-09-16 05:30:504963 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194964 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364965 EXPECT_FALSE(d.auth_required_called());
4966 EXPECT_EQ(1, network_delegate.created_requests());
4967 EXPECT_EQ(0, network_delegate.destroyed_requests());
4968 }
4969 EXPECT_EQ(1, network_delegate.destroyed_requests());
4970}
4971
4972// Tests that the network delegate can asynchronously complete OnAuthRequired
4973// by cancelling authentication.
4974TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554975 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364976
4977 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304978 BlockingNetworkDelegate network_delegate(
4979 BlockingNetworkDelegate::AUTO_CALLBACK);
4980 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364981 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364982 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4983
[email protected]ef2bf422012-05-11 03:27:094984 TestURLRequestContext context(true);
4985 context.set_network_delegate(&network_delegate);
4986 context.Init();
[email protected]c2911d72011-10-03 22:16:364987
4988 {
tommycli59a63432015-11-06 00:10:554989 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164990 std::unique_ptr<URLRequest> r(context.CreateRequest(
4991 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194992 r->Start();
Wez2a31b222018-06-07 22:07:154993 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364994
maksim.sisovb53724b52016-09-16 05:30:504995 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194996 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364997 EXPECT_FALSE(d.auth_required_called());
4998 EXPECT_EQ(1, network_delegate.created_requests());
4999 EXPECT_EQ(0, network_delegate.destroyed_requests());
5000 }
5001 EXPECT_EQ(1, network_delegate.destroyed_requests());
5002}
5003
David Benjamin0bda12f2018-02-07 19:58:455004// Tests that NetworkDelegate header overrides from the 401 response do not
5005// affect the 200 response. This is a regression test for
5006// https://crbug.com/801237.
5007TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
5008 ASSERT_TRUE(http_test_server()->Start());
5009
5010 TestDelegate d;
5011 d.set_credentials(AuthCredentials(kUser, kSecret));
5012 default_network_delegate_.set_add_header_to_first_response(true);
5013
5014 {
5015 GURL url(http_test_server()->GetURL("/auth-basic"));
Ryan Sleevib8449e02018-07-15 04:31:075016 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455017 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5018 r->Start();
5019
Wez2a31b222018-06-07 22:07:155020 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455021
5022 EXPECT_EQ(OK, d.request_status());
5023 EXPECT_EQ(200, r->GetResponseCode());
5024 EXPECT_TRUE(d.auth_required_called());
5025 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
5026 }
5027
5028 {
5029 GURL url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075030 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455031 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5032 r->Start();
5033
Wez2a31b222018-06-07 22:07:155034 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455035
5036 // Check that set_add_header_to_first_response normally adds a header.
5037 EXPECT_EQ(OK, d.request_status());
5038 EXPECT_EQ(200, r->GetResponseCode());
5039 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
5040 }
5041}
5042
[email protected]9045b8822012-01-13 20:35:355043// Tests that we can handle when a network request was canceled while we were
5044// waiting for the network delegate.
5045// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
5046TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:555047 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355048
5049 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305050 BlockingNetworkDelegate network_delegate(
5051 BlockingNetworkDelegate::USER_CALLBACK);
5052 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:355053
[email protected]ef2bf422012-05-11 03:27:095054 TestURLRequestContext context(true);
5055 context.set_network_delegate(&network_delegate);
5056 context.Init();
[email protected]9045b8822012-01-13 20:35:355057
5058 {
rhalavatib7bd7c792017-04-27 05:25:165059 std::unique_ptr<URLRequest> r(
5060 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5061 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355062
[email protected]f7022f32014-08-21 16:32:195063 r->Start();
Wez2a31b222018-06-07 22:07:155064 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305065 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
5066 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355067 EXPECT_EQ(0, network_delegate.completed_requests());
5068 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195069 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355070 // Ensure that network delegate is notified.
5071 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505072 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355073 EXPECT_EQ(1, network_delegate.created_requests());
5074 EXPECT_EQ(0, network_delegate.destroyed_requests());
5075 }
5076 EXPECT_EQ(1, network_delegate.destroyed_requests());
5077}
5078
5079// Tests that we can handle when a network request was canceled while we were
5080// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:005081// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
5082// callback.
[email protected]9045b8822012-01-13 20:35:355083TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:555084 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355085
5086 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305087 BlockingNetworkDelegate network_delegate(
5088 BlockingNetworkDelegate::USER_CALLBACK);
5089 network_delegate.set_block_on(
5090 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:355091
[email protected]ef2bf422012-05-11 03:27:095092 TestURLRequestContext context(true);
5093 context.set_network_delegate(&network_delegate);
5094 context.Init();
[email protected]9045b8822012-01-13 20:35:355095
5096 {
rhalavatib7bd7c792017-04-27 05:25:165097 std::unique_ptr<URLRequest> r(
5098 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5099 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355100
[email protected]f7022f32014-08-21 16:32:195101 r->Start();
Wez2a31b222018-06-07 22:07:155102 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305103 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
5104 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355105 EXPECT_EQ(0, network_delegate.completed_requests());
5106 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195107 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355108 // Ensure that network delegate is notified.
5109 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505110 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355111 EXPECT_EQ(1, network_delegate.created_requests());
5112 EXPECT_EQ(0, network_delegate.destroyed_requests());
5113 }
5114 EXPECT_EQ(1, network_delegate.destroyed_requests());
5115}
5116
5117// Tests that we can handle when a network request was canceled while we were
5118// waiting for the network delegate.
5119// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
5120TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:555121 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355122
5123 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305124 BlockingNetworkDelegate network_delegate(
5125 BlockingNetworkDelegate::USER_CALLBACK);
5126 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:355127
[email protected]ef2bf422012-05-11 03:27:095128 TestURLRequestContext context(true);
5129 context.set_network_delegate(&network_delegate);
5130 context.Init();
[email protected]9045b8822012-01-13 20:35:355131
5132 {
rhalavatib7bd7c792017-04-27 05:25:165133 std::unique_ptr<URLRequest> r(
5134 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5135 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355136
[email protected]f7022f32014-08-21 16:32:195137 r->Start();
Wez2a31b222018-06-07 22:07:155138 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305139 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
5140 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355141 EXPECT_EQ(0, network_delegate.completed_requests());
5142 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195143 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355144 // Ensure that network delegate is notified.
5145 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505146 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355147 EXPECT_EQ(1, network_delegate.created_requests());
5148 EXPECT_EQ(0, network_delegate.destroyed_requests());
5149 }
5150 EXPECT_EQ(1, network_delegate.destroyed_requests());
5151}
5152
5153// Tests that we can handle when a network request was canceled while we were
5154// waiting for the network delegate.
5155// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:025156TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:555157 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355158
5159 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305160 BlockingNetworkDelegate network_delegate(
5161 BlockingNetworkDelegate::USER_CALLBACK);
5162 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:355163
[email protected]ef2bf422012-05-11 03:27:095164 TestURLRequestContext context(true);
5165 context.set_network_delegate(&network_delegate);
5166 context.Init();
[email protected]9045b8822012-01-13 20:35:355167
5168 {
danakj8522a25b2016-04-16 00:17:365169 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165170 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
5171 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355172
[email protected]f7022f32014-08-21 16:32:195173 r->Start();
Wez2a31b222018-06-07 22:07:155174 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305175 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
5176 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355177 EXPECT_EQ(0, network_delegate.completed_requests());
5178 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195179 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355180 // Ensure that network delegate is notified.
5181 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505182 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355183 EXPECT_EQ(1, network_delegate.created_requests());
5184 EXPECT_EQ(0, network_delegate.destroyed_requests());
5185 }
5186 EXPECT_EQ(1, network_delegate.destroyed_requests());
5187}
5188
tommycli59a63432015-11-06 00:10:555189namespace {
5190
danakj8522a25b2016-04-16 00:17:365191std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:555192 const test_server::HttpRequest& request) {
5193 if (request.headers.find("Host") == request.headers.end() ||
5194 request.headers.at("Host") != "www.server-auth.com" ||
5195 request.method != test_server::METHOD_CONNECT) {
5196 return nullptr;
5197 }
5198
danakj8522a25b2016-04-16 00:17:365199 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:555200 new test_server::BasicHttpResponse);
5201 http_response->set_code(HTTP_UNAUTHORIZED);
5202 http_response->AddCustomHeader("WWW-Authenticate",
5203 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:485204 return std::move(http_response);
tommycli59a63432015-11-06 00:10:555205}
5206
5207} // namespace
5208
5209// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:115210// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:555211// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:355212TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:555213 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:125214 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:555215 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115216
[email protected]ceefd7fd2012-11-29 00:36:245217 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:045218 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:555219 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:505220
[email protected]dc651782009-02-14 01:45:085221 TestDelegate d;
5222 {
danakj8522a25b2016-04-16 00:17:365223 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165224 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
5225 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:085226
[email protected]f7022f32014-08-21 16:32:195227 r->Start();
5228 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:085229
Wez2a31b222018-06-07 22:07:155230 d.RunUntilComplete();
[email protected]dc651782009-02-14 01:45:085231
[email protected]d8fc4722014-06-13 13:17:155232 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:475233 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:505234 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:085235 }
5236}
5237
[email protected]b89290212009-08-14 22:37:355238TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:555239 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115240
initial.commit586acc5fe2008-07-26 22:42:525241 TestDelegate d;
5242 {
Ryan Sleevib8449e02018-07-15 04:31:075243 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165244 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5245 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525246
[email protected]f7022f32014-08-21 16:32:195247 r->Start();
5248 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525249
Wez2a31b222018-06-07 22:07:155250 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525251
5252 EXPECT_EQ(1, d.response_started_count());
5253 EXPECT_FALSE(d.received_data_before_response());
5254 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555255 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375256 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555257 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375258 r->GetResponseRemoteEndpoint().port());
[email protected]c31a54592009-09-04 02:36:165259
[email protected]9e743cd2010-03-16 07:03:535260 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:525261 }
initial.commit586acc5fe2008-07-26 22:42:525262}
5263
[email protected]263163f2012-06-14 22:40:345264// This test has the server send a large number of cookies to the client.
5265// To ensure that no number of cookies causes a crash, a galloping binary
5266// search is used to estimate that maximum number of cookies that are accepted
5267// by the browser. Beyond the maximum number, the request will fail with
5268// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:315269#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:305270// http://crbug.com/177916
5271#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
5272#else
5273#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
5274#endif // defined(OS_WIN)
5275TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:555276 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:345277
5278 int lower_bound = 0;
5279 int upper_bound = 1;
5280
5281 // Double the number of cookies until the response header limits are
5282 // exceeded.
5283 while (DoManyCookiesRequest(upper_bound)) {
5284 lower_bound = upper_bound;
5285 upper_bound *= 2;
5286 ASSERT_LT(upper_bound, 1000000);
5287 }
5288
pkasting6b68a162014-12-01 22:10:295289 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:345290 if (tolerance < 2)
5291 tolerance = 2;
5292
5293 // Perform a binary search to find the highest possible number of cookies,
5294 // within the desired tolerance.
5295 while (upper_bound - lower_bound >= tolerance) {
5296 int num_cookies = (lower_bound + upper_bound) / 2;
5297
5298 if (DoManyCookiesRequest(num_cookies))
5299 lower_bound = num_cookies;
5300 else
5301 upper_bound = num_cookies;
5302 }
5303 // Success: the test did not crash.
5304}
5305
[email protected]b89290212009-08-14 22:37:355306TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:555307 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115308
initial.commit586acc5fe2008-07-26 22:42:525309 TestDelegate d;
5310 {
Ryan Sleevib8449e02018-07-15 04:31:075311 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165312 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5313 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525314
[email protected]f7022f32014-08-21 16:32:195315 r->Start();
5316 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525317
Wez2a31b222018-06-07 22:07:155318 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525319
5320 EXPECT_EQ(1, d.response_started_count());
5321 EXPECT_FALSE(d.received_data_before_response());
5322 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555323 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375324 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555325 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375326 r->GetResponseRemoteEndpoint().port());
initial.commit586acc5fe2008-07-26 22:42:525327 }
[email protected]5d7b373e2009-09-02 07:19:035328}
5329
[email protected]79e1fd62013-06-20 06:50:045330TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555331 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045332
5333 TestDelegate d;
5334 {
tommycli59a63432015-11-06 00:10:555335 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075336 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165337 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045338
5339 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195340 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045341
[email protected]f7022f32014-08-21 16:32:195342 r->Start();
5343 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045344
Wez2a31b222018-06-07 22:07:155345 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:045346
5347 EXPECT_EQ(1, d.response_started_count());
5348 EXPECT_FALSE(d.received_data_before_response());
5349 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555350 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375351 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555352 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375353 r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:045354
5355 EXPECT_TRUE(d.have_full_request_headers());
5356 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5357 }
5358}
5359
[email protected]58e32bb2013-01-21 18:23:255360TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555361 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255362
5363 TestDelegate d;
5364 {
Ryan Sleevib8449e02018-07-15 04:31:075365 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165366 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5367 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255368
[email protected]f7022f32014-08-21 16:32:195369 r->Start();
5370 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255371
Wez2a31b222018-06-07 22:07:155372 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255373
5374 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195375 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255376 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5377
5378 EXPECT_EQ(1, d.response_started_count());
5379 EXPECT_FALSE(d.received_data_before_response());
5380 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555381 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375382 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555383 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375384 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:255385 }
5386}
5387
tommycli59a63432015-11-06 00:10:555388// TODO(svaldez): Update tests to use EmbeddedTestServer.
5389#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395390TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555391 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555392 base::FilePath(kTestFilePath));
5393
5394 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395395
5396 // Parameter that specifies the Content-Length field in the response:
5397 // C - Compressed length.
5398 // U - Uncompressed length.
5399 // L - Large length (larger than both C & U).
5400 // M - Medium length (between C & U).
5401 // S - Small length (smaller than both C & U).
5402 const char test_parameters[] = "CULMS";
Avi Drissman4365a4782018-12-28 19:26:245403 const int num_tests = base::size(test_parameters) - 1; // Skip NULL.
[email protected]aad63572011-05-24 20:14:395404 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445405 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395406 // S has too little data, but we seem to accept it.
5407 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375408 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395409
xunjielifb4da222016-07-14 18:38:595410 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:195411 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
xunjielifb4da222016-07-14 18:38:595412 file_path = file_path.Append(kTestFilePath);
5413 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5414 std::string expected_content;
5415 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5416
5417 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395418 TestDelegate d;
5419 {
tommycli59a63432015-11-06 00:10:555420 std::string test_file = base::StringPrintf(
5421 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395422
[email protected]ceefd7fd2012-11-29 00:36:245423 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095424 TestURLRequestContext context(true);
5425 context.set_network_delegate(&network_delegate);
5426 context.Init();
[email protected]87a09a92011-07-14 15:50:505427
rhalavatib7bd7c792017-04-27 05:25:165428 std::unique_ptr<URLRequest> r(
5429 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5430 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195431 r->Start();
5432 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395433
Wez2a31b222018-06-07 22:07:155434 d.RunUntilComplete();
[email protected]aad63572011-05-24 20:14:395435
5436 EXPECT_EQ(1, d.response_started_count());
5437 EXPECT_FALSE(d.received_data_before_response());
5438 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505439 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395440 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505441 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5442 << "\"";
xunjielifb4da222016-07-14 18:38:595443 if (test_parameters[i] == 'S') {
5444 // When content length is smaller than both compressed length and
5445 // uncompressed length, HttpStreamParser might not read the full
5446 // response body.
5447 continue;
5448 }
5449 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395450 } else {
maksim.sisovb53724b52016-09-16 05:30:505451 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395452 << " Parameter = \"" << test_file << "\"";
5453 }
5454 }
5455 }
5456}
tommycli59a63432015-11-06 00:10:555457#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395458
[email protected]58e32bb2013-01-21 18:23:255459TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555460 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255461
tommycli59a63432015-11-06 00:10:555462 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455463 GURL original_url =
tommycli59a63432015-11-06 00:10:555464 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255465 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075466 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165467 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195468 req->Start();
Wez2a31b222018-06-07 22:07:155469 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255470
5471 EXPECT_EQ(1, d.response_started_count());
5472 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195473 EXPECT_EQ(destination_url, req->url());
5474 EXPECT_EQ(original_url, req->original_url());
5475 ASSERT_EQ(2U, req->url_chain().size());
5476 EXPECT_EQ(original_url, req->url_chain()[0]);
5477 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255478
5479 LoadTimingInfo load_timing_info_before_redirect;
5480 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5481 &load_timing_info_before_redirect));
5482 TestLoadTimingNotReused(load_timing_info_before_redirect,
5483 CONNECT_TIMING_HAS_DNS_TIMES);
5484
5485 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195486 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255487 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5488
5489 // Check that a new socket was used on redirect, since the server does not
5490 // supposed keep-alive sockets, and that the times before the redirect are
5491 // before the ones recorded for the second request.
5492 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5493 load_timing_info.socket_log_id);
5494 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5495 load_timing_info.connect_timing.connect_start);
5496}
5497
[email protected]8f1ac082011-04-19 21:14:135498TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555499 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135500
tommycli59a63432015-11-06 00:10:555501 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455502 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555503 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5504 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5505 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135506 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075507 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165508 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195509 req->Start();
Wez2a31b222018-06-07 22:07:155510 d.RunUntilComplete();
[email protected]8f1ac082011-04-19 21:14:135511
5512 EXPECT_EQ(1, d.response_started_count());
5513 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195514 EXPECT_EQ(destination_url, req->url());
5515 EXPECT_EQ(original_url, req->original_url());
5516 ASSERT_EQ(3U, req->url_chain().size());
5517 EXPECT_EQ(original_url, req->url_chain()[0]);
5518 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5519 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135520}
5521
[email protected]abe1c4a2013-10-25 19:28:515522// First and second pieces of information logged by delegates to URLRequests.
5523const char kFirstDelegateInfo[] = "Wonderful delegate";
5524const char kSecondDelegateInfo[] = "Exciting delegate";
5525
5526// Logs delegate information to a URLRequest. The first string is logged
5527// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5528// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5529// another asynchronous call is used to clear the delegate information
5530// before calling a callback. The object then deletes itself.
5531class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5532 public:
David Benjamind1f287bf2018-06-12 01:57:205533 using Callback = base::OnceCallback<void()>;
[email protected]abe1c4a2013-10-25 19:28:515534
5535 // Each time delegate information is added to the URLRequest, the resulting
5536 // load state is checked. The expected load state after each request is
5537 // passed in as an argument.
5538 static void Run(URLRequest* url_request,
5539 LoadState expected_first_load_state,
5540 LoadState expected_second_load_state,
5541 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205542 Callback callback) {
tzik38f920a2018-08-01 04:41:205543 // base::MakeRefCounted<AsyncDelegateLogger> is unavailable here, since the
5544 // constructor of AsyncDelegateLogger is private.
5545 auto logger = base::WrapRefCounted(new AsyncDelegateLogger(
David Benjamind1f287bf2018-06-12 01:57:205546 url_request, expected_first_load_state, expected_second_load_state,
tzik38f920a2018-08-01 04:41:205547 expected_third_load_state, std::move(callback)));
[email protected]abe1c4a2013-10-25 19:28:515548 logger->Start();
5549 }
5550
5551 // Checks that the log entries, starting with log_position, contain the
5552 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5553 // recorded. Returns the index of entry after the expected number of
5554 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465555 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515556 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515557 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5558 if (log_position + 3 >= entries.size()) {
5559 ADD_FAILURE() << "Not enough log entries";
5560 return entries.size();
5561 }
5562 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005563 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5564 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075565 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515566 &delegate_info));
5567 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5568
5569 ++log_position;
mikecirone8b85c432016-09-08 19:11:005570 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5571 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515572
5573 ++log_position;
mikecirone8b85c432016-09-08 19:11:005574 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5575 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075576 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515577 &delegate_info));
5578 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5579
5580 ++log_position;
mikecirone8b85c432016-09-08 19:11:005581 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5582 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515583
5584 return log_position + 1;
5585 }
5586
5587 private:
5588 friend class base::RefCounted<AsyncDelegateLogger>;
5589
5590 AsyncDelegateLogger(URLRequest* url_request,
5591 LoadState expected_first_load_state,
5592 LoadState expected_second_load_state,
5593 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205594 Callback callback)
[email protected]abe1c4a2013-10-25 19:28:515595 : url_request_(url_request),
5596 expected_first_load_state_(expected_first_load_state),
5597 expected_second_load_state_(expected_second_load_state),
5598 expected_third_load_state_(expected_third_load_state),
David Benjamind1f287bf2018-06-12 01:57:205599 callback_(std::move(callback)) {}
[email protected]abe1c4a2013-10-25 19:28:515600
Chris Watkins7a41d3552017-12-01 02:13:275601 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515602
5603 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535604 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515605 LoadStateWithParam load_state = url_request_->GetLoadState();
5606 EXPECT_EQ(expected_first_load_state_, load_state.state);
5607 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455608 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155609 FROM_HERE,
5610 base::BindOnce(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515611 }
5612
5613 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535614 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515615 LoadStateWithParam load_state = url_request_->GetLoadState();
5616 EXPECT_EQ(expected_second_load_state_, load_state.state);
5617 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5618 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5619 } else {
5620 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5621 }
skyostil4891b25b2015-06-11 11:43:455622 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155623 FROM_HERE, base::BindOnce(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515624 }
5625
5626 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535627 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515628 LoadStateWithParam load_state = url_request_->GetLoadState();
5629 EXPECT_EQ(expected_third_load_state_, load_state.state);
5630 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085631 EXPECT_EQ(base::string16(), load_state.param);
David Benjamind1f287bf2018-06-12 01:57:205632 std::move(callback_).Run();
[email protected]abe1c4a2013-10-25 19:28:515633 }
5634
5635 URLRequest* url_request_;
5636 const int expected_first_load_state_;
5637 const int expected_second_load_state_;
5638 const int expected_third_load_state_;
David Benjamind1f287bf2018-06-12 01:57:205639 Callback callback_;
[email protected]abe1c4a2013-10-25 19:28:515640
5641 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5642};
5643
5644// NetworkDelegate that logs delegate information before a request is started,
5645// before headers are sent, when headers are read, and when auth information
5646// is requested. Uses AsyncDelegateLogger.
5647class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5648 public:
Chris Watkins7a41d3552017-12-01 02:13:275649 AsyncLoggingNetworkDelegate() = default;
5650 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515651
5652 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205653 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205654 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:205655 GURL* new_url) override {
David Benjamind1f287bf2018-06-12 01:57:205656 // TestNetworkDelegate always completes synchronously.
5657 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
5658 request, base::NullCallback(), new_url));
5659 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515660 }
5661
ryansturm2343cb62016-06-15 01:09:005662 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205663 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:005664 HttpRequestHeaders* headers) override {
David Benjamind1f287bf2018-06-12 01:57:205665 // TestNetworkDelegate always completes synchronously.
5666 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
5667 request, base::NullCallback(), headers));
5668 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515669 }
5670
dchengb03027d2014-10-21 12:00:205671 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515672 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205673 CompletionOnceCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515674 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165675 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135676 GURL* allowed_unsafe_redirect_url) override {
David Benjamind1f287bf2018-06-12 01:57:205677 // TestNetworkDelegate always completes synchronously.
5678 CHECK_NE(ERR_IO_PENDING,
5679 TestNetworkDelegate::OnHeadersReceived(
5680 request, base::NullCallback(), original_response_headers,
5681 override_response_headers, allowed_unsafe_redirect_url));
5682 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515683 }
5684
dchengb03027d2014-10-21 12:00:205685 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515686 URLRequest* request,
5687 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:205688 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:135689 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515690 AsyncDelegateLogger::Run(
David Benjamind1f287bf2018-06-12 01:57:205691 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5692 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5693 base::BindOnce(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5694 std::move(callback), credentials));
[email protected]abe1c4a2013-10-25 19:28:515695 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5696 }
5697
5698 private:
David Benjamind1f287bf2018-06-12 01:57:205699 static int RunCallbackAsynchronously(URLRequest* request,
5700 CompletionOnceCallback callback) {
5701 AsyncDelegateLogger::Run(request, LOAD_STATE_WAITING_FOR_DELEGATE,
5702 LOAD_STATE_WAITING_FOR_DELEGATE,
5703 LOAD_STATE_WAITING_FOR_DELEGATE,
5704 base::BindOnce(std::move(callback), OK));
[email protected]abe1c4a2013-10-25 19:28:515705 return ERR_IO_PENDING;
5706 }
5707
David Benjamind1f287bf2018-06-12 01:57:205708 static void SetAuthAndResume(AuthCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515709 AuthCredentials* credentials) {
5710 *credentials = AuthCredentials(kUser, kSecret);
David Benjamind1f287bf2018-06-12 01:57:205711 std::move(callback).Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
[email protected]abe1c4a2013-10-25 19:28:515712 }
5713
5714 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5715};
5716
5717// URLRequest::Delegate that logs delegate information when the headers
5718// are received, when each read completes, and during redirects. Uses
5719// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5720//
5721// Inherits from TestDelegate to reuse the TestDelegate code to handle
5722// advancing to the next step in most cases, as well as cancellation.
5723class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5724 public:
5725 enum CancelStage {
5726 NO_CANCEL = 0,
5727 CANCEL_ON_RECEIVED_REDIRECT,
5728 CANCEL_ON_RESPONSE_STARTED,
5729 CANCEL_ON_READ_COMPLETED
5730 };
5731
5732 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5733 : cancel_stage_(cancel_stage) {
5734 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5735 set_cancel_in_received_redirect(true);
5736 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5737 set_cancel_in_response_started(true);
5738 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5739 set_cancel_in_received_data(true);
5740 }
Chris Watkins7a41d3552017-12-01 02:13:275741 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515742
5743 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205744 void OnReceivedRedirect(URLRequest* request,
5745 const RedirectInfo& redirect_info,
5746 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515747 *defer_redirect = true;
5748 AsyncDelegateLogger::Run(
5749 request,
5750 LOAD_STATE_WAITING_FOR_DELEGATE,
5751 LOAD_STATE_WAITING_FOR_DELEGATE,
5752 LOAD_STATE_WAITING_FOR_DELEGATE,
5753 base::Bind(
5754 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595755 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515756 }
5757
maksim.sisov0f4aa142016-09-05 05:55:285758 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515759 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285760 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5761 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5762 base::Bind(
5763 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5764 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515765 }
5766
dchengb03027d2014-10-21 12:00:205767 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515768 AsyncDelegateLogger::Run(
5769 request,
5770 LOAD_STATE_IDLE,
5771 LOAD_STATE_IDLE,
5772 LOAD_STATE_IDLE,
5773 base::Bind(
5774 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5775 base::Unretained(this), request, bytes_read));
5776 }
5777
5778 private:
5779 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595780 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515781 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595782 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515783 // FollowDeferredRedirect should not be called after cancellation.
5784 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5785 return;
Arthur Sonzognib8465ff72019-01-04 18:44:355786 if (!defer_redirect) {
5787 request->FollowDeferredRedirect(base::nullopt /* removed_headers */,
5788 base::nullopt /* modified_headers */);
5789 }
[email protected]abe1c4a2013-10-25 19:28:515790 }
5791
maksim.sisov0f4aa142016-09-05 05:55:285792 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515793 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285794 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515795 }
5796
5797 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5798 // The parent class continues the request.
5799 TestDelegate::OnReadCompleted(request, bytes_read);
5800 }
5801
5802 const CancelStage cancel_stage_;
5803
5804 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5805};
5806
5807// Tests handling of delegate info before a request starts.
5808TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555809 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515810
5811 TestDelegate request_delegate;
5812 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:355813 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:515814 context.set_net_log(&net_log_);
5815 context.Init();
5816
5817 {
rhalavatib7bd7c792017-04-27 05:25:165818 std::unique_ptr<URLRequest> r(context.CreateRequest(
5819 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5820 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195821 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515822 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085823 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515824
5825 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195826 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515827 LOAD_STATE_WAITING_FOR_DELEGATE,
5828 LOAD_STATE_WAITING_FOR_DELEGATE,
5829 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195830 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515831
Wez2a31b222018-06-07 22:07:155832 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515833
[email protected]f7022f32014-08-21 16:32:195834 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505835 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515836 }
5837
mmenke43758e62015-05-04 21:09:465838 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515839 net_log_.GetEntries(&entries);
5840 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005841 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515842
5843 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5844
5845 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005846 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5847 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515848}
5849
5850// Tests handling of delegate info from a network delegate.
5851TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555852 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515853
5854 TestDelegate request_delegate;
5855 AsyncLoggingNetworkDelegate network_delegate;
5856 TestURLRequestContext context(true);
5857 context.set_network_delegate(&network_delegate);
5858 context.set_net_log(&net_log_);
5859 context.Init();
5860
5861 {
rhalavatib7bd7c792017-04-27 05:25:165862 std::unique_ptr<URLRequest> r(context.CreateRequest(
5863 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
5864 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195865 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515866 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085867 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515868
[email protected]f7022f32014-08-21 16:32:195869 r->Start();
Wez2a31b222018-06-07 22:07:155870 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515871
[email protected]f7022f32014-08-21 16:32:195872 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505873 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515874 EXPECT_EQ(1, network_delegate.created_requests());
5875 EXPECT_EQ(0, network_delegate.destroyed_requests());
5876 }
5877 EXPECT_EQ(1, network_delegate.destroyed_requests());
5878
5879 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465880 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515881 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155882 static const NetLogEventType kExpectedEvents[] = {
5883 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5884 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5885 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5886 };
5887 for (NetLogEventType event : kExpectedEvents) {
5888 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515889 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155890 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515891
5892 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5893 log_position + 1);
5894
5895 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155896 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005897 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515898 }
5899
mikecirone8b85c432016-09-08 19:11:005900 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5901 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515902}
5903
5904// Tests handling of delegate info from a network delegate in the case of an
5905// HTTP redirect.
5906TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555907 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515908
5909 TestDelegate request_delegate;
5910 AsyncLoggingNetworkDelegate network_delegate;
5911 TestURLRequestContext context(true);
5912 context.set_network_delegate(&network_delegate);
5913 context.set_net_log(&net_log_);
5914 context.Init();
5915
5916 {
danakj8522a25b2016-04-16 00:17:365917 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555918 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165919 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195920 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515921 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085922 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515923
[email protected]f7022f32014-08-21 16:32:195924 r->Start();
Wez2a31b222018-06-07 22:07:155925 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515926
[email protected]f7022f32014-08-21 16:32:195927 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505928 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515929 EXPECT_EQ(2, network_delegate.created_requests());
5930 EXPECT_EQ(0, network_delegate.destroyed_requests());
5931 }
5932 EXPECT_EQ(1, network_delegate.destroyed_requests());
5933
5934 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465935 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515936 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155937 static const NetLogEventType kExpectedEvents[] = {
5938 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5939 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5940 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5941 };
5942 for (NetLogEventType event : kExpectedEvents) {
5943 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515944 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155945 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515946
David Benjamin9776ca22018-06-13 00:00:155947 log_position =
5948 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:515949
5950 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155951 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005952 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515953 }
5954
5955 // The URLRequest::Delegate then gets informed about the redirect.
5956 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155957 entries, log_position + 1,
5958 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
mikecirone8b85c432016-09-08 19:11:005959 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515960
5961 // The NetworkDelegate logged information in the same three events as before.
David Benjamin9776ca22018-06-13 00:00:155962 for (NetLogEventType event : kExpectedEvents) {
5963 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515964 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155965 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515966
5967 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5968 log_position + 1);
5969
5970 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155971 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005972 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515973 }
5974
mikecirone8b85c432016-09-08 19:11:005975 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5976 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515977}
5978
5979// Tests handling of delegate info from a network delegate in the case of HTTP
5980// AUTH.
5981TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555982 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515983
5984 TestDelegate request_delegate;
5985 AsyncLoggingNetworkDelegate network_delegate;
5986 TestURLRequestContext context(true);
5987 context.set_network_delegate(&network_delegate);
5988 context.set_net_log(&net_log_);
5989 context.Init();
5990
5991 {
rhalavatib7bd7c792017-04-27 05:25:165992 std::unique_ptr<URLRequest> r(context.CreateRequest(
5993 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
5994 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195995 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515996 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085997 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515998
[email protected]f7022f32014-08-21 16:32:195999 r->Start();
Wez2a31b222018-06-07 22:07:156000 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516001
[email protected]f7022f32014-08-21 16:32:196002 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506003 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516004 EXPECT_EQ(1, network_delegate.created_requests());
6005 EXPECT_EQ(0, network_delegate.destroyed_requests());
6006 }
6007 EXPECT_EQ(1, network_delegate.destroyed_requests());
6008
6009 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466010 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516011 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:156012 static const NetLogEventType kExpectedEvents[] = {
6013 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6014 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6015 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6016 NetLogEventType::NETWORK_DELEGATE_AUTH_REQUIRED,
6017 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6018 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6019 };
6020 for (NetLogEventType event : kExpectedEvents) {
6021 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516022 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156023 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516024
David Benjamin9776ca22018-06-13 00:00:156025 log_position =
6026 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516027
6028 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156029 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006030 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516031 }
6032
mikecirone8b85c432016-09-08 19:11:006033 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6034 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516035}
6036
tommycli59a63432015-11-06 00:10:556037// TODO(svaldez): Update tests to use EmbeddedTestServer.
6038#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516039// Tests handling of delegate info from a URLRequest::Delegate.
6040TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:556041 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:556042 base::FilePath(kTestFilePath));
6043
6044 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:516045
6046 AsyncLoggingUrlRequestDelegate request_delegate(
6047 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6048 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356049 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516050 context.set_net_log(&net_log_);
6051 context.Init();
6052
6053 {
6054 // A chunked response with delays between chunks is used to make sure that
6055 // attempts by the URLRequest delegate to log information while reading the
6056 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:486057 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:516058 // that it occurs.
danakj8522a25b2016-04-16 00:17:366059 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556060 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166061 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196062 LoadStateWithParam load_state = r->GetLoadState();
6063 r->Start();
Wez2a31b222018-06-07 22:07:156064 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516065
[email protected]f7022f32014-08-21 16:32:196066 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506067 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516068 }
6069
mmenke43758e62015-05-04 21:09:466070 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516071 net_log_.GetEntries(&entries);
6072
[email protected]1826a402014-01-08 15:40:486073 size_t log_position = 0;
6074
[email protected]abe1c4a2013-10-25 19:28:516075 // The delegate info should only have been logged on header complete. Other
6076 // times it should silently be ignored.
David Benjamin9776ca22018-06-13 00:00:156077 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
6078 entries, 0, NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST));
mikecirone8b85c432016-09-08 19:11:006079 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156080 entries, log_position + 1,
6081 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
mikecirone8b85c432016-09-08 19:11:006082 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516083
David Benjamin9776ca22018-06-13 00:00:156084 log_position =
6085 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516086
6087 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156088 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6089 entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006090 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516091
mikecirone8b85c432016-09-08 19:11:006092 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6093 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516094 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
David Benjamin9776ca22018-06-13 00:00:156095 entries, log_position + 1,
6096 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED));
[email protected]abe1c4a2013-10-25 19:28:516097}
tommycli59a63432015-11-06 00:10:556098#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516099
6100// Tests handling of delegate info from a URLRequest::Delegate in the case of
6101// an HTTP redirect.
6102TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:556103 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516104
6105 AsyncLoggingUrlRequestDelegate request_delegate(
6106 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6107 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356108 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516109 context.set_net_log(&net_log_);
6110 context.Init();
6111
6112 {
danakj8522a25b2016-04-16 00:17:366113 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556114 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166115 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196116 LoadStateWithParam load_state = r->GetLoadState();
6117 r->Start();
Wez2a31b222018-06-07 22:07:156118 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516119
[email protected]f7022f32014-08-21 16:32:196120 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506121 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516122 }
6123
mmenke43758e62015-05-04 21:09:466124 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516125 net_log_.GetEntries(&entries);
6126
6127 // Delegate info should only have been logged in OnReceivedRedirect and
6128 // OnResponseStarted.
6129 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156130 static const NetLogEventType kExpectedEvents[] = {
6131 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6132 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6133 };
6134 for (NetLogEventType event : kExpectedEvents) {
6135 SCOPED_TRACE(NetLog::EventTypeToString(event));
6136 log_position = ExpectLogContainsSomewhereAfter(entries, log_position, event,
6137 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516138
David Benjamin9776ca22018-06-13 00:00:156139 log_position =
6140 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516141
6142 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156143 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006144 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516145 }
6146
mikecirone8b85c432016-09-08 19:11:006147 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6148 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516149}
6150
6151// Tests handling of delegate info from a URLRequest::Delegate in the case of
6152// an HTTP redirect, with cancellation at various points.
6153TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:556154 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516155
6156 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
6157 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
6158 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
6159 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
6160 };
6161
David Benjamin9776ca22018-06-13 00:00:156162 for (auto cancel_stage : kCancelStages) {
6163 AsyncLoggingUrlRequestDelegate request_delegate(cancel_stage);
vishal.b62985ca92015-04-17 08:45:516164 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046165 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356166 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516167 context.set_net_log(&net_log);
6168 context.Init();
6169
6170 {
danakj8522a25b2016-04-16 00:17:366171 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556172 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166173 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196174 LoadStateWithParam load_state = r->GetLoadState();
6175 r->Start();
Wez2a31b222018-06-07 22:07:156176 request_delegate.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506177 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
Wez2a31b222018-06-07 22:07:156178
6179 // Spin the message loop to run AsyncDelegateLogger task(s) posted after
6180 // the |request_delegate| completion task.
6181 base::RunLoop().RunUntilIdle();
[email protected]abe1c4a2013-10-25 19:28:516182 }
6183
mmenke43758e62015-05-04 21:09:466184 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516185 net_log.GetEntries(&entries);
6186
6187 // Delegate info is always logged in both OnReceivedRedirect and
6188 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6189 // OnResponseStarted delegate call is after cancellation, but logging is
6190 // still currently supported in that call.
6191 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156192 static const NetLogEventType kExpectedEvents[] = {
6193 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6194 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6195 };
6196 for (NetLogEventType event : kExpectedEvents) {
6197 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516198 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156199 entries, log_position, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516200
David Benjamin9776ca22018-06-13 00:00:156201 log_position =
6202 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516203
6204 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156205 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006206 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516207 }
6208
mikecirone8b85c432016-09-08 19:11:006209 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6210 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516211 }
6212}
6213
[email protected]847c0fa92012-11-06 16:37:426214namespace {
6215
6216const char kExtraHeader[] = "Allow-Snafu";
6217const char kExtraValue[] = "fubar";
6218
6219class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206220 void OnReceivedRedirect(URLRequest* request,
6221 const RedirectInfo& redirect_info,
6222 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596223 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426224 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6225 }
6226};
6227
6228} // namespace
6229
6230TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556231 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426232
tommycli59a63432015-11-06 00:10:556233 GURL destination_url =
6234 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6235 GURL original_url =
6236 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426237 RedirectWithAdditionalHeadersDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076238 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166239 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196240 req->Start();
Wez2a31b222018-06-07 22:07:156241 d.RunUntilComplete();
[email protected]847c0fa92012-11-06 16:37:426242
6243 std::string value;
[email protected]f7022f32014-08-21 16:32:196244 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426245 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6246 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196247 EXPECT_FALSE(req->is_pending());
6248 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426249 EXPECT_EQ(kExtraValue, d.data_received());
6250}
6251
[email protected]251a1b92012-11-13 11:01:096252namespace {
6253
6254const char kExtraHeaderToRemove[] = "To-Be-Removed";
6255
6256class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206257 void OnReceivedRedirect(URLRequest* request,
6258 const RedirectInfo& redirect_info,
6259 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596260 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096261 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6262 }
6263};
6264
6265} // namespace
6266
6267TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556268 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096269
tommycli59a63432015-11-06 00:10:556270 GURL destination_url = http_test_server()->GetURL(
6271 "/echoheader?" + std::string(kExtraHeaderToRemove));
6272 GURL original_url =
6273 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096274 RedirectWithHeaderRemovalDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076275 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166276 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196277 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6278 req->Start();
Wez2a31b222018-06-07 22:07:156279 d.RunUntilComplete();
[email protected]251a1b92012-11-13 11:01:096280
6281 std::string value;
[email protected]f7022f32014-08-21 16:32:196282 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096283 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196284 EXPECT_FALSE(req->is_pending());
6285 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096286 EXPECT_EQ("None", d.data_received());
6287}
6288
mmenke94f1bd92016-12-07 21:13:056289TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446290 TestDelegate d;
6291 {
Ryan Sleevib8449e02018-07-15 04:31:076292 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166293 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6294 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446295
[email protected]f7022f32014-08-21 16:32:196296 r->Start();
6297 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446298
[email protected]f7022f32014-08-21 16:32:196299 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446300
Wez2a31b222018-06-07 22:07:156301 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446302
6303 // We expect to receive OnResponseStarted even though the request has been
6304 // cancelled.
6305 EXPECT_EQ(1, d.response_started_count());
6306 EXPECT_EQ(0, d.bytes_received());
6307 EXPECT_FALSE(d.received_data_before_response());
6308 }
6309}
6310
mmenke94f1bd92016-12-07 21:13:056311TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556312 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446313
6314 TestDelegate d;
6315 {
Ryan Sleevib8449e02018-07-15 04:31:076316 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166317 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6318 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446319
6320 d.set_cancel_in_response_started(true);
6321
[email protected]f7022f32014-08-21 16:32:196322 r->Start();
6323 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446324
Wez2a31b222018-06-07 22:07:156325 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446326
6327 EXPECT_EQ(1, d.response_started_count());
6328 EXPECT_EQ(0, d.bytes_received());
6329 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506330 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446331 }
6332}
6333
mmenke94f1bd92016-12-07 21:13:056334TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556335 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446336
6337 TestDelegate d;
6338 {
Ryan Sleevib8449e02018-07-15 04:31:076339 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166340 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6341 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056342
6343 d.set_cancel_in_received_data(true);
6344
6345 r->Start();
6346 EXPECT_TRUE(r->is_pending());
6347
Wez2a31b222018-06-07 22:07:156348 d.RunUntilComplete();
mmenke94f1bd92016-12-07 21:13:056349
6350 EXPECT_EQ(1, d.response_started_count());
6351 EXPECT_NE(0, d.received_bytes_count());
6352 EXPECT_FALSE(d.received_data_before_response());
6353 EXPECT_EQ(ERR_ABORTED, d.request_status());
6354 }
6355}
6356
6357TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6358 ASSERT_TRUE(http_test_server()->Start());
6359
6360 TestDelegate d;
6361 {
6362 // This returns an empty response (With headers).
Ryan Sleevib8449e02018-07-15 04:31:076363 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166364 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6365 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446366
6367 d.set_cancel_in_received_data(true);
6368
[email protected]f7022f32014-08-21 16:32:196369 r->Start();
6370 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446371
Wez2a31b222018-06-07 22:07:156372 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446373
6374 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056375 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446376 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506377 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446378 }
6379}
6380
mmenke94f1bd92016-12-07 21:13:056381TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556382 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446383
6384 TestDelegate d;
6385 {
Ryan Sleevib8449e02018-07-15 04:31:076386 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166387 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6388 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446389
[email protected]f7022f32014-08-21 16:32:196390 r->Start();
6391 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446392
6393 // The request will be implicitly canceled when it is destroyed. The
6394 // test delegate must not post a quit message when this happens because
6395 // this test doesn't actually have a message loop. The quit message would
6396 // get put on this thread's message queue and the next test would exit
6397 // early, causing problems.
Wez0e717112018-06-18 23:09:226398 d.set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:446399 }
6400 // expect things to just cleanup properly.
6401
kimwjdalsl2bb4ff02015-12-16 22:06:026402 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446403 // message loop
6404 EXPECT_FALSE(d.received_data_before_response());
6405 EXPECT_EQ(0, d.bytes_received());
6406}
6407
mmenke94f1bd92016-12-07 21:13:056408TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556409 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446410
6411 // populate cache
6412 {
6413 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076414 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166415 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6416 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196417 r->Start();
Wez2a31b222018-06-07 22:07:156418 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506419 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446420 }
6421
6422 // cancel read from cache (see bug 990242)
6423 {
6424 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076425 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166426 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6427 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196428 r->Start();
6429 r->Cancel();
Wez2a31b222018-06-07 22:07:156430 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446431
maksim.sisovb53724b52016-09-16 05:30:506432 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446433 EXPECT_EQ(1, d.response_started_count());
6434 EXPECT_EQ(0, d.bytes_received());
6435 EXPECT_FALSE(d.received_data_before_response());
6436 }
6437}
6438
6439TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556440 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446441 HTTPUploadDataOperationTest("POST");
6442}
6443
6444TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556445 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446446 HTTPUploadDataOperationTest("PUT");
6447}
6448
6449TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556450 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446451
6452 TestDelegate d;
6453 {
Ryan Sleevib8449e02018-07-15 04:31:076454 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166455 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6456 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196457 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446458
[email protected]f7022f32014-08-21 16:32:196459 r->Start();
6460 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446461
Wez2a31b222018-06-07 22:07:156462 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446463
maksim.sisovb53724b52016-09-16 05:30:506464 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6465 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446466
6467 EXPECT_FALSE(d.received_data_before_response());
6468 EXPECT_TRUE(d.data_received().empty());
6469 }
6470}
6471
6472TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556473 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446474
6475 TestDelegate d;
6476 {
Ryan Sleevib8449e02018-07-15 04:31:076477 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166478 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6479 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196480 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446481
[email protected]6cdfd7f2013-02-08 20:40:156482 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196483 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026484 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446485
danakj8522a25b2016-04-16 00:17:366486 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446487
[email protected]6cdfd7f2013-02-08 20:40:156488 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196489 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476490 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446491 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196492 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146493 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076494 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046495 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6496 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446497
[email protected]f7022f32014-08-21 16:32:196498 r->Start();
6499 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446500
Wez2a31b222018-06-07 22:07:156501 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446502
avibf0746c2015-12-09 19:53:146503 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296504 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6505 ASSERT_LE(size64, std::numeric_limits<int>::max());
6506 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366507 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446508
[email protected]7600d0b2013-12-08 21:43:306509 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446510
maksim.sisovb53724b52016-09-16 05:30:506511 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6512 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446513
6514 EXPECT_FALSE(d.received_data_before_response());
6515
[email protected]329b68b2012-11-14 17:54:276516 EXPECT_EQ(size, d.bytes_received());
6517 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446518 }
6519}
6520
[email protected]999dd8c2013-11-12 06:45:546521TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556522 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546523
6524 TestDelegate d;
6525 {
Ryan Sleevib8449e02018-07-15 04:31:076526 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166527 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6528 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196529 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546530
danakj8522a25b2016-04-16 00:17:366531 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546532
Jeremy Roman0579ed62017-08-29 15:56:196533 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456534 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546535 base::FilePath(FILE_PATH_LITERAL(
6536 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076537 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046538 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6539 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546540
[email protected]f7022f32014-08-21 16:32:196541 r->Start();
6542 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546543
Wez2a31b222018-06-07 22:07:156544 d.RunUntilComplete();
[email protected]999dd8c2013-11-12 06:45:546545
[email protected]999dd8c2013-11-12 06:45:546546 EXPECT_TRUE(d.request_failed());
6547 EXPECT_FALSE(d.received_data_before_response());
6548 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506549 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546550 }
6551}
6552
mmenke56b0cbb912016-03-28 21:34:536553namespace {
6554
6555// Adds a standard set of data to an upload for chunked upload integration
6556// tests.
6557void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6558 writer->AppendData("a", 1, false);
6559 writer->AppendData("bcd", 3, false);
6560 writer->AppendData("this is a longer chunk than before.", 35, false);
6561 writer->AppendData("\r\n\r\n", 4, false);
6562 writer->AppendData("0", 1, false);
6563 writer->AppendData("2323", 4, true);
6564}
6565
6566// Checks that the upload data added in AddChunksToUpload() was echoed back from
6567// the server.
6568void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6569 // This should match the chunks sent by AddChunksToUpload().
6570 const std::string expected_data =
6571 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6572
maksim.sisovb53724b52016-09-16 05:30:506573 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6574 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536575
6576 EXPECT_FALSE(d->received_data_before_response());
6577
6578 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6579 EXPECT_EQ(expected_data, d->data_received());
6580}
6581
6582} // namespace
6583
[email protected]316c1e5e2012-09-12 15:17:446584TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556585 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446586
6587 TestDelegate d;
6588 {
Ryan Sleevib8449e02018-07-15 04:31:076589 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166590 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6591 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366592 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536593 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366594 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536595 upload_data_stream->CreateWriter();
6596 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196597 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536598 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196599 r->Start();
6600 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446601
Wez2a31b222018-06-07 22:07:156602 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446603
[email protected]f7022f32014-08-21 16:32:196604 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446605 }
6606}
6607
[email protected]329b68b2012-11-14 17:54:276608TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556609 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276610
6611 TestDelegate d;
6612 {
Ryan Sleevib8449e02018-07-15 04:31:076613 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166614 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6615 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366616 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536617 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366618 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536619 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046620 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196621 r->set_method("POST");
6622 r->Start();
6623 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536624 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156625 d.RunUntilComplete();
[email protected]329b68b2012-11-14 17:54:276626
[email protected]f7022f32014-08-21 16:32:196627 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276628 }
6629}
6630
Asanka Herathf05753e2018-08-16 17:38:206631TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556632 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446633
6634 TestDelegate d;
6635 {
Ryan Sleevib8449e02018-07-15 04:31:076636 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166637 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6638 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366639 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536640 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366641 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536642 upload_data_stream->CreateWriter();
6643 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196644 r->set_method("POST");
6645 r->Start();
6646 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446647
Asanka Herathf05753e2018-08-16 17:38:206648 // Pump messages until we start sending headers..
[email protected]255620da2013-08-19 13:14:296649 base::RunLoop().RunUntilIdle();
Asanka Herathf05753e2018-08-16 17:38:206650
6651 // And now wait for completion.
6652 base::RunLoop run_loop;
6653 d.set_on_complete(run_loop.QuitClosure());
mmenke56b0cbb912016-03-28 21:34:536654 AddDataToUpload(writer.get());
Asanka Herathf05753e2018-08-16 17:38:206655 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:446656
[email protected]f7022f32014-08-21 16:32:196657 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446658 }
6659}
6660
6661TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556662 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446663
6664 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076665 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166666 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6667 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196668 req->Start();
Wez2a31b222018-06-07 22:07:156669 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446670
[email protected]f7022f32014-08-21 16:32:196671 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446672
6673 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196674 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446675
6676 std::string header;
6677 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6678 EXPECT_EQ("private", header);
6679
6680 header.clear();
6681 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6682 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6683
6684 // The response has two "X-Multiple-Entries" headers.
6685 // This verfies our output has them concatenated together.
6686 header.clear();
6687 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6688 EXPECT_EQ("a, b", header);
6689}
6690
tommycli59a63432015-11-06 00:10:556691// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6692// security state. (see http://crbug.com/550977).
6693#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466694TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556695 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6696 https_test_server.SetSSLConfig(
6697 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6698 https_test_server.ServeFilesFromSourceDirectory(
6699 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466700 ASSERT_TRUE(https_test_server.Start());
6701
tommycli59a63432015-11-06 00:10:556702 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466703 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076704 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166705 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6706 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196707 request->Start();
Wez2a31b222018-06-07 22:07:156708 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466709
6710 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076711 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406712 TransportSecurityState::STSState sts_state;
6713 TransportSecurityState::PKPState pkp_state;
6714 EXPECT_TRUE(
6715 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6716 EXPECT_FALSE(
6717 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6718 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6719 sts_state.upgrade_mode);
6720 EXPECT_TRUE(sts_state.include_subdomains);
6721 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036722#if defined(OS_ANDROID)
6723 // Android's CertVerifyProc does not (yet) handle pins.
6724#else
martijnc0d6b622015-06-30 19:14:406725 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036726#endif
[email protected]37fd55fb2013-06-29 13:13:276727}
6728
estarka5da76702015-04-09 04:00:166729TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556730 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6731 https_test_server.ServeFilesFromSourceDirectory(
6732 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166733 ASSERT_TRUE(https_test_server.Start());
6734 // Make sure this test fails if the test server is changed to not
6735 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556736 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6737 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166738
6739 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076740 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166741 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6742 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166743 request->Start();
Wez2a31b222018-06-07 22:07:156744 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:166745 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076746 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406747 TransportSecurityState::STSState sts_state;
6748 EXPECT_FALSE(
6749 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166750}
6751
estark06e0dac2015-08-07 21:56:016752namespace {
Martijn Croonenb1383da2017-10-11 11:56:356753const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
Matt Mueller230996f12018-10-22 19:39:446754const char kPKPReportUri[] = "http://report-uri.preloaded.test/pkp";
6755const char kPKPHost[] = "with-report-uri-pkp.preloaded.test";
estark06e0dac2015-08-07 21:56:016756} // namespace
6757
Matt Mueller230996f12018-10-22 19:39:446758// Tests that reports get sent on PKP violations when a report-uri is set.
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516759TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
Matt Mueller230996f12018-10-22 19:39:446760 GURL report_uri(kPKPReportUri);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516761 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6762 https_test_server.SetSSLConfig(
6763 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6764 https_test_server.ServeFilesFromSourceDirectory(
6765 base::FilePath(kTestFilePath));
6766 ASSERT_TRUE(https_test_server.Start());
6767
Matt Mueller230996f12018-10-22 19:39:446768 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016769
6770 // Set up a pin for |test_server_hostname|.
6771 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446772 security_state.EnableStaticPinsForTesting();
6773 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016774
6775 MockCertificateReportSender mock_report_sender;
6776 security_state.SetReportSender(&mock_report_sender);
6777
6778 // Set up a MockCertVerifier to trigger a violation of the previously
6779 // set pin.
6780 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6781 ASSERT_TRUE(cert);
6782
6783 MockCertVerifier cert_verifier;
6784 CertVerifyResult verify_result;
6785 verify_result.verified_cert = cert;
6786 verify_result.is_issued_by_known_root = true;
6787 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446788 ASSERT_TRUE(
6789 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016790 verify_result.public_key_hashes.push_back(hash3);
6791 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6792
6793 TestNetworkDelegate network_delegate;
6794 TestURLRequestContext context(true);
6795 context.set_transport_security_state(&security_state);
6796 context.set_network_delegate(&network_delegate);
6797 context.set_cert_verifier(&cert_verifier);
6798 context.Init();
6799
6800 // Now send a request to trigger the violation.
6801 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366802 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446803 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166804 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016805 violating_request->Start();
Wez2a31b222018-06-07 22:07:156806 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016807
6808 // Check that a report was sent.
6809 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6810 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446811 EXPECT_EQ("application/json; charset=utf-8",
6812 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366813 std::unique_ptr<base::Value> value(
Lei Zhanga8b4c5fb2019-02-16 03:02:036814 base::JSONReader::ReadDeprecated(mock_report_sender.latest_report()));
estark06e0dac2015-08-07 21:56:016815 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086816 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016817 base::DictionaryValue* report_dict;
6818 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6819 std::string report_hostname;
6820 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6821 EXPECT_EQ(test_server_hostname, report_hostname);
6822}
6823
Matt Mueller230996f12018-10-22 19:39:446824// Tests that reports do not get sent on requests to static pkp hosts that
6825// don't have pin violations.
6826TEST_F(URLRequestTestHTTP, ProcessPKPWithNoViolation) {
tommycli59a63432015-11-06 00:10:556827 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6828 https_test_server.SetSSLConfig(
6829 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6830 https_test_server.ServeFilesFromSourceDirectory(
6831 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016832 ASSERT_TRUE(https_test_server.Start());
6833
Matt Mueller230996f12018-10-22 19:39:446834 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016835
6836 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446837 security_state.EnableStaticPinsForTesting();
6838 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016839 MockCertificateReportSender mock_report_sender;
6840 security_state.SetReportSender(&mock_report_sender);
6841
Matt Mueller230996f12018-10-22 19:39:446842 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6843 ASSERT_TRUE(cert);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516844 MockCertVerifier mock_cert_verifier;
Matt Mueller230996f12018-10-22 19:39:446845 CertVerifyResult verify_result;
6846 verify_result.verified_cert = cert;
6847 verify_result.is_issued_by_known_root = true;
6848 HashValue hash;
6849 // The expected value of GoodPin1 used by |test_default::kHSTSSource|.
6850 ASSERT_TRUE(
6851 hash.FromString("sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY="));
6852 verify_result.public_key_hashes.push_back(hash);
6853 mock_cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6854
6855 TestNetworkDelegate network_delegate;
estark06e0dac2015-08-07 21:56:016856 TestURLRequestContext context(true);
6857 context.set_transport_security_state(&security_state);
6858 context.set_network_delegate(&network_delegate);
6859 context.set_cert_verifier(&mock_cert_verifier);
estark06e0dac2015-08-07 21:56:016860 context.Init();
6861
6862 // Now send a request that does not trigger the violation.
6863 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366864 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446865 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166866 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016867 request->Start();
Wez2a31b222018-06-07 22:07:156868 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016869
Matt Mueller230996f12018-10-22 19:39:446870 // Check that the request succeeded, a report was not sent and the pkp was
6871 // not bypassed.
6872 EXPECT_EQ(OK, d.request_status());
estark06e0dac2015-08-07 21:56:016873 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6874 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
Matt Mueller230996f12018-10-22 19:39:446875 TransportSecurityState::STSState sts_state;
martijnc0d6b622015-06-30 19:14:406876 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:446877 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
6878 &sts_state, &pkp_state));
6879 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
6880 EXPECT_FALSE(request->ssl_info().pkp_bypassed);
estarka5da76702015-04-09 04:00:166881}
6882
dadriandf302c42016-06-10 18:48:596883TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6884 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6885 https_test_server.SetSSLConfig(
6886 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6887 https_test_server.ServeFilesFromSourceDirectory(
6888 base::FilePath(kTestFilePath));
6889 ASSERT_TRUE(https_test_server.Start());
6890
6891 // Set up a MockCertVerifier to be a local root that violates the pin
6892 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6893 ASSERT_TRUE(cert);
6894
6895 MockCertVerifier cert_verifier;
6896 CertVerifyResult verify_result;
6897 verify_result.verified_cert = cert;
6898 verify_result.is_issued_by_known_root = false;
6899 HashValue hash;
6900 ASSERT_TRUE(
6901 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6902 verify_result.public_key_hashes.push_back(hash);
6903 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
dadriandf302c42016-06-10 18:48:596904
Matt Mueller230996f12018-10-22 19:39:446905 std::string test_server_hostname = kPKPHost;
dadriandf302c42016-06-10 18:48:596906
Matt Mueller230996f12018-10-22 19:39:446907 // Set up PKP
dadriandf302c42016-06-10 18:48:596908 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446909 security_state.EnableStaticPinsForTesting();
6910 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
6911 MockCertificateReportSender mock_report_sender;
6912 security_state.SetReportSender(&mock_report_sender);
dadriandf302c42016-06-10 18:48:596913
6914 TestNetworkDelegate network_delegate;
6915 TestURLRequestContext context(true);
6916 context.set_transport_security_state(&security_state);
6917 context.set_network_delegate(&network_delegate);
6918 context.set_cert_verifier(&cert_verifier);
6919 context.Init();
6920
6921 TestDelegate d;
6922 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446923 https_test_server.GetURL(test_server_hostname, "/simple.html"),
6924 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:596925 request->Start();
Wez2a31b222018-06-07 22:07:156926 d.RunUntilComplete();
dadriandf302c42016-06-10 18:48:596927
Matt Mueller230996f12018-10-22 19:39:446928 // Check that the request succeeded, a report was not sent and the PKP was
6929 // bypassed.
6930 EXPECT_EQ(OK, d.request_status());
6931 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6932 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6933 TransportSecurityState::STSState sts_state;
dadriandf302c42016-06-10 18:48:596934 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:446935 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
6936 &sts_state, &pkp_state));
6937 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
dadriandf302c42016-06-10 18:48:596938 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6939}
6940
[email protected]242d8562012-10-30 21:20:466941TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556942 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6943 https_test_server.SetSSLConfig(
6944 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6945 https_test_server.ServeFilesFromSourceDirectory(
6946 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466947 ASSERT_TRUE(https_test_server.Start());
6948
tommycli59a63432015-11-06 00:10:556949 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166950
[email protected]242d8562012-10-30 21:20:466951 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076952 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:556953 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166954 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196955 request->Start();
Wez2a31b222018-06-07 22:07:156956 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466957
6958 // We should have set parameters from the first header, not the second.
6959 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076960 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406961 TransportSecurityState::STSState sts_state;
6962 EXPECT_TRUE(
6963 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6964 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6965 sts_state.upgrade_mode);
6966 EXPECT_FALSE(sts_state.include_subdomains);
6967 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466968}
6969
estark1614475f2016-03-10 03:46:476970// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6971// called.
6972class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6973 public:
6974 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:276975 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:476976
6977 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6978 const GURL& report_uri,
estarkae028b462017-06-20 23:25:016979 base::Time expiration,
estarkbf1b52962017-05-05 17:05:256980 const X509Certificate* validated_certificate_chain,
6981 const X509Certificate* served_certificate_chain,
6982 const SignedCertificateTimestampAndStatusList&
6983 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:476984 num_failures_++;
6985 }
6986
6987 uint32_t num_failures() { return num_failures_; }
6988
6989 private:
6990 uint32_t num_failures_;
6991};
6992
Emily Stark627238f2017-11-29 03:29:546993// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:476994// for every certificate.
6995class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6996 public:
6997 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:546998 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:276999 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:477000
Emily Stark627238f2017-11-29 03:29:547001 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:477002 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:237003 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:207004 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:477005 return default_result_;
7006 }
7007
Emily Stark627238f2017-11-29 03:29:547008 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:477009 default_result_ = default_result;
7010 }
7011
7012 private:
Emily Stark627238f2017-11-29 03:29:547013 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:477014};
7015
Emily Stark4cfecf072017-08-08 01:05:517016// Tests that Expect CT headers for the preload list are processed correctly.
7017TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:357018 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7019
estark1614475f2016-03-10 03:46:477020 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7021 https_test_server.SetSSLConfig(
7022 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7023 https_test_server.ServeFilesFromSourceDirectory(
7024 base::FilePath(kTestFilePath));
7025 ASSERT_TRUE(https_test_server.Start());
7026
7027 MockExpectCTReporter reporter;
7028 TransportSecurityState transport_security_state;
7029 transport_security_state.enable_static_expect_ct_ = true;
7030 transport_security_state.SetExpectCTReporter(&reporter);
7031
7032 // Set up a MockCertVerifier to accept the certificate that the server sends.
7033 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7034 ASSERT_TRUE(cert);
7035 MockCertVerifier cert_verifier;
7036 CertVerifyResult verify_result;
7037 verify_result.verified_cert = cert;
7038 verify_result.is_issued_by_known_root = true;
7039 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7040
rsleevi22cae1672016-12-28 01:53:367041 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
7042 // CT violation.
7043 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:477044 MockCTPolicyEnforcer ct_policy_enforcer;
7045 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547046 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:477047
7048 TestNetworkDelegate network_delegate;
7049 // Use a MockHostResolver (which by default maps all hosts to
7050 // 127.0.0.1) so that the request can be sent to a site on the Expect
7051 // CT preload list.
7052 MockHostResolver host_resolver;
7053 TestURLRequestContext context(true);
7054 context.set_host_resolver(&host_resolver);
7055 context.set_transport_security_state(&transport_security_state);
7056 context.set_network_delegate(&network_delegate);
7057 context.set_cert_verifier(&cert_verifier);
7058 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:467059 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:477060 context.Init();
7061
7062 // Now send a request to trigger the violation.
7063 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:517064 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:477065 GURL::Replacements replace_host;
7066 replace_host.SetHostStr(kExpectCTStaticHostname);
7067 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:167068 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
7069 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:477070 violating_request->Start();
Wez2a31b222018-06-07 22:07:157071 d.RunUntilComplete();
estark1614475f2016-03-10 03:46:477072
7073 EXPECT_EQ(1u, reporter.num_failures());
7074}
Emily Stark4cfecf072017-08-08 01:05:517075
7076// Tests that Expect CT HTTP headers are processed correctly.
7077TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
7078 base::test::ScopedFeatureList feature_list;
7079 feature_list.InitAndEnableFeature(
7080 TransportSecurityState::kDynamicExpectCTFeature);
7081
7082 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7083 https_test_server.SetSSLConfig(
7084 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7085 https_test_server.ServeFilesFromSourceDirectory(
7086 base::FilePath(kTestFilePath));
7087 ASSERT_TRUE(https_test_server.Start());
7088
7089 MockExpectCTReporter reporter;
7090 TransportSecurityState transport_security_state;
7091 transport_security_state.SetExpectCTReporter(&reporter);
7092
7093 // Set up a MockCertVerifier to accept the certificate that the server sends.
7094 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7095 ASSERT_TRUE(cert);
7096 MockCertVerifier cert_verifier;
7097 CertVerifyResult verify_result;
7098 verify_result.verified_cert = cert;
7099 verify_result.is_issued_by_known_root = true;
7100 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7101
7102 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7103 // compliance.
7104 DoNothingCTVerifier ct_verifier;
7105 MockCTPolicyEnforcer ct_policy_enforcer;
7106 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547107 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517108
7109 TestNetworkDelegate network_delegate;
7110 // Use a MockHostResolver (which by default maps all hosts to
7111 // 127.0.0.1).
7112 MockHostResolver host_resolver;
7113 TestURLRequestContext context(true);
7114 context.set_host_resolver(&host_resolver);
7115 context.set_transport_security_state(&transport_security_state);
7116 context.set_network_delegate(&network_delegate);
7117 context.set_cert_verifier(&cert_verifier);
7118 context.set_cert_transparency_verifier(&ct_verifier);
7119 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7120 context.Init();
7121
7122 // Now send a request to trigger the header processing.
7123 TestDelegate d;
7124 GURL url = https_test_server.GetURL("/expect-ct-header.html");
7125 std::unique_ptr<URLRequest> request(context.CreateRequest(
7126 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7127 request->Start();
Wez2a31b222018-06-07 22:07:157128 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517129
7130 TransportSecurityState::ExpectCTState state;
7131 ASSERT_TRUE(
7132 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7133 EXPECT_TRUE(state.enforce);
7134 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7135}
7136
7137// Tests that if multiple Expect CT HTTP headers are sent, they are all
7138// processed.
7139TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
7140 base::test::ScopedFeatureList feature_list;
7141 feature_list.InitAndEnableFeature(
7142 TransportSecurityState::kDynamicExpectCTFeature);
7143
7144 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7145 https_test_server.SetSSLConfig(
7146 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7147 https_test_server.ServeFilesFromSourceDirectory(
7148 base::FilePath(kTestFilePath));
7149 ASSERT_TRUE(https_test_server.Start());
7150
7151 MockExpectCTReporter reporter;
7152 TransportSecurityState transport_security_state;
7153 transport_security_state.SetExpectCTReporter(&reporter);
7154
7155 // Set up a MockCertVerifier to accept the certificate that the server sends.
7156 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7157 ASSERT_TRUE(cert);
7158 MockCertVerifier cert_verifier;
7159 CertVerifyResult verify_result;
7160 verify_result.verified_cert = cert;
7161 verify_result.is_issued_by_known_root = true;
7162 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7163
7164 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7165 // compliance.
7166 DoNothingCTVerifier ct_verifier;
7167 MockCTPolicyEnforcer ct_policy_enforcer;
7168 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547169 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517170
7171 TestNetworkDelegate network_delegate;
7172 // Use a MockHostResolver (which by default maps all hosts to
7173 // 127.0.0.1).
7174 MockHostResolver host_resolver;
7175 TestURLRequestContext context(true);
7176 context.set_host_resolver(&host_resolver);
7177 context.set_transport_security_state(&transport_security_state);
7178 context.set_network_delegate(&network_delegate);
7179 context.set_cert_verifier(&cert_verifier);
7180 context.set_cert_transparency_verifier(&ct_verifier);
7181 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7182 context.Init();
7183
7184 // Now send a request to trigger the header processing.
7185 TestDelegate d;
7186 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7187 std::unique_ptr<URLRequest> request(context.CreateRequest(
7188 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7189 request->Start();
Wez2a31b222018-06-07 22:07:157190 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517191
7192 TransportSecurityState::ExpectCTState state;
7193 ASSERT_TRUE(
7194 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7195 EXPECT_TRUE(state.enforce);
7196 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7197}
7198
mmenkefd9d15c2017-06-29 13:45:547199#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477200
Lily Chenfec60d92019-01-24 01:16:427201#if BUILDFLAG(ENABLE_REPORTING)
7202
Lily Chend3930e72019-03-01 19:31:117203TEST_F(URLRequestTestHTTP, NetworkErrorLogging_DontReportIfNetworkNotAccessed) {
7204 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7205 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7206 ASSERT_TRUE(https_test_server.Start());
7207 GURL request_url = https_test_server.GetURL("/cachetime");
7208
7209 TestNetworkErrorLoggingService nel_service;
7210 TestURLRequestContext context(true);
7211 context.set_network_error_logging_service(&nel_service);
7212 context.Init();
7213
7214 // Populate the cache.
7215 TestDelegate d;
7216 std::unique_ptr<URLRequest> request(context.CreateRequest(
7217 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7218 request->Start();
7219 d.RunUntilComplete();
7220
7221 ASSERT_EQ(1u, nel_service.errors().size());
7222 const TestNetworkErrorLoggingService::RequestDetails& error =
7223 nel_service.errors()[0];
7224 EXPECT_EQ(request_url, error.uri);
7225 EXPECT_EQ(200, error.status_code);
7226 EXPECT_EQ(OK, error.type);
7227
7228 request = context.CreateRequest(request_url, DEFAULT_PRIORITY, &d,
7229 TRAFFIC_ANNOTATION_FOR_TESTS);
7230 request->Start();
7231 d.RunUntilComplete();
7232
7233 EXPECT_FALSE(request->response_info().network_accessed);
7234 EXPECT_TRUE(request->response_info().was_cached);
7235 // No additional NEL report was generated.
7236 EXPECT_EQ(1u, nel_service.errors().size());
7237}
7238
Lily Chenfec60d92019-01-24 01:16:427239TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicSuccess) {
7240 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7241 https_test_server.ServeFilesFromSourceDirectory(
7242 base::FilePath(kTestFilePath));
7243 ASSERT_TRUE(https_test_server.Start());
7244 GURL request_url = https_test_server.GetURL("/simple.html");
7245
7246 TestNetworkErrorLoggingService nel_service;
7247 TestURLRequestContext context(true);
7248 context.set_network_error_logging_service(&nel_service);
7249 context.Init();
7250
7251 TestDelegate d;
7252 std::unique_ptr<URLRequest> request(context.CreateRequest(
7253 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7254 request->Start();
7255 d.RunUntilComplete();
7256
7257 ASSERT_EQ(1u, nel_service.errors().size());
7258 const TestNetworkErrorLoggingService::RequestDetails& error =
7259 nel_service.errors()[0];
7260 EXPECT_EQ(request_url, error.uri);
7261 EXPECT_EQ(200, error.status_code);
7262 EXPECT_EQ(OK, error.type);
7263}
7264
7265TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicError) {
7266 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7267 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7268 ASSERT_TRUE(https_test_server.Start());
7269 GURL request_url = https_test_server.GetURL("/close-socket");
7270
7271 TestNetworkErrorLoggingService nel_service;
7272 TestURLRequestContext context(true);
7273 context.set_network_error_logging_service(&nel_service);
7274 context.Init();
7275
7276 TestDelegate d;
7277 std::unique_ptr<URLRequest> request(context.CreateRequest(
7278 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7279 request->Start();
7280 d.RunUntilComplete();
7281
7282 ASSERT_EQ(1u, nel_service.errors().size());
7283 const TestNetworkErrorLoggingService::RequestDetails& error =
7284 nel_service.errors()[0];
7285 EXPECT_EQ(request_url, error.uri);
7286 EXPECT_EQ(0, error.status_code);
7287 EXPECT_EQ(ERR_EMPTY_RESPONSE, error.type);
7288}
7289
7290TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Redirect) {
7291 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7292 https_test_server.ServeFilesFromSourceDirectory(
7293 base::FilePath(kTestFilePath));
7294 ASSERT_TRUE(https_test_server.Start());
7295 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7296 GURL redirect_url = https_test_server.GetURL("/with-headers.html");
7297
7298 TestNetworkErrorLoggingService nel_service;
7299 TestURLRequestContext context(true);
7300 context.set_network_error_logging_service(&nel_service);
7301 context.Init();
7302
7303 TestDelegate d;
7304 std::unique_ptr<URLRequest> request(context.CreateRequest(
7305 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7306 request->Start();
7307 d.RunUntilComplete();
7308
7309 ASSERT_EQ(2u, nel_service.errors().size());
7310 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7311 nel_service.errors()[0];
7312 EXPECT_EQ(request_url, error1.uri);
7313 EXPECT_EQ(302, error1.status_code);
7314 EXPECT_EQ(OK, error1.type);
7315 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7316 nel_service.errors()[1];
7317 EXPECT_EQ(redirect_url, error2.uri);
7318 EXPECT_EQ(200, error2.status_code);
7319 EXPECT_EQ(OK, error2.type);
7320}
7321
Lily Chend3930e72019-03-01 19:31:117322TEST_F(URLRequestTestHTTP, NetworkErrorLogging_RedirectWithoutLocationHeader) {
7323 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7324 https_test_server.ServeFilesFromSourceDirectory(
7325 base::FilePath(kTestFilePath));
7326 ASSERT_TRUE(https_test_server.Start());
7327 GURL request_url = https_test_server.GetURL("/308-without-location-header");
7328
7329 TestNetworkErrorLoggingService nel_service;
7330 TestURLRequestContext context(true);
7331 context.set_network_error_logging_service(&nel_service);
7332 context.Init();
7333
7334 TestDelegate d;
7335 std::unique_ptr<URLRequest> request(context.CreateRequest(
7336 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7337 request->Start();
7338 d.RunUntilComplete();
7339
7340 ASSERT_EQ(1u, nel_service.errors().size());
7341 const TestNetworkErrorLoggingService::RequestDetails& error =
7342 nel_service.errors()[0];
7343 EXPECT_EQ(request_url, error.uri);
7344 EXPECT_EQ(308, error.status_code);
7345 // The body of the response was successfully read.
7346 EXPECT_EQ(OK, error.type);
7347}
7348
Lily Chenfec60d92019-01-24 01:16:427349TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Auth) {
7350 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7351 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7352 ASSERT_TRUE(https_test_server.Start());
7353 GURL request_url = https_test_server.GetURL("/auth-basic");
7354
7355 TestNetworkErrorLoggingService nel_service;
7356 TestURLRequestContext context(true);
7357 context.set_network_error_logging_service(&nel_service);
7358 context.Init();
7359
7360 TestDelegate d;
7361 d.set_credentials(AuthCredentials(kUser, kSecret));
7362 std::unique_ptr<URLRequest> request(context.CreateRequest(
7363 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7364 request->Start();
7365 d.RunUntilComplete();
7366
7367 ASSERT_EQ(2u, nel_service.errors().size());
7368 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7369 nel_service.errors()[0];
7370 EXPECT_EQ(request_url, error1.uri);
7371 EXPECT_EQ(401, error1.status_code);
7372 EXPECT_EQ(OK, error1.type);
7373 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7374 nel_service.errors()[1];
7375 EXPECT_EQ(request_url, error2.uri);
7376 EXPECT_EQ(200, error2.status_code);
7377 EXPECT_EQ(OK, error2.type);
7378}
7379
Lily Chend3930e72019-03-01 19:31:117380TEST_F(URLRequestTestHTTP, NetworkErrorLogging_304Response) {
7381 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7382 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7383 ASSERT_TRUE(https_test_server.Start());
7384 GURL request_url = https_test_server.GetURL("/auth-basic");
7385
7386 TestNetworkErrorLoggingService nel_service;
7387 TestURLRequestContext context(true);
7388 context.set_network_error_logging_service(&nel_service);
7389 context.Init();
7390
7391 // populate the cache
7392 {
7393 TestDelegate d;
7394 d.set_credentials(AuthCredentials(kUser, kSecret));
7395 std::unique_ptr<URLRequest> r(context.CreateRequest(
7396 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7397 r->Start();
7398 d.RunUntilComplete();
7399 }
7400 ASSERT_EQ(2u, nel_service.errors().size());
7401 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7402 nel_service.errors()[0];
7403 EXPECT_EQ(request_url, error1.uri);
7404 EXPECT_EQ(401, error1.status_code);
7405 EXPECT_EQ(OK, error1.type);
7406 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7407 nel_service.errors()[1];
7408 EXPECT_EQ(request_url, error2.uri);
7409 EXPECT_EQ(200, error2.status_code);
7410 EXPECT_EQ(OK, error2.type);
7411
7412 // repeat request with end-to-end validation. since auth-basic results in a
7413 // cachable page, we expect this test to result in a 304. in which case, the
7414 // response should be fetched from the cache.
7415 {
7416 TestDelegate d;
7417 d.set_credentials(AuthCredentials(kUser, kSecret));
7418 std::unique_ptr<URLRequest> r(context.CreateRequest(
7419 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7420 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7421 r->Start();
7422 d.RunUntilComplete();
7423
7424 // Should be the same cached document.
7425 EXPECT_TRUE(r->was_cached());
7426 }
7427 ASSERT_EQ(3u, nel_service.errors().size());
7428 const TestNetworkErrorLoggingService::RequestDetails& error3 =
7429 nel_service.errors()[2];
7430 EXPECT_EQ(request_url, error3.uri);
7431 EXPECT_EQ(304, error3.status_code);
7432 EXPECT_EQ(OK, error3.type);
7433}
7434
7435TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelInResponseStarted) {
Lily Chenfec60d92019-01-24 01:16:427436 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7437 https_test_server.ServeFilesFromSourceDirectory(
7438 base::FilePath(kTestFilePath));
7439 ASSERT_TRUE(https_test_server.Start());
7440 GURL request_url = https_test_server.GetURL("/simple.html");
7441
7442 TestNetworkErrorLoggingService nel_service;
7443 TestURLRequestContext context(true);
7444 context.set_network_error_logging_service(&nel_service);
7445 context.Init();
7446
7447 TestDelegate d;
7448 d.set_cancel_in_response_started(true);
7449 std::unique_ptr<URLRequest> request(context.CreateRequest(
7450 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7451 request->Start();
7452 d.RunUntilComplete();
7453
7454 ASSERT_EQ(1u, nel_service.errors().size());
7455 const TestNetworkErrorLoggingService::RequestDetails& error =
7456 nel_service.errors()[0];
7457 EXPECT_EQ(request_url, error.uri);
7458 EXPECT_EQ(200, error.status_code);
Lily Chend3930e72019-03-01 19:31:117459 // Headers were received and the body should have been read but was not.
7460 EXPECT_EQ(ERR_ABORTED, error.type);
7461}
7462
7463TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelOnDataReceived) {
7464 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7465 https_test_server.ServeFilesFromSourceDirectory(
7466 base::FilePath(kTestFilePath));
7467 ASSERT_TRUE(https_test_server.Start());
7468 GURL request_url = https_test_server.GetURL("/simple.html");
7469
7470 TestNetworkErrorLoggingService nel_service;
7471 TestURLRequestContext context(true);
7472 context.set_network_error_logging_service(&nel_service);
7473 context.Init();
7474
7475 TestDelegate d;
7476 d.set_cancel_in_received_data(true);
7477 std::unique_ptr<URLRequest> request(context.CreateRequest(
7478 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7479 request->Start();
7480 d.RunUntilComplete();
7481
7482 ASSERT_EQ(1u, nel_service.errors().size());
7483 const TestNetworkErrorLoggingService::RequestDetails& error =
7484 nel_service.errors()[0];
7485 EXPECT_EQ(request_url, error.uri);
7486 EXPECT_EQ(200, error.status_code);
7487 // Data was received but the body was not completely read.
7488 EXPECT_EQ(ERR_ABORTED, error.type);
7489}
7490
7491TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelRedirect) {
7492 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7493 https_test_server.ServeFilesFromSourceDirectory(
7494 base::FilePath(kTestFilePath));
7495 ASSERT_TRUE(https_test_server.Start());
7496 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7497
7498 TestNetworkErrorLoggingService nel_service;
7499 TestURLRequestContext context(true);
7500 context.set_network_error_logging_service(&nel_service);
7501 context.Init();
7502
7503 TestDelegate d;
7504 d.set_cancel_in_received_redirect(true);
7505 std::unique_ptr<URLRequest> request(context.CreateRequest(
7506 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7507 request->Start();
7508 d.RunUntilComplete();
7509
7510 ASSERT_EQ(1u, nel_service.errors().size());
7511 const TestNetworkErrorLoggingService::RequestDetails& error =
7512 nel_service.errors()[0];
7513 EXPECT_EQ(request_url, error.uri);
7514 EXPECT_EQ(302, error.status_code);
7515 // A valid HTTP response was received, even though the request was cancelled.
Lily Chenfec60d92019-01-24 01:16:427516 EXPECT_EQ(OK, error.type);
7517}
7518
7519#endif // BUILDFLAG(ENABLE_REPORTING)
7520
[email protected]316c1e5e2012-09-12 15:17:447521TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557522 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447523
7524 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077525 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557526 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167527 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197528 req->Start();
Wez2a31b222018-06-07 22:07:157529 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447530
7531 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197532 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447533 EXPECT_EQ("text/html", mime_type);
7534
7535 std::string charset;
[email protected]f7022f32014-08-21 16:32:197536 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447537 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197538 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447539}
7540
[email protected]02494ec2014-05-07 15:05:297541TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347542 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347543 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347544 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027545 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347546
7547 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507548 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347549}
7550
brettwa1228ebb2016-10-28 03:51:347551#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297552TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7553 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7554 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457555 FileProtocolHandler file_protocol_handler(
7556 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297557 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7558
7559 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507560 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297561}
7562
[email protected]588614c22013-08-16 00:09:027563TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557564 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447565
7566 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077567 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557568 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167569 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197570 req->Start();
Wez2a31b222018-06-07 22:07:157571 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447572
maksim.sisovb53724b52016-09-16 05:30:507573 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307574
7575 // The redirect should have been rejected before reporting it to the caller.
7576 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447577}
brettwa1228ebb2016-10-28 03:51:347578#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447579
[email protected]588614c22013-08-16 00:09:027580TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557581 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027582
7583 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077584 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557585 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167586 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197587 req->Start();
Wez2a31b222018-06-07 22:07:157588 d.RunUntilComplete();
[email protected]588614c22013-08-16 00:09:027589
maksim.sisovb53724b52016-09-16 05:30:507590 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307591
7592 // The redirect should have been rejected before reporting it to the
7593 // caller. See https://crbug.com/723796
7594 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027595}
7596
davidbend894710b2017-06-06 19:28:307597// Test that redirects to invalid URLs are rejected. See
7598// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447599TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557600 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447601
7602 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077603 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557604 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167605 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197606 req->Start();
Wez2a31b222018-06-07 22:07:157607 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447608
davidbend894710b2017-06-06 19:28:307609 EXPECT_EQ(1, d.response_started_count());
7610 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7611
7612 // The redirect should have been rejected before reporting it to the caller.
7613 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447614}
7615
[email protected]e50efea2014-03-24 18:41:007616// Make sure redirects are cached, despite not reading their bodies.
7617TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557618 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007619 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557620 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007621
7622 {
7623 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077624 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167625 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197626 req->Start();
Wez2a31b222018-06-07 22:07:157627 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507628 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007629 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557630 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007631 }
7632
7633 {
7634 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077635 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167636 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197637 req->Start();
Wez0e717112018-06-18 23:09:227638 d.RunUntilRedirect();
[email protected]e50efea2014-03-24 18:41:007639
7640 EXPECT_EQ(1, d.received_redirect_count());
7641 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197642 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007643
Arthur Sonzognib8465ff72019-01-04 18:44:357644 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7645 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157646 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007647 EXPECT_EQ(1, d.received_redirect_count());
7648 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507649 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557650 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007651 }
7652}
7653
7654// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7655// when the headers are read, since the body won't have been read.
7656TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557657 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007658 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557659 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007660
7661 {
7662 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557663 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007664 default_network_delegate_.set_redirect_on_headers_received_url(
7665 redirect_to_url);
7666
7667 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077668 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167669 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197670 req->Start();
Wez2a31b222018-06-07 22:07:157671 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507672 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007673 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197674 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007675 }
7676
7677 {
7678 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077679 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167680 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197681 req->Start();
Wez2a31b222018-06-07 22:07:157682 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007683
maksim.sisovb53724b52016-09-16 05:30:507684 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197685 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007686 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197687 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007688 }
7689}
7690
[email protected]5f714132014-03-26 10:41:167691// Tests that redirection to an unsafe URL is allowed when it has been marked as
7692// safe.
7693TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557694 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167695
7696 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7697 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7698 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7699
7700 TestDelegate d;
7701 {
Ryan Sleevib8449e02018-07-15 04:31:077702 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167703 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7704 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167705
[email protected]f7022f32014-08-21 16:32:197706 r->Start();
Wez2a31b222018-06-07 22:07:157707 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167708
maksim.sisovb53724b52016-09-16 05:30:507709 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197710 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197711 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167712 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7713 }
7714}
7715
7716// Tests that a redirect to a different unsafe URL is blocked, even after adding
7717// some other URL to the whitelist.
7718TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557719 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167720
7721 GURL unsafe_url("data:text/html,something");
7722 GURL different_unsafe_url("data:text/html,something-else");
7723 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7724 default_network_delegate_.set_allowed_unsafe_redirect_url(
7725 different_unsafe_url);
7726
7727 TestDelegate d;
7728 {
Ryan Sleevib8449e02018-07-15 04:31:077729 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167730 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7731 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167732
[email protected]f7022f32014-08-21 16:32:197733 r->Start();
Wez2a31b222018-06-07 22:07:157734 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167735
maksim.sisovb53724b52016-09-16 05:30:507736 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307737
7738 // The redirect should have been rejected before reporting it to the caller.
7739 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167740 }
7741}
7742
[email protected]5f714132014-03-26 10:41:167743// Redirects from an URL with fragment to an unsafe URL with fragment should
7744// be allowed, and the reference fragment of the target URL should be preserved.
7745TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557746 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167747
tommycli59a63432015-11-06 00:10:557748 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167749 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7750 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7751
7752 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7753 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7754
7755 TestDelegate d;
7756 {
Ryan Sleevib8449e02018-07-15 04:31:077757 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167758 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167759
[email protected]f7022f32014-08-21 16:32:197760 r->Start();
Wez2a31b222018-06-07 22:07:157761 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167762
[email protected]f7022f32014-08-21 16:32:197763 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507764 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197765 EXPECT_EQ(original_url, r->original_url());
7766 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167767 }
7768}
7769
7770// When a delegate has specified a safe redirect URL, but it does not match the
7771// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147772TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557773 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167774
tommycli59a63432015-11-06 00:10:557775 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167776 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557777 GURL redirect_url(http_test_server()->GetURL("/target"));
7778 GURL expected_redirect_url(
7779 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167780
7781 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7782 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7783
7784 TestDelegate d;
7785 {
Ryan Sleevib8449e02018-07-15 04:31:077786 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167787 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167788
[email protected]f7022f32014-08-21 16:32:197789 r->Start();
Wez2a31b222018-06-07 22:07:157790 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167791
[email protected]f7022f32014-08-21 16:32:197792 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507793 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197794 EXPECT_EQ(original_url, r->original_url());
7795 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167796 }
7797}
7798
[email protected]f878230e2014-04-03 15:36:147799// When a delegate has specified a safe redirect URL, assume that the redirect
7800// URL should not be changed. In particular, the reference fragment should not
7801// be modified.
7802TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557803 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147804
tommycli59a63432015-11-06 00:10:557805 GURL original_url(
7806 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147807 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7808
7809 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7810 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7811
7812 TestDelegate d;
7813 {
Ryan Sleevib8449e02018-07-15 04:31:077814 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167815 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147816
[email protected]f7022f32014-08-21 16:32:197817 r->Start();
Wez2a31b222018-06-07 22:07:157818 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147819
[email protected]f7022f32014-08-21 16:32:197820 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507821 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197822 EXPECT_EQ(original_url, r->original_url());
7823 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147824 }
7825}
7826
7827// When a URLRequestRedirectJob is created, the redirection must be followed and
7828// the reference fragment of the target URL must not be modified.
7829TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557830 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147831
tommycli59a63432015-11-06 00:10:557832 GURL original_url(
7833 http_test_server()->GetURL("/original#should-not-be-appended"));
7834 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147835
7836 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077837 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167838 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147839
danakj8522a25b2016-04-16 00:17:367840 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197841 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427842 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7843 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:147844
[email protected]f7022f32014-08-21 16:32:197845 r->Start();
Wez2a31b222018-06-07 22:07:157846 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147847
maksim.sisovb53724b52016-09-16 05:30:507848 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197849 EXPECT_EQ(original_url, r->original_url());
7850 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147851}
7852
lizeb5120f6dc2016-02-19 09:29:447853TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
7854 ASSERT_TRUE(http_test_server()->Start());
7855
7856 const std::string referrer("foobar://totally.legit.referrer");
7857 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077858 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167859 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7860 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:447861 req->SetReferrer(referrer);
7862 req->Start();
Wez2a31b222018-06-07 22:07:157863 d.RunUntilComplete();
lizeb5120f6dc2016-02-19 09:29:447864
7865 EXPECT_EQ(std::string("None"), d.data_received());
7866}
7867
[email protected]316c1e5e2012-09-12 15:17:447868TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:557869 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447870
7871 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077872 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167873 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7874 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197875 req->SetReferrer("http://user:[email protected]/");
7876 req->Start();
Wez2a31b222018-06-07 22:07:157877 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447878
7879 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
7880}
7881
[email protected]99ecf6e2013-04-10 22:46:137882TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:557883 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137884
7885 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077886 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167887 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7888 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197889 req->SetReferrer("http://foo.com/test#fragment");
7890 req->Start();
Wez2a31b222018-06-07 22:07:157891 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:137892
7893 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
7894}
7895
7896TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:557897 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137898
7899 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077900 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167901 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7902 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197903 req->SetReferrer("http://foo.com/test#fragment");
7904 req->SetReferrer("");
7905 req->Start();
Wez2a31b222018-06-07 22:07:157906 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:137907
7908 EXPECT_EQ(std::string("None"), d.data_received());
7909}
7910
[email protected]316c1e5e2012-09-12 15:17:447911TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:557912 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447913
7914 TestDelegate d;
7915 {
7916 d.set_cancel_in_received_redirect(true);
Ryan Sleevib8449e02018-07-15 04:31:077917 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167918 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7919 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197920 req->Start();
Wez2a31b222018-06-07 22:07:157921 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447922
7923 EXPECT_EQ(1, d.response_started_count());
7924 EXPECT_EQ(0, d.bytes_received());
7925 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507926 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447927 }
7928}
7929
7930TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:557931 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447932
7933 TestDelegate d;
7934 {
tommycli59a63432015-11-06 00:10:557935 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:077936 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167937 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047938
[email protected]f7022f32014-08-21 16:32:197939 req->Start();
Wez0e717112018-06-18 23:09:227940 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:447941
7942 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:237943 EXPECT_TRUE(d.have_full_request_headers());
7944 CheckFullRequestHeaders(d.full_request_headers(), test_url);
7945 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:447946
Arthur Sonzognib8465ff72019-01-04 18:44:357947 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7948 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157949 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447950
7951 EXPECT_EQ(1, d.response_started_count());
7952 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507953 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447954
[email protected]6cdfd7f2013-02-08 20:40:157955 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:197956 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477957 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:447958 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7959
7960 std::string contents;
[email protected]82f84b92013-08-30 18:23:507961 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:447962 EXPECT_EQ(contents, d.data_received());
7963 }
7964}
7965
[email protected]79e1fd62013-06-20 06:50:047966TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:557967 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:047968
7969 TestDelegate d;
7970 {
tommycli59a63432015-11-06 00:10:557971 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:077972 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167973 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047974
7975 EXPECT_FALSE(d.have_full_request_headers());
7976
[email protected]f7022f32014-08-21 16:32:197977 req->Start();
Wez0e717112018-06-18 23:09:227978 d.RunUntilRedirect();
[email protected]79e1fd62013-06-20 06:50:047979
7980 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:047981
Arthur Sonzognib8465ff72019-01-04 18:44:357982 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7983 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157984 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:047985
tommycli59a63432015-11-06 00:10:557986 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:047987 EXPECT_EQ(1, d.response_started_count());
7988 EXPECT_TRUE(d.have_full_request_headers());
7989 CheckFullRequestHeaders(d.full_request_headers(), target_url);
7990 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507991 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:047992
7993 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:197994 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477995 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:047996 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7997
7998 std::string contents;
[email protected]82f84b92013-08-30 18:23:507999 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:048000 EXPECT_EQ(contents, d.data_received());
8001 }
8002}
8003
Arthur Sonzognib8465ff72019-01-04 18:44:358004TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedHeaders) {
Chong Zhang7607f1f2018-06-01 20:52:208005 ASSERT_TRUE(http_test_server()->Start());
8006
8007 TestDelegate d;
8008 {
Chong Zhang7607f1f2018-06-01 20:52:208009 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078010 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Chong Zhang7607f1f2018-06-01 20:52:208011 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8012
8013 // Set initial headers for the request.
8014 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8015 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8016
8017 req->Start();
Wez0e717112018-06-18 23:09:228018 d.RunUntilRedirect();
Chong Zhang7607f1f2018-06-01 20:52:208019
8020 // Initial request should only have initial headers.
8021 EXPECT_EQ(1, d.received_redirect_count());
8022 EXPECT_TRUE(d.have_full_request_headers());
8023 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8024 std::string sent_value;
8025 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8026 EXPECT_EQ("Value1", sent_value);
8027 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8028 EXPECT_EQ("Value2", sent_value);
8029 EXPECT_FALSE(sent_headers1.GetHeader("Header3", &sent_value));
8030 d.ClearFullRequestHeaders();
8031
8032 // Overwrite Header2 and add Header3.
Arthur Sonzognib8465ff72019-01-04 18:44:358033 net::HttpRequestHeaders modified_headers;
8034 modified_headers.SetHeader("Header2", "");
8035 modified_headers.SetHeader("Header3", "Value3");
Chong Zhang7607f1f2018-06-01 20:52:208036
Arthur Sonzognib8465ff72019-01-04 18:44:358037 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8038 modified_headers);
Wez2a31b222018-06-07 22:07:158039 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:208040
8041 EXPECT_EQ(1, d.response_started_count());
8042 EXPECT_FALSE(d.received_data_before_response());
8043 EXPECT_EQ(OK, d.request_status());
8044
8045 // Redirected request should also have modified headers.
8046 EXPECT_TRUE(d.have_full_request_headers());
8047 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8048 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8049 EXPECT_EQ("Value1", sent_value);
8050 EXPECT_TRUE(sent_headers2.GetHeader("Header2", &sent_value));
8051 EXPECT_EQ("", sent_value);
8052 EXPECT_TRUE(sent_headers2.GetHeader("Header3", &sent_value));
8053 EXPECT_EQ("Value3", sent_value);
8054 }
8055}
8056
Arthur Sonzognib8465ff72019-01-04 18:44:358057TEST_F(URLRequestTestHTTP, DeferredRedirect_RemovedHeaders) {
8058 ASSERT_TRUE(http_test_server()->Start());
8059
8060 TestDelegate d;
8061 {
8062 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
8063 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8064 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8065
8066 // Set initial headers for the request.
8067 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8068 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8069
8070 req->Start();
8071 d.RunUntilRedirect();
8072
8073 // Initial request should have initial headers.
8074 EXPECT_EQ(1, d.received_redirect_count());
8075 EXPECT_TRUE(d.have_full_request_headers());
8076 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8077 std::string sent_value;
8078 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8079 EXPECT_EQ("Value1", sent_value);
8080 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8081 EXPECT_EQ("Value2", sent_value);
8082 d.ClearFullRequestHeaders();
8083
8084 // Keep Header1 and remove Header2.
8085 std::vector<std::string> removed_headers({"Header2"});
8086 req->FollowDeferredRedirect(removed_headers,
8087 base::nullopt /* modified_headers */);
8088 d.RunUntilComplete();
8089
8090 EXPECT_EQ(1, d.response_started_count());
8091 EXPECT_FALSE(d.received_data_before_response());
8092 EXPECT_EQ(OK, d.request_status());
8093
8094 // Redirected request should also have
8095 EXPECT_TRUE(d.have_full_request_headers());
8096 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8097 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8098 EXPECT_EQ("Value1", sent_value);
8099 EXPECT_FALSE(sent_headers2.GetHeader("Header2", &sent_value));
8100 }
8101}
8102
[email protected]316c1e5e2012-09-12 15:17:448103TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:558104 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448105
8106 TestDelegate d;
8107 {
Ryan Sleevib8449e02018-07-15 04:31:078108 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168109 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8110 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198111 req->Start();
Wez0e717112018-06-18 23:09:228112 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:448113
8114 EXPECT_EQ(1, d.received_redirect_count());
8115
[email protected]f7022f32014-08-21 16:32:198116 req->Cancel();
Wez2a31b222018-06-07 22:07:158117 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448118
8119 EXPECT_EQ(1, d.response_started_count());
8120 EXPECT_EQ(0, d.bytes_received());
8121 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508122 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448123 }
8124}
8125
8126TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:558127 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448128
[email protected]3b23a222013-05-15 21:33:258129 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:448130 {
8131 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078132 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558133 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168134 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448135 HttpRequestHeaders headers;
8136 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198137 req->SetExtraRequestHeaders(headers);
8138 req->Start();
Wez2a31b222018-06-07 22:07:158139 d.RunUntilComplete();
[email protected]3b23a222013-05-15 21:33:258140
8141 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198142 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258143 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448144 }
8145
[email protected]3b23a222013-05-15 21:33:258146 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:448147 {
8148 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078149 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558150 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168151 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448152 HttpRequestHeaders headers;
8153 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198154 req->SetExtraRequestHeaders(headers);
8155 req->Start();
Wez2a31b222018-06-07 22:07:158156 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448157
[email protected]f7022f32014-08-21 16:32:198158 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258159
8160 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198161 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258162 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:448163 }
8164
[email protected]3b23a222013-05-15 21:33:258165 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:448166 {
8167 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078168 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558169 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168170 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448171 HttpRequestHeaders headers;
8172 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:198173 req->SetExtraRequestHeaders(headers);
8174 req->Start();
Wez2a31b222018-06-07 22:07:158175 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448176
[email protected]f7022f32014-08-21 16:32:198177 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258178
8179 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198180 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258181 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448182 }
8183}
8184
8185TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:558186 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448187
8188 // populate the cache
8189 {
8190 TestDelegate d;
8191 d.set_credentials(AuthCredentials(kUser, kSecret));
8192
Ryan Sleevib8449e02018-07-15 04:31:078193 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168194 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8195 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198196 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448197
Wez2a31b222018-06-07 22:07:158198 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448199
8200 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8201 }
8202
8203 // repeat request with end-to-end validation. since auth-basic results in a
8204 // cachable page, we expect this test to result in a 304. in which case, the
8205 // response should be fetched from the cache.
8206 {
8207 TestDelegate d;
8208 d.set_credentials(AuthCredentials(kUser, kSecret));
8209
Ryan Sleevib8449e02018-07-15 04:31:078210 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168211 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8212 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198213 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8214 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448215
Wez2a31b222018-06-07 22:07:158216 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448217
8218 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8219
8220 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198221 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:448222 }
8223}
8224
8225// Check that Set-Cookie headers in 401 responses are respected.
8226// http://crbug.com/6450
8227TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:558228 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448229
8230 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:558231 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:448232
8233 // Request a page that will give a 401 containing a Set-Cookie header.
8234 // Verify that when the transaction is restarted, it includes the new cookie.
8235 {
[email protected]ceefd7fd2012-11-29 00:36:248236 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448237 TestURLRequestContext context(true);
8238 context.set_network_delegate(&network_delegate);
8239 context.Init();
8240
8241 TestDelegate d;
8242 d.set_credentials(AuthCredentials(kUser, kSecret));
8243
danakj8522a25b2016-04-16 00:17:368244 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:168245 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
8246 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198247 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448248
Wez2a31b222018-06-07 22:07:158249 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448250
8251 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8252
8253 // Make sure we sent the cookie in the restarted transaction.
8254 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8255 != std::string::npos);
8256 }
8257
8258 // Same test as above, except this time the restart is initiated earlier
8259 // (without user intervention since identity is embedded in the URL).
8260 {
[email protected]ceefd7fd2012-11-29 00:36:248261 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448262 TestURLRequestContext context(true);
8263 context.set_network_delegate(&network_delegate);
8264 context.Init();
8265
8266 TestDelegate d;
8267
8268 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:188269 replacements.SetUsernameStr("user2");
8270 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:448271 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
8272
rhalavatib7bd7c792017-04-27 05:25:168273 std::unique_ptr<URLRequest> r(context.CreateRequest(
8274 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198275 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448276
Wez2a31b222018-06-07 22:07:158277 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448278
8279 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
8280
8281 // Make sure we sent the cookie in the restarted transaction.
8282 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8283 != std::string::npos);
8284 }
8285}
8286
Aaron Tagliaboschi028009e2019-03-07 16:28:068287TEST_F(URLRequestTestHTTP, AuthChallengeWithFilteredCookie) {
8288 ASSERT_TRUE(http_test_server()->Start());
8289
8290 GURL url_requiring_auth = http_test_server()->GetURL(
8291 "/auth-basic?set-cookie-if-not-challenged&set-cookie-if-challenged");
8292
8293 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8294 std::make_unique<TestNetworkDelegate>()); // Must outlive URLRequest.
8295 filtering_network_delegate.SetCookieFilter(
8296 "got_challenged"); // Filter the cookie auth-basic sets
8297 TestURLRequestContext context(true);
8298 context.set_network_delegate(&filtering_network_delegate);
8299 context.Init();
8300
8301 TestDelegate delegate;
8302
8303 delegate.set_credentials(AuthCredentials(kUser, kSecret));
8304
8305 std::unique_ptr<URLRequest> request(
8306 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &delegate,
8307 TRAFFIC_ANNOTATION_FOR_TESTS));
8308 request->Start();
8309
8310 delegate.RunUntilComplete();
8311 EXPECT_THAT(delegate.request_status(), IsOk());
8312
8313 // Make sure the cookie was actually filtered.
8314 EXPECT_EQ(std::string::npos,
8315 delegate.data_received().find("Cookie: got_challenged=true"));
8316 // Make sure it was blocked twice.
8317 EXPECT_EQ(2, filtering_network_delegate.blocked_set_cookie_count());
8318}
8319
[email protected]58e32bb2013-01-21 18:23:258320// Tests that load timing works as expected with auth and the cache.
8321TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:558322 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:258323
8324 // populate the cache
8325 {
8326 TestDelegate d;
8327 d.set_credentials(AuthCredentials(kUser, kSecret));
8328
Ryan Sleevib8449e02018-07-15 04:31:078329 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168330 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8331 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198332 r->Start();
[email protected]58e32bb2013-01-21 18:23:258333
Wez2a31b222018-06-07 22:07:158334 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258335
8336 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8337
8338 LoadTimingInfo load_timing_info_before_auth;
8339 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
8340 &load_timing_info_before_auth));
8341 TestLoadTimingNotReused(load_timing_info_before_auth,
8342 CONNECT_TIMING_HAS_DNS_TIMES);
8343
8344 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198345 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:258346 // The test server does not support keep alive sockets, so the second
8347 // request with auth should use a new socket.
8348 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
8349 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
8350 load_timing_info.socket_log_id);
8351 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
8352 load_timing_info.connect_timing.connect_start);
8353 }
8354
[email protected]3b23a222013-05-15 21:33:258355 // Repeat request with end-to-end validation. Since auth-basic results in a
8356 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258357 // response should be fetched from the cache.
8358 {
8359 TestDelegate d;
8360 d.set_credentials(AuthCredentials(kUser, kSecret));
8361
Ryan Sleevib8449e02018-07-15 04:31:078362 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168363 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8364 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198365 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8366 r->Start();
[email protected]58e32bb2013-01-21 18:23:258367
Wez2a31b222018-06-07 22:07:158368 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258369
8370 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8371
8372 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198373 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258374
[email protected]3b23a222013-05-15 21:33:258375 // Since there was a request that went over the wire, the load timing
8376 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258377 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198378 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258379 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258380 }
8381}
8382
[email protected]316c1e5e2012-09-12 15:17:448383// In this test, we do a POST which the server will 302 redirect.
8384// The subsequent transaction should use GET, and should not send the
8385// Content-Type header.
8386// http://code.google.com/p/chromium/issues/detail?id=843
8387TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558388 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448389
8390 const char kData[] = "hello world";
8391
8392 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078393 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168394 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8395 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198396 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078397 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448398
8399 // Set headers (some of which are specific to the POST).
8400 HttpRequestHeaders headers;
Yeol45b9e0a2018-07-27 02:03:298401 headers.SetHeader("Content-Type",
8402 "multipart/form-data;"
8403 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ");
8404 headers.SetHeader("Accept",
8405 "text/xml,application/xml,application/xhtml+xml,"
8406 "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
8407 headers.SetHeader("Accept-Language", "en-US,en");
8408 headers.SetHeader("Accept-Charset", "ISO-8859-1,*,utf-8");
8409 headers.SetHeader("Content-Length", "11");
8410 headers.SetHeader("Origin", "http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198411 req->SetExtraRequestHeaders(headers);
8412 req->Start();
Wez2a31b222018-06-07 22:07:158413 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448414
8415 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198416 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448417 EXPECT_EQ("text/html", mime_type);
8418
8419 const std::string& data = d.data_received();
8420
8421 // Check that the post-specific headers were stripped:
8422 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8423 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498424 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448425
8426 // These extra request headers should not have been stripped.
8427 EXPECT_TRUE(ContainsString(data, "Accept:"));
8428 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8429 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8430}
8431
jww5fe460ff2015-03-28 00:22:518432// The following tests check that we handle mutating the request for HTTP
8433// redirects as expected.
8434// See https://crbug.com/56373, https://crbug.com/102130, and
8435// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448436
8437TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558438 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448439
tommycli59a63432015-11-06 00:10:558440 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518441 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558442 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448443
8444 HTTPRedirectMethodTest(url, "POST", "GET", true);
8445 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8446 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518447
8448 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8449 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498450 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8451 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8452 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408453 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8454 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448455}
8456
8457TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558458 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448459
tommycli59a63432015-11-06 00:10:558460 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518461 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558462 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448463
8464 HTTPRedirectMethodTest(url, "POST", "GET", true);
8465 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8466 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518467
8468 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8469 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498470 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8471 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8472 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408473 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8474 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448475}
8476
8477TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558478 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448479
tommycli59a63432015-11-06 00:10:558480 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518481 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558482 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448483
8484 HTTPRedirectMethodTest(url, "POST", "GET", true);
8485 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8486 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518487
Alex Clarke1e08882b32017-10-06 14:22:408488 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8489 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8490 std::string());
8491 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8492 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8493 std::string());
jww5fe460ff2015-03-28 00:22:518494 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8495 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408496 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8497 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8498 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8499 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8500 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498501 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8502 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8503 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408504 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
8505 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:448506}
8507
8508TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558509 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448510
tommycli59a63432015-11-06 00:10:558511 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518512 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558513 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448514
8515 HTTPRedirectMethodTest(url, "POST", "POST", true);
8516 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8517 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518518
8519 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8520 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8521 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8522 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408523 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8524 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448525}
8526
[email protected]0a17aab32014-04-24 03:32:378527TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558528 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378529
tommycli59a63432015-11-06 00:10:558530 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518531 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558532 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378533
8534 HTTPRedirectMethodTest(url, "POST", "POST", true);
8535 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8536 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518537
8538 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8539 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8540 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8541 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408542 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8543 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:378544}
8545
8546// Make sure that 308 responses without bodies are not treated as redirects.
8547// Certain legacy apis that pre-date the response code expect this behavior
8548// (Like Google Drive).
8549TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558550 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378551
8552 TestDelegate d;
tommycli59a63432015-11-06 00:10:558553 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378554
Ryan Sleevib8449e02018-07-15 04:31:078555 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168556 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378557
[email protected]f7022f32014-08-21 16:32:198558 request->Start();
Wez2a31b222018-06-07 22:07:158559 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:508560 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378561 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198562 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378563 EXPECT_EQ("This is not a redirect.", d.data_received());
8564}
8565
[email protected]f878230e2014-04-03 15:36:148566TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558567 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148568
tommycli59a63432015-11-06 00:10:558569 GURL original_url(
8570 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8571 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148572
8573 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148574 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8575 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148576
Josh Karlinbe37f912018-12-07 01:05:148577 r->Start();
8578 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148579
Josh Karlinbe37f912018-12-07 01:05:148580 EXPECT_EQ(2U, r->url_chain().size());
8581 EXPECT_EQ(OK, d.request_status());
8582 EXPECT_EQ(original_url, r->original_url());
8583 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148584}
8585
[email protected]cba24642014-08-15 20:49:598586TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558587 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598588
tommycli59a63432015-11-06 00:10:558589 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598590 GURL first_party_url("http://example.com");
8591
8592 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148593 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8594 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8595 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598596
Josh Karlinbe37f912018-12-07 01:05:148597 r->Start();
8598 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598599
Josh Karlinbe37f912018-12-07 01:05:148600 EXPECT_EQ(2U, r->url_chain().size());
8601 EXPECT_EQ(OK, d.request_status());
8602 EXPECT_EQ(first_party_url, r->site_for_cookies());
8603}
8604
8605TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameOrigin) {
8606 ASSERT_TRUE(http_test_server()->Start());
8607
8608 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8609 url::Origin top_frame_origin =
8610 url::Origin::Create(GURL("http://example.com"));
8611 TestDelegate d;
8612
8613 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8614 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8615 r->set_top_frame_origin(top_frame_origin);
8616
8617 r->Start();
8618 d.RunUntilComplete();
8619
8620 EXPECT_EQ(2U, r->url_chain().size());
8621 EXPECT_EQ(OK, d.request_status());
8622 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
8623}
8624
8625TEST_F(URLRequestTestHTTP, RedirectPreserveUnsetTopFrameOrigin) {
8626 ASSERT_TRUE(http_test_server()->Start());
8627
8628 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8629 TestDelegate d;
8630
8631 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8632 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8633 // Since we're not setting a top frame origin, we wouldn't expect one after
8634 // the redirect.
8635 r->Start();
8636 d.RunUntilComplete();
8637
8638 EXPECT_EQ(2U, r->url_chain().size());
8639 EXPECT_EQ(OK, d.request_status());
8640 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:598641}
8642
Josh Karlinf3caee1642018-12-10 22:54:278643TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameURL) {
8644 ASSERT_TRUE(http_test_server()->Start());
8645
8646 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8647 url::Origin top_frame_origin =
8648 url::Origin::Create(GURL("http://example.com"));
8649 TestDelegate d;
8650 {
8651 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8652 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8653 r->set_top_frame_origin(top_frame_origin);
8654
8655 r->Start();
8656 d.RunUntilComplete();
8657
8658 EXPECT_EQ(2U, r->url_chain().size());
8659 EXPECT_EQ(OK, d.request_status());
8660 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
8661 }
8662}
8663
[email protected]cba24642014-08-15 20:49:598664TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558665 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598666
tommycli59a63432015-11-06 00:10:558667 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598668 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558669 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598670
8671 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148672
Ryan Sleevib8449e02018-07-15 04:31:078673 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168674 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468675 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198676 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598677 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8678
[email protected]f7022f32014-08-21 16:32:198679 r->Start();
Wez2a31b222018-06-07 22:07:158680 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598681
[email protected]f7022f32014-08-21 16:32:198682 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508683 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468684 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
Josh Karlinbe37f912018-12-07 01:05:148685}
8686
8687TEST_F(URLRequestTestHTTP, RedirectUpdateTopFrameOrigin) {
8688 ASSERT_TRUE(http_test_server()->Start());
8689
8690 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8691 url::Origin original_top_frame_origin =
8692 url::Origin::Create(GURL("http://example.com"));
8693 url::Origin expected_top_frame_origin =
8694 url::Origin::Create(GURL(http_test_server()->GetURL("/echo")));
8695
8696 TestDelegate d;
8697
8698 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8699 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8700 r->set_top_frame_origin(original_top_frame_origin);
8701 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8702
8703 r->Start();
8704 d.RunUntilComplete();
8705
8706 EXPECT_EQ(2U, r->url_chain().size());
8707 EXPECT_EQ(OK, d.request_status());
8708 EXPECT_EQ(expected_top_frame_origin, *r->top_frame_origin());
8709}
8710
8711TEST_F(URLRequestTestHTTP, RedirectIgnoreUnsetTopFrameOrigin) {
8712 ASSERT_TRUE(http_test_server()->Start());
8713
8714 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8715 TestDelegate d;
8716
8717 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8718 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8719 // Since we're not setting a top frame origin, we wouldn't expect one after
8720 // the redirect.
8721 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8722
8723 r->Start();
8724 d.RunUntilComplete();
8725
8726 EXPECT_EQ(2U, r->url_chain().size());
8727 EXPECT_EQ(OK, d.request_status());
8728 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:598729}
8730
[email protected]316c1e5e2012-09-12 15:17:448731TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558732 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448733
8734 const char kData[] = "hello world";
8735
8736 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078737 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168738 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8739 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198740 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078741 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448742 HttpRequestHeaders headers;
8743 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:248744 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198745 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448746
danakj8522a25b2016-04-16 00:17:368747 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558748 req.get(), &default_network_delegate_,
8749 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428750 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8751 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448752
[email protected]f7022f32014-08-21 16:32:198753 req->Start();
Wez2a31b222018-06-07 22:07:158754 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198755 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:448756}
8757
8758TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:558759 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448760
8761 const char kData[] = "hello world";
8762
8763 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078764 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168765 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8766 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198767 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078768 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448769 HttpRequestHeaders headers;
8770 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:248771 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198772 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448773
danakj8522a25b2016-04-16 00:17:368774 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558775 req.get(), &default_network_delegate_,
8776 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:098777 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:428778 "Very Good Reason"));
8779 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448780
[email protected]f7022f32014-08-21 16:32:198781 req->Start();
Wez2a31b222018-06-07 22:07:158782 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198783 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:448784 EXPECT_EQ(kData, d.data_received());
8785}
8786
8787// Check that default A-L header is sent.
8788TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558789 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448790
[email protected]8790210c2013-12-02 05:29:538791 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:248792 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448793 TestURLRequestContext context(true);
8794 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:438795 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448796 context.Init();
8797
8798 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368799 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558800 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168801 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198802 req->Start();
Wez2a31b222018-06-07 22:07:158803 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448804 EXPECT_EQ("en", d.data_received());
8805}
8806
8807// Check that an empty A-L header is not sent. http://crbug.com/77365.
8808TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558809 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448810
[email protected]8790210c2013-12-02 05:29:538811 std::string empty_string; // Avoid most vexing parse on line below.
8812 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:248813 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448814 TestURLRequestContext context(true);
8815 context.set_network_delegate(&network_delegate);
8816 context.Init();
8817 // We override the language after initialization because empty entries
8818 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:438819 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448820
8821 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368822 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558823 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168824 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198825 req->Start();
Wez2a31b222018-06-07 22:07:158826 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448827 EXPECT_EQ("None", d.data_received());
8828}
8829
8830// Check that if request overrides the A-L header, the default is not appended.
8831// See http://crbug.com/20894
8832TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558833 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448834
8835 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078836 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558837 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168838 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448839 HttpRequestHeaders headers;
8840 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:198841 req->SetExtraRequestHeaders(headers);
8842 req->Start();
Wez2a31b222018-06-07 22:07:158843 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448844 EXPECT_EQ(std::string("ru"), d.data_received());
8845}
8846
8847// Check that default A-E header is sent.
8848TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558849 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448850
8851 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078852 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558853 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168854 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448855 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:198856 req->SetExtraRequestHeaders(headers);
8857 req->Start();
Wez2a31b222018-06-07 22:07:158858 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448859 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
8860}
8861
8862// Check that if request overrides the A-E header, the default is not appended.
8863// See http://crbug.com/47381
8864TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558865 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448866
8867 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078868 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558869 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168870 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448871 HttpRequestHeaders headers;
8872 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:198873 req->SetExtraRequestHeaders(headers);
8874 req->Start();
Wez2a31b222018-06-07 22:07:158875 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448876 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
8877 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
8878}
8879
[email protected]84f05432013-03-15 01:00:128880// Check that setting the A-C header sends the proper header.
8881TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:558882 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448883
8884 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078885 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558886 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:168887 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448888 HttpRequestHeaders headers;
8889 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:198890 req->SetExtraRequestHeaders(headers);
8891 req->Start();
Wez2a31b222018-06-07 22:07:158892 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448893 EXPECT_EQ(std::string("koi-8r"), d.data_received());
8894}
8895
8896// Check that default User-Agent header is sent.
8897TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:558898 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448899
8900 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078901 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558902 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168903 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198904 req->Start();
Wez2a31b222018-06-07 22:07:158905 d.RunUntilComplete();
Ryan Sleevib8449e02018-07-15 04:31:078906 EXPECT_EQ(default_context().http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:378907 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448908}
8909
8910// Check that if request overrides the User-Agent header,
8911// the default is not appended.
marqf14fff8d2015-12-02 15:52:298912// TODO(crbug.com/564656) This test is flaky on iOS.
8913#if defined(OS_IOS)
8914#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
8915#else
8916#define MAYBE_OverrideUserAgent OverrideUserAgent
8917#endif
8918TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:558919 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448920
8921 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078922 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558923 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168924 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448925 HttpRequestHeaders headers;
8926 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:198927 req->SetExtraRequestHeaders(headers);
8928 req->Start();
Wez2a31b222018-06-07 22:07:158929 d.RunUntilComplete();
[email protected]cd6f2522014-01-16 18:27:358930 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448931}
8932
[email protected]ee4c30d2012-11-07 15:08:438933// Check that a NULL HttpUserAgentSettings causes the corresponding empty
8934// User-Agent header to be sent but does not send the Accept-Language and
8935// Accept-Charset headers.
8936TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:558937 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:438938
[email protected]ceefd7fd2012-11-29 00:36:248939 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:438940 TestURLRequestContext context(true);
8941 context.set_network_delegate(&network_delegate);
8942 context.Init();
8943 // We override the HttpUserAgentSettings after initialization because empty
8944 // entries get overridden by Init().
Raul Tambre94493c652019-03-11 17:18:358945 context.set_http_user_agent_settings(nullptr);
[email protected]ee4c30d2012-11-07 15:08:438946
8947 struct {
8948 const char* request;
8949 const char* expected_response;
tommycli59a63432015-11-06 00:10:558950 } tests[] = {{"/echoheader?Accept-Language", "None"},
8951 {"/echoheader?Accept-Charset", "None"},
8952 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:438953
Avi Drissman4365a4782018-12-28 19:26:248954 for (size_t i = 0; i < base::size(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:438955 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368956 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168957 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
8958 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198959 req->Start();
Wez2a31b222018-06-07 22:07:158960 d.RunUntilComplete();
[email protected]ee4c30d2012-11-07 15:08:438961 EXPECT_EQ(tests[i].expected_response, d.data_received())
8962 << " Request = \"" << tests[i].request << "\"";
8963 }
8964}
8965
[email protected]5033ab82013-03-22 20:17:468966// Make sure that URLRequest passes on its priority updates to
8967// newly-created jobs after the first one.
8968TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:558969 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:468970
8971 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078972 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168973 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8974 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198975 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:468976
danakj8522a25b2016-04-16 00:17:368977 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558978 req.get(), &default_network_delegate_,
8979 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428980 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8981 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:468982
[email protected]f7022f32014-08-21 16:32:198983 req->SetPriority(LOW);
8984 req->Start();
8985 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:468986
mmenkeed0498b2015-12-08 23:20:428987 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:368988 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:428989 req.get(), &default_network_delegate_, &job_priority));
8990 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:468991
8992 // Should trigger |job| to be started.
Wez2a31b222018-06-07 22:07:158993 d.RunUntilComplete();
mmenkeed0498b2015-12-08 23:20:428994 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:468995}
8996
[email protected]80abdad2014-03-15 00:20:548997// Check that creating a network request while entering/exiting suspend mode
8998// fails as it should. This is the only case where an HttpTransactionFactory
8999// does not return an HttpTransaction.
9000TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
9001 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:369002 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
Ryan Sleevib8449e02018-07-15 04:31:079003 default_context().http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:549004 network_layer->OnSuspend();
9005
dchengc7eeda422015-12-26 03:56:489006 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:039007 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:279008 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:549009
9010 TestURLRequestContext context(true);
9011 context.set_http_transaction_factory(&http_cache);
9012 context.Init();
9013
9014 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369015 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169016 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9017 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199018 req->Start();
Wez2a31b222018-06-07 22:07:159019 d.RunUntilComplete();
[email protected]80abdad2014-03-15 00:20:549020
9021 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:509022 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:549023}
9024
mmenke2281f3762015-11-02 20:38:179025namespace {
[email protected]80abdad2014-03-15 00:20:549026
mmenke2281f3762015-11-02 20:38:179027// HttpTransactionFactory that synchronously fails to create transactions.
9028class FailingHttpTransactionFactory : public HttpTransactionFactory {
9029 public:
9030 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
9031 : network_session_(network_session) {}
9032
Chris Watkins7a41d3552017-12-01 02:13:279033 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:179034
9035 // HttpTransactionFactory methods:
9036 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:369037 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:179038 return ERR_FAILED;
9039 }
9040
9041 HttpCache* GetCache() override { return nullptr; }
9042
9043 HttpNetworkSession* GetSession() override { return network_session_; }
9044
9045 private:
9046 HttpNetworkSession* network_session_;
9047
9048 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
9049};
9050
9051} // namespace
9052
9053// Check that when a request that fails to create an HttpTransaction can be
9054// cancelled while the failure notification is pending, and doesn't send two
9055// failure notifications.
9056//
9057// This currently only happens when in suspend mode and there's no cache, but
9058// just use a special HttpTransactionFactory, to avoid depending on those
9059// behaviors.
9060TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
9061 FailingHttpTransactionFactory http_transaction_factory(
Ryan Sleevib8449e02018-07-15 04:31:079062 default_context().http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:549063 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:179064 context.set_http_transaction_factory(&http_transaction_factory);
9065 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:549066 context.Init();
9067
9068 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369069 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169070 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9071 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:179072 // Don't send cookies (Collecting cookies is asynchronous, and need request to
9073 // try to create an HttpNetworkTransaction synchronously on start).
9074 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:199075 req->Start();
mmenke2281f3762015-11-02 20:38:179076 req->Cancel();
Wez2a31b222018-06-07 22:07:159077 d.RunUntilComplete();
mmenke2281f3762015-11-02 20:38:179078 // Run pending error task, if there is one.
9079 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:549080
9081 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:179082 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509083 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:179084
9085 // NetworkDelegate should see the cancellation, but not the error.
9086 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
9087 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:549088}
9089
ttuttlec0c828492015-05-15 01:25:559090TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:559091 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559092
9093 TestDelegate d;
tommycli59a63432015-11-06 00:10:559094 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079095 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169096 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559097
9098 req->Start();
Wez2a31b222018-06-07 22:07:159099 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559100
9101 EXPECT_TRUE(req->response_info().network_accessed);
9102}
9103
9104TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:559105 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559106
9107 // Populate the cache.
9108 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079109 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169110 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9111 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559112 req->Start();
Wez2a31b222018-06-07 22:07:159113 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559114
maksim.sisovb53724b52016-09-16 05:30:509115 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559116 EXPECT_TRUE(req->response_info().network_accessed);
9117 EXPECT_FALSE(req->response_info().was_cached);
9118
Ryan Sleevib8449e02018-07-15 04:31:079119 req = default_context().CreateRequest(
9120 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9121 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:559122 req->Start();
Wez2a31b222018-06-07 22:07:159123 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559124
maksim.sisovb53724b52016-09-16 05:30:509125 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559126 EXPECT_FALSE(req->response_info().network_accessed);
9127 EXPECT_TRUE(req->response_info().was_cached);
9128}
9129
9130TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:559131 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559132
9133 TestDelegate d;
tommycli59a63432015-11-06 00:10:559134 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079135 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169136 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:339137 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:559138
9139 req->Start();
Wez2a31b222018-06-07 22:07:159140 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559141
9142 EXPECT_FALSE(req->response_info().network_accessed);
9143}
9144
rdsmithbf8c3c12016-11-18 18:16:249145// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:089146// correctly in the absence of contention.
9147TEST_F(URLRequestTestHTTP, ThrottledPriority) {
9148 ASSERT_TRUE(http_test_server()->Start());
9149
9150 TestDelegate d;
9151 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079152 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169153 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:089154 req->Start();
Wez2a31b222018-06-07 22:07:159155 d.RunUntilComplete();
rdsmith5eb6fbc2016-10-21 17:36:089156
9157 EXPECT_TRUE(req->status().is_success());
9158}
9159
ricea3a1c71f2016-06-17 10:05:269160TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
9161 ASSERT_TRUE(http_test_server()->Start());
9162
9163 TestDelegate d;
9164 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169165 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9166 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269167 req->Start();
Wez2a31b222018-06-07 22:07:159168 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269169
9170 EXPECT_EQ(5, req->GetRawBodyBytes());
9171}
9172
9173TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
9174 ASSERT_TRUE(http_test_server()->Start());
9175
9176 TestDelegate d;
9177 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169178 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
9179 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269180 req->Start();
Wez2a31b222018-06-07 22:07:159181 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269182
9183 EXPECT_EQ(30, req->GetRawBodyBytes());
9184}
9185
jamd3f5a3c2016-10-27 18:52:029186// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
9187// the delegate isn't called back synchronously.
9188TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
9189 ASSERT_TRUE(http_test_server()->Start());
9190 default_network_delegate_.set_before_start_transaction_fails();
9191
9192 TestDelegate d;
9193 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169194 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
9195 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:029196 req->Start();
9197 DCHECK(!d.response_completed());
Wez2a31b222018-06-07 22:07:159198 d.RunUntilComplete();
jamd3f5a3c2016-10-27 18:52:029199 DCHECK(d.response_completed());
9200 EXPECT_EQ(ERR_FAILED, d.request_status());
9201}
9202
bengr1bf8e942014-11-07 01:36:509203class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9204 public:
9205 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9206 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9207 // tests into the factory tests.
Raul Tambre94493c652019-03-11 17:18:359208 URLRequestInterceptorTestHTTP()
9209 : URLRequestTestHTTP(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:509210
9211 void SetUpFactory() override {
9212 interceptor_ = new MockURLRequestInterceptor();
9213 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369214 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509215 }
9216
9217 MockURLRequestInterceptor* interceptor() const {
9218 return interceptor_;
9219 }
9220
9221 private:
9222 MockURLRequestInterceptor* interceptor_;
9223};
9224
9225TEST_F(URLRequestInterceptorTestHTTP,
9226 NetworkDelegateNotificationOnRedirectIntercept) {
9227 interceptor()->set_intercept_redirect(true);
9228 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9229 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9230
tommycli59a63432015-11-06 00:10:559231 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509232
9233 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369234 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169235 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9236 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509237 req->Start();
Wez2a31b222018-06-07 22:07:159238 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509239
9240 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9241 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509242 int status = d.request_status();
9243 EXPECT_EQ(OK, status);
9244 if (status == OK)
bengr1bf8e942014-11-07 01:36:509245 EXPECT_EQ(200, req->response_headers()->response_code());
9246
9247 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9248 EXPECT_EQ(1, d.response_started_count());
9249 EXPECT_EQ(0, d.received_redirect_count());
9250
9251 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009252 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509253 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9254}
9255
9256TEST_F(URLRequestInterceptorTestHTTP,
9257 NetworkDelegateNotificationOnErrorIntercept) {
9258 // Intercept that error and respond with an OK response.
9259 interceptor()->set_intercept_final_response(true);
9260 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9261 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9262 default_network_delegate()->set_can_be_intercepted_on_error(true);
9263
tommycli59a63432015-11-06 00:10:559264 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509265
9266 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369267 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559268 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169269 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509270 req->set_method("GET");
9271 req->Start();
Wez2a31b222018-06-07 22:07:159272 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509273
9274 EXPECT_TRUE(interceptor()->did_intercept_final());
9275
9276 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509277 int status = d.request_status();
9278 EXPECT_EQ(OK, status);
9279 if (status == OK)
bengr1bf8e942014-11-07 01:36:509280 EXPECT_EQ(200, req->response_headers()->response_code());
9281 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9282 EXPECT_EQ(1, d.response_started_count());
9283 EXPECT_EQ(0, d.received_redirect_count());
9284
9285 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009286 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509287 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9288}
9289
9290TEST_F(URLRequestInterceptorTestHTTP,
9291 NetworkDelegateNotificationOnResponseIntercept) {
9292 // Intercept that error and respond with an OK response.
9293 interceptor()->set_intercept_final_response(true);
9294
9295 // Intercept with a real URLRequestHttpJob.
9296 interceptor()->set_use_url_request_http_job(true);
9297
tommycli59a63432015-11-06 00:10:559298 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509299
9300 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369301 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169302 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9303 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509304 req->set_method("GET");
9305 req->Start();
Wez2a31b222018-06-07 22:07:159306 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509307
9308 EXPECT_TRUE(interceptor()->did_intercept_final());
9309
9310 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509311 int status = d.request_status();
9312 EXPECT_EQ(OK, status);
9313 if (status == OK)
bengr1bf8e942014-11-07 01:36:509314 EXPECT_EQ(200, req->response_headers()->response_code());
9315 EXPECT_EQ("hello", d.data_received());
9316 EXPECT_EQ(1, d.response_started_count());
9317 EXPECT_EQ(0, d.received_redirect_count());
9318
9319 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009320 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509321 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9322}
9323
mkwst0c5eab872014-11-21 14:18:549324class URLRequestTestReferrerPolicy : public URLRequestTest {
9325 public:
Chris Watkins7a41d3552017-12-01 02:13:279326 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:549327
tommycli59a63432015-11-06 00:10:559328 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9329 origin_server_.reset(new EmbeddedTestServer(type));
9330 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9331 origin_server_->AddDefaultHandlers(
9332 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9333 } else {
9334 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9335 }
mkwst0c5eab872014-11-21 14:18:549336 ASSERT_TRUE(origin_server_->Start());
9337 }
9338
tommycli59a63432015-11-06 00:10:559339 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9340 net::EmbeddedTestServer::Type dest_type) {
9341 origin_server_.reset(new EmbeddedTestServer(origin_type));
9342 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9343 origin_server_->AddDefaultHandlers(
9344 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9345 } else {
9346 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9347 }
mkwst0c5eab872014-11-21 14:18:549348 ASSERT_TRUE(origin_server_->Start());
9349
tommycli59a63432015-11-06 00:10:559350 destination_server_.reset(new EmbeddedTestServer(dest_type));
9351 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9352 destination_server_->AddDefaultHandlers(
9353 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9354 } else {
9355 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9356 }
mkwst0c5eab872014-11-21 14:18:549357 ASSERT_TRUE(destination_server_->Start());
9358 }
9359
9360 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9361 const GURL& referrer,
9362 const GURL& expected) {
9363 // Create and execute the request: we'll only have a |destination_server_|
9364 // if the origins are meant to be distinct. Otherwise, we'll use the
9365 // |origin_server_| for both endpoints.
9366 GURL destination_url =
tommycli59a63432015-11-06 00:10:559367 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9368 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549369 GURL origin_url =
tommycli59a63432015-11-06 00:10:559370 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549371
9372 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079373 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169374 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549375 req->set_referrer_policy(policy);
9376 req->SetReferrer(referrer.spec());
9377 req->Start();
Wez2a31b222018-06-07 22:07:159378 d.RunUntilComplete();
mkwst0c5eab872014-11-21 14:18:549379
9380 EXPECT_EQ(1, d.response_started_count());
9381 EXPECT_EQ(1, d.received_redirect_count());
9382 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509383 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549384 EXPECT_EQ(200, req->response_headers()->response_code());
9385
9386 EXPECT_EQ(expected.spec(), req->referrer());
9387 if (expected.is_empty())
9388 EXPECT_EQ("None", d.data_received());
9389 else
9390 EXPECT_EQ(expected.spec(), d.data_received());
9391 }
9392
tommycli59a63432015-11-06 00:10:559393 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549394
9395 private:
danakj8522a25b2016-04-16 00:17:369396 std::unique_ptr<EmbeddedTestServer> origin_server_;
9397 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549398};
9399
9400TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559401 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549402
estarkc8ccba82017-06-13 22:37:409403 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549404 VerifyReferrerAfterRedirect(
9405 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409406 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549407
9408 VerifyReferrerAfterRedirect(
9409 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409410 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549411
9412 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409413 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549414
estarkc8ccba82017-06-13 22:37:409415 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9416 referrer);
9417
9418 // The original referrer set on the request is expected to obey the referrer
9419 // policy and already be stripped to the origin; thus this test case just
9420 // checks that this policy doesn't cause the referrer to change when following
9421 // a redirect.
9422 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9423 referrer.GetOrigin());
9424
9425 VerifyReferrerAfterRedirect(
9426 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9427 referrer);
9428
9429 // The original referrer set on the request is expected to obey the referrer
9430 // policy and already be stripped to the origin; thus this test case just
9431 // checks that this policy doesn't cause the referrer to change when following
9432 // a redirect.
9433 VerifyReferrerAfterRedirect(
9434 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9435 referrer.GetOrigin(), referrer.GetOrigin());
9436
9437 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549438}
9439
tommycli59a63432015-11-06 00:10:559440TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9441 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9442 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409443 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549444
9445 VerifyReferrerAfterRedirect(
9446 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409447 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549448
9449 VerifyReferrerAfterRedirect(
9450 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409451 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549452
9453 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409454 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9455 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549456
estarkc8ccba82017-06-13 22:37:409457 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9458 referrer);
9459
9460 // The original referrer set on the request is expected to obey the referrer
9461 // policy and already be stripped to the origin; thus this test case just
9462 // checks that this policy doesn't cause the referrer to change when following
9463 // a redirect.
9464 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9465 referrer.GetOrigin());
9466
9467 VerifyReferrerAfterRedirect(
9468 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9469
9470 // The original referrer set on the request is expected to obey the referrer
9471 // policy and already be stripped to the origin; thus this test case just
9472 // checks that this policy doesn't cause the referrer to change when following
9473 // a redirect.
9474 VerifyReferrerAfterRedirect(
9475 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9476 referrer.GetOrigin(), referrer.GetOrigin());
9477
9478 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549479}
9480
9481TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559482 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409483 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549484
9485 VerifyReferrerAfterRedirect(
9486 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409487 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549488
9489 VerifyReferrerAfterRedirect(
9490 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409491 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549492
9493 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409494 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549495
estarkc8ccba82017-06-13 22:37:409496 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9497 referrer);
9498
9499 // The original referrer set on the request is expected to obey the referrer
9500 // policy and already be stripped to the origin; thus this test case just
9501 // checks that this policy doesn't cause the referrer to change when following
9502 // a redirect.
9503 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9504 referrer.GetOrigin());
9505
9506 VerifyReferrerAfterRedirect(
9507 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9508 referrer);
9509
9510 // The original referrer set on the request is expected to obey the referrer
9511 // policy and already be stripped to the origin; thus this test case just
9512 // checks that this policy doesn't cause the referrer to change when following
9513 // a redirect.
9514 VerifyReferrerAfterRedirect(
9515 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9516 referrer.GetOrigin(), referrer.GetOrigin());
9517
9518 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549519}
9520
tommycli59a63432015-11-06 00:10:559521TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
9522 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9523 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409524 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549525
9526 VerifyReferrerAfterRedirect(
9527 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409528 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549529
9530 VerifyReferrerAfterRedirect(
9531 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409532 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549533
9534 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409535 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559536 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549537
estarkc8ccba82017-06-13 22:37:409538 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9539 referrer);
9540
9541 // The original referrer set on the request is expected to obey the referrer
9542 // policy and already be stripped to the origin; thus this test case just
9543 // checks that this policy doesn't cause the referrer to change when following
9544 // a redirect.
9545 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9546 referrer.GetOrigin());
9547
9548 VerifyReferrerAfterRedirect(
9549 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9550
9551 // The original referrer set on the request is expected to obey the referrer
9552 // policy and already be stripped to the origin; thus this test case just
9553 // checks that this policy doesn't cause the referrer to change when following
9554 // a redirect.
9555 VerifyReferrerAfterRedirect(
9556 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9557 referrer.GetOrigin(), referrer.GetOrigin());
9558
9559 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549560}
9561
tommycli59a63432015-11-06 00:10:559562TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
9563 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9564 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409565 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549566
9567 VerifyReferrerAfterRedirect(
9568 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409569 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549570
9571 VerifyReferrerAfterRedirect(
9572 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409573 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549574
9575 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409576 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559577 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549578
estarkc8ccba82017-06-13 22:37:409579 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9580 referrer);
9581
9582 // The original referrer set on the request is expected to obey the referrer
9583 // policy and already be stripped to the origin; thus this test case just
9584 // checks that this policy doesn't cause the referrer to change when following
9585 // a redirect.
9586 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9587 referrer.GetOrigin());
9588
9589 VerifyReferrerAfterRedirect(
9590 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9591
9592 // The original referrer set on the request is expected to obey the referrer
9593 // policy and already be stripped to the origin; thus this test case just
9594 // checks that this policy doesn't cause the referrer to change when following
9595 // a redirect.
9596 VerifyReferrerAfterRedirect(
9597 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9598 referrer.GetOrigin(), referrer.GetOrigin());
9599
9600 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549601}
9602
tommycli59a63432015-11-06 00:10:559603TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
9604 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9605 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409606 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549607
9608 VerifyReferrerAfterRedirect(
9609 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409610 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549611
9612 VerifyReferrerAfterRedirect(
9613 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409614 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549615
9616 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409617 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559618 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549619
estarkc8ccba82017-06-13 22:37:409620 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9621 referrer);
9622
9623 // The original referrer set on the request is expected to obey the referrer
9624 // policy and already be stripped to the origin; thus this test case just
9625 // checks that this policy doesn't cause the referrer to change when following
9626 // a redirect.
9627 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9628 referrer.GetOrigin());
9629
9630 VerifyReferrerAfterRedirect(
9631 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9632
9633 // The original referrer set on the request is expected to obey the referrer
9634 // policy and already be stripped to the origin, though it should be
9635 // subsequently cleared during the downgrading redirect.
9636 VerifyReferrerAfterRedirect(
9637 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9638 referrer.GetOrigin(), GURL());
9639
9640 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549641}
9642
Bence Béky98447b12018-05-08 03:14:019643class HTTPSRequestTest : public TestWithScopedTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:509644 public:
fdorayf33fede2017-05-11 21:18:109645 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:099646 default_context_.set_network_delegate(&default_network_delegate_);
9647 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:509648 }
Martijn Croonenb1383da2017-10-11 11:56:359649 ~HTTPSRequestTest() override {
9650 SetTransportSecurityStateSourceForTesting(nullptr);
9651 }
[email protected]87a09a92011-07-14 15:50:509652
9653 protected:
[email protected]ceefd7fd2012-11-29 00:36:249654 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:099655 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:469656};
9657
[email protected]c044616e2013-02-20 02:01:269658TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:559659 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9660 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229661 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119662 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469663
[email protected]ea224582008-12-07 20:25:469664 TestDelegate d;
9665 {
danakj8522a25b2016-04-16 00:17:369666 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169667 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9668 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199669 r->Start();
9670 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469671
Wez2a31b222018-06-07 22:07:159672 d.RunUntilComplete();
[email protected]ea224582008-12-07 20:25:469673
9674 EXPECT_EQ(1, d.response_started_count());
9675 EXPECT_FALSE(d.received_data_before_response());
9676 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199677 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199678 EXPECT_EQ(test_server.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:379679 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
[email protected]6d81b482011-02-22 19:47:199680 EXPECT_EQ(test_server.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:379681 r->GetResponseRemoteEndpoint().port());
[email protected]ea224582008-12-07 20:25:469682 }
[email protected]ea224582008-12-07 20:25:469683}
9684
[email protected]5774ada2010-07-15 06:30:549685TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559686 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9687 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9688 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229689 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119690 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339691
9692 bool err_allowed = true;
9693 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9694 TestDelegate d;
9695 {
9696 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369697 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169698 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9699 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339700
[email protected]f7022f32014-08-21 16:32:199701 r->Start();
9702 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339703
Wez2a31b222018-06-07 22:07:159704 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339705
9706 EXPECT_EQ(1, d.response_started_count());
9707 EXPECT_FALSE(d.received_data_before_response());
9708 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179709 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339710 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199711 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179712 } else {
[email protected]bacff652009-03-31 17:50:339713 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179714 }
[email protected]bacff652009-03-31 17:50:339715 }
9716 }
9717}
9718
[email protected]5774ada2010-07-15 06:30:549719TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559720 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9721 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9722 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229723 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119724 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339725
9726 // Iterate from false to true, just so that we do the opposite of the
9727 // previous test in order to increase test coverage.
9728 bool err_allowed = false;
9729 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9730 TestDelegate d;
9731 {
9732 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369733 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169734 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9735 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339736
[email protected]f7022f32014-08-21 16:32:199737 r->Start();
9738 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339739
Wez2a31b222018-06-07 22:07:159740 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339741
9742 EXPECT_EQ(1, d.response_started_count());
9743 EXPECT_FALSE(d.received_data_before_response());
9744 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179745 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339746 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199747 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179748 } else {
[email protected]bacff652009-03-31 17:50:339749 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179750 }
[email protected]bacff652009-03-31 17:50:339751 }
9752 }
9753}
[email protected]73e0bba2009-02-19 22:57:099754
tommycli59a63432015-11-06 00:10:559755// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
9756// security state. (see http://crbug.com/550977).
9757#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:359758// This tests that a load of a domain with preloaded HSTS and HPKP with a
9759// certificate error sets the |certificate_errors_are_fatal| flag correctly.
9760// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:449761TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359762 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9763
tommycli59a63432015-11-06 00:10:559764 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9765 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9766 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449767 ASSERT_TRUE(test_server.Start());
9768
Martijn Croonenb1383da2017-10-11 11:56:359769 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9770 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9771 // means that we have to use a MockHostResolver in order to direct
9772 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9773 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449774
9775 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249776 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449777 TestURLRequestContext context(true);
9778 context.set_network_delegate(&network_delegate);
9779 context.set_host_resolver(&host_resolver);
9780 TransportSecurityState transport_security_state;
9781 context.set_transport_security_state(&transport_security_state);
9782 context.Init();
9783
9784 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369785 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359786 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369787 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169788 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449789
[email protected]f7022f32014-08-21 16:32:199790 r->Start();
9791 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449792
Wez2a31b222018-06-07 22:07:159793 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449794
9795 EXPECT_EQ(1, d.response_started_count());
9796 EXPECT_FALSE(d.received_data_before_response());
9797 EXPECT_TRUE(d.have_certificate_errors());
9798 EXPECT_TRUE(d.certificate_errors_are_fatal());
9799}
9800
9801// This tests that cached HTTPS page loads do not cause any updates to the
9802// TransportSecurityState.
9803TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359804 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9805
[email protected]316c1e5e2012-09-12 15:17:449806 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
9807 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:559808 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9809 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9810 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449811 ASSERT_TRUE(test_server.Start());
9812
Martijn Croonenb1383da2017-10-11 11:56:359813 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9814 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9815 // means that we have to use a MockHostResolver in order to direct
9816 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9817 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449818
9819 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249820 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449821 TestURLRequestContext context(true);
9822 context.set_network_delegate(&network_delegate);
9823 context.set_host_resolver(&host_resolver);
9824 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:269825
martijnc0d6b622015-06-30 19:14:409826 TransportSecurityState::STSState static_sts_state;
9827 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269828 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359829 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:449830 context.set_transport_security_state(&transport_security_state);
9831 context.Init();
9832
martijnc0d6b622015-06-30 19:14:409833 TransportSecurityState::STSState dynamic_sts_state;
9834 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:359835 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
9836 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
9837 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
9838 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269839
[email protected]316c1e5e2012-09-12 15:17:449840 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369841 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359842 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369843 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169844 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449845
[email protected]f7022f32014-08-21 16:32:199846 r->Start();
9847 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449848
Wez2a31b222018-06-07 22:07:159849 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449850
9851 EXPECT_EQ(1, d.response_started_count());
9852 EXPECT_FALSE(d.received_data_before_response());
9853 EXPECT_TRUE(d.have_certificate_errors());
9854 EXPECT_TRUE(d.certificate_errors_are_fatal());
9855
[email protected]9e6968d2014-05-07 21:46:269856 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:409857 TransportSecurityState::STSState new_static_sts_state;
9858 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269859 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359860 "hsts-hpkp-preloaded.test", &new_static_sts_state,
9861 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:409862 TransportSecurityState::STSState new_dynamic_sts_state;
9863 TransportSecurityState::PKPState new_dynamic_pkp_state;
9864 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:359865 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:409866 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:359867 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269868
martijnc0d6b622015-06-30 19:14:409869 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
9870 EXPECT_EQ(new_static_sts_state.include_subdomains,
9871 static_sts_state.include_subdomains);
9872 EXPECT_EQ(new_static_pkp_state.include_subdomains,
9873 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:489874 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
9875 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
9876 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:449877}
9878
[email protected]8ccc69f2012-11-28 19:52:149879// Make sure HSTS preserves a POST request's method and body.
9880TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
9881 static const char kData[] = "hello world";
9882
tommycli59a63432015-11-06 00:10:559883 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9884 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229885 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:149886 ASSERT_TRUE(test_server.Start());
9887
9888
9889 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9890 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:559891 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:229892 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:149893 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:149894
9895 // Force https for www.somewhere.com.
9896 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:209897 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
9898 bool include_subdomains = false;
9899 transport_security_state.AddHSTS("www.somewhere.com", expiry,
9900 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:149901
9902 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9903
9904 TestURLRequestContext context(true);
9905 context.set_host_resolver(&host_resolver);
9906 context.set_transport_security_state(&transport_security_state);
9907 context.set_network_delegate(&network_delegate);
9908 context.Init();
9909
9910 TestDelegate d;
9911 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
9912 // cause a certificate error. Ignore the error.
9913 d.set_allow_certificate_errors(true);
9914
danakj8522a25b2016-04-16 00:17:369915 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199916 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:369917 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169918 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199919 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079920 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:149921
[email protected]f7022f32014-08-21 16:32:199922 req->Start();
Wez2a31b222018-06-07 22:07:159923 d.RunUntilComplete();
[email protected]8ccc69f2012-11-28 19:52:149924
[email protected]f7022f32014-08-21 16:32:199925 EXPECT_EQ("https", req->url().scheme());
9926 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:149927 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:409928
9929 LoadTimingInfo load_timing_info;
9930 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
9931 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
9932 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:149933}
9934
rob4e0be1f2014-09-11 23:40:229935// Make sure that the CORS headers are added to cross-origin HSTS redirects.
9936TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
9937 static const char kOriginHeaderValue[] = "http://www.example.com";
9938
tommycli59a63432015-11-06 00:10:559939 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9940 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:229941 ASSERT_TRUE(test_server.Start());
9942
9943 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9944 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:559945 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
9946 // default.
rob4e0be1f2014-09-11 23:40:229947 MockHostResolver host_resolver;
9948
9949 TransportSecurityState transport_security_state;
9950 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
9951 bool include_subdomains = false;
9952 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
9953
9954 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9955
9956 MockCertVerifier cert_verifier;
9957 cert_verifier.set_default_result(OK);
9958
9959 TestURLRequestContext context(true);
9960 context.set_host_resolver(&host_resolver);
9961 context.set_transport_security_state(&transport_security_state);
9962 context.set_network_delegate(&network_delegate);
9963 context.set_cert_verifier(&cert_verifier);
9964 context.Init();
9965
9966 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
9967 test_server.host_port_pair().port()));
9968 url::Replacements<char> replacements;
9969 const char kNewScheme[] = "https";
9970 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
9971 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
9972
9973 TestDelegate d;
rob4e0be1f2014-09-11 23:40:229974
rhalavatib7bd7c792017-04-27 05:25:169975 std::unique_ptr<URLRequest> req(context.CreateRequest(
9976 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:229977 // Set Origin header to simulate a cross-origin request.
9978 HttpRequestHeaders request_headers;
9979 request_headers.SetHeader("Origin", kOriginHeaderValue);
9980 req->SetExtraRequestHeaders(request_headers);
9981
9982 req->Start();
Wez0e717112018-06-18 23:09:229983 d.RunUntilRedirect();
rob4e0be1f2014-09-11 23:40:229984
9985 EXPECT_EQ(1, d.received_redirect_count());
9986
9987 const HttpResponseHeaders* headers = req->response_headers();
9988 std::string redirect_location;
Raul Tambre94493c652019-03-11 17:18:359989 EXPECT_TRUE(
9990 headers->EnumerateHeader(nullptr, "Location", &redirect_location));
rob4e0be1f2014-09-11 23:40:229991 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
9992
9993 std::string received_cors_header;
Raul Tambre94493c652019-03-11 17:18:359994 EXPECT_TRUE(headers->EnumerateHeader(nullptr, "Access-Control-Allow-Origin",
rob4e0be1f2014-09-11 23:40:229995 &received_cors_header));
9996 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
9997}
9998
[email protected]316c1e5e2012-09-12 15:17:449999namespace {
10000
10001class SSLClientAuthTestDelegate : public TestDelegate {
10002 public:
10003 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
Wez0e717112018-06-18 23:09:2210004 set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:4410005 }
dchengb03027d2014-10-21 12:00:2010006 void OnCertificateRequested(URLRequest* request,
10007 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:4410008 on_certificate_requested_count_++;
Wez0e717112018-06-18 23:09:2210009 std::move(on_certificate_requested_).Run();
10010 }
10011 void RunUntilCertificateRequested() {
10012 base::RunLoop run_loop;
10013 on_certificate_requested_ = run_loop.QuitClosure();
10014 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:4410015 }
10016 int on_certificate_requested_count() {
10017 return on_certificate_requested_count_;
10018 }
10019 private:
10020 int on_certificate_requested_count_;
Wez0e717112018-06-18 23:09:2210021 base::OnceClosure on_certificate_requested_;
[email protected]316c1e5e2012-09-12 15:17:4410022};
10023
David Benjamin76a40ad2018-02-24 22:22:0810024class TestSSLPrivateKey : public SSLPrivateKey {
10025 public:
10026 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
10027 : key_(std::move(key)) {}
10028
10029 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
10030 int sign_count() const { return sign_count_; }
10031
David Benjaminb65b0732018-11-09 20:33:5310032 std::string GetProviderName() override { return key_->GetProviderName(); }
David Benjamin76a40ad2018-02-24 22:22:0810033 std::vector<uint16_t> GetAlgorithmPreferences() override {
10034 return key_->GetAlgorithmPreferences();
10035 }
10036 void Sign(uint16_t algorithm,
10037 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:2610038 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:0810039 sign_count_++;
10040 if (fail_signing_) {
10041 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:2610042 FROM_HERE, base::BindOnce(std::move(callback),
10043 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
10044 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:0810045 } else {
David Benjamin8f2d2c12018-02-27 00:08:2610046 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:0810047 }
10048 }
10049
10050 private:
10051 ~TestSSLPrivateKey() override = default;
10052
10053 scoped_refptr<SSLPrivateKey> key_;
10054 bool fail_signing_ = false;
10055 int sign_count_ = 0;
10056};
10057
[email protected]316c1e5e2012-09-12 15:17:4410058} // namespace
10059
10060// TODO(davidben): Test the rest of the code. Specifically,
10061// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:4410062// - Getting a certificate request in an SSL renegotiation sending the
10063// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:0810064TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:5510065 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10066 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:1210067 ssl_config.client_cert_type =
10068 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:0810069 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:5510070 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210071 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410072 ASSERT_TRUE(test_server.Start());
10073
10074 SSLClientAuthTestDelegate d;
10075 {
danakj8522a25b2016-04-16 00:17:3610076 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610077 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10078 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410079
[email protected]f7022f32014-08-21 16:32:1910080 r->Start();
10081 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410082
Wez0e717112018-06-18 23:09:2210083 d.RunUntilCertificateRequested();
10084 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410085
10086 EXPECT_EQ(1, d.on_certificate_requested_count());
10087 EXPECT_FALSE(d.received_data_before_response());
10088 EXPECT_EQ(0, d.bytes_received());
10089
10090 // Send no certificate.
10091 // TODO(davidben): Get temporary client cert import (with keys) working on
10092 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:5410093 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:4410094
Wez2a31b222018-06-07 22:07:1510095 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410096
David Benjamin76a40ad2018-02-24 22:22:0810097 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:4410098 EXPECT_EQ(1, d.response_started_count());
10099 EXPECT_FALSE(d.received_data_before_response());
10100 EXPECT_NE(0, d.bytes_received());
10101 }
10102}
10103
David Benjamin76a40ad2018-02-24 22:22:0810104TEST_F(HTTPSRequestTest, ClientAuth) {
10105 std::unique_ptr<FakeClientCertIdentity> identity =
10106 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10107 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10108 ASSERT_TRUE(identity);
10109 scoped_refptr<TestSSLPrivateKey> private_key =
10110 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10111
10112 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10113 net::SSLServerConfig ssl_config;
10114 ssl_config.client_cert_type =
10115 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10116 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10117 test_server.AddDefaultHandlers(
10118 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10119 ASSERT_TRUE(test_server.Start());
10120
10121 {
10122 SSLClientAuthTestDelegate d;
10123 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10124 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10125 TRAFFIC_ANNOTATION_FOR_TESTS));
10126
10127 r->Start();
10128 EXPECT_TRUE(r->is_pending());
10129
Wez0e717112018-06-18 23:09:2210130 d.RunUntilCertificateRequested();
10131 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810132
10133 EXPECT_EQ(1, d.on_certificate_requested_count());
10134 EXPECT_FALSE(d.received_data_before_response());
10135 EXPECT_EQ(0, d.bytes_received());
10136
10137 // Send a certificate.
10138 r->ContinueWithCertificate(identity->certificate(), private_key);
10139
Wez2a31b222018-06-07 22:07:1510140 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810141
10142 EXPECT_EQ(OK, d.request_status());
10143 EXPECT_EQ(1, d.response_started_count());
10144 EXPECT_FALSE(d.received_data_before_response());
10145 EXPECT_NE(0, d.bytes_received());
10146
10147 // The private key should have been used.
10148 EXPECT_EQ(1, private_key->sign_count());
10149 }
10150
10151 // Close all connections and clear the session cache to force a new handshake.
10152 default_context_.http_transaction_factory()
10153 ->GetSession()
10154 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710155 default_context_.http_transaction_factory()
10156 ->GetSession()
10157 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810158
10159 // Connecting again should not call OnCertificateRequested. The identity is
10160 // taken from the client auth cache.
10161 {
10162 SSLClientAuthTestDelegate d;
10163 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10164 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10165 TRAFFIC_ANNOTATION_FOR_TESTS));
10166
10167 r->Start();
10168 EXPECT_TRUE(r->is_pending());
10169
Wez2a31b222018-06-07 22:07:1510170 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810171
10172 EXPECT_EQ(OK, d.request_status());
10173 EXPECT_EQ(0, d.on_certificate_requested_count());
10174 EXPECT_FALSE(d.received_data_before_response());
10175 EXPECT_EQ(1, d.response_started_count());
10176 EXPECT_FALSE(d.received_data_before_response());
10177 EXPECT_NE(0, d.bytes_received());
10178
10179 // The private key should have been used.
10180 EXPECT_EQ(2, private_key->sign_count());
10181 }
10182}
10183
10184// Test that private keys that fail to sign anything get evicted from the cache.
10185TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
10186 std::unique_ptr<FakeClientCertIdentity> identity =
10187 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10188 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10189 ASSERT_TRUE(identity);
10190 scoped_refptr<TestSSLPrivateKey> private_key =
10191 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10192 private_key->set_fail_signing(true);
10193
10194 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10195 net::SSLServerConfig ssl_config;
10196 ssl_config.client_cert_type =
10197 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10198 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10199 test_server.AddDefaultHandlers(
10200 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10201 ASSERT_TRUE(test_server.Start());
10202
10203 {
10204 SSLClientAuthTestDelegate d;
10205 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10206 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10207 TRAFFIC_ANNOTATION_FOR_TESTS));
10208
10209 r->Start();
10210 EXPECT_TRUE(r->is_pending());
Wez0e717112018-06-18 23:09:2210211
10212 d.RunUntilCertificateRequested();
10213 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810214
10215 EXPECT_EQ(1, d.on_certificate_requested_count());
10216 EXPECT_FALSE(d.received_data_before_response());
10217 EXPECT_EQ(0, d.bytes_received());
10218
10219 // Send a certificate.
10220 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510221 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810222
10223 // The private key cannot sign anything, so we report an error.
10224 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
10225 EXPECT_EQ(1, d.response_started_count());
10226 EXPECT_FALSE(d.received_data_before_response());
10227 EXPECT_EQ(0, d.bytes_received());
10228
10229 // The private key should have been used.
10230 EXPECT_EQ(1, private_key->sign_count());
10231 }
10232
10233 // Close all connections and clear the session cache to force a new handshake.
10234 default_context_.http_transaction_factory()
10235 ->GetSession()
10236 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710237 default_context_.http_transaction_factory()
10238 ->GetSession()
10239 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810240
10241 // The bad identity should have been evicted from the cache, so connecting
10242 // again should call OnCertificateRequested again.
10243 {
10244 SSLClientAuthTestDelegate d;
10245 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10246 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10247 TRAFFIC_ANNOTATION_FOR_TESTS));
10248
10249 r->Start();
10250 EXPECT_TRUE(r->is_pending());
10251
Wez0e717112018-06-18 23:09:2210252 d.RunUntilCertificateRequested();
10253 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810254
10255 EXPECT_EQ(1, d.on_certificate_requested_count());
10256 EXPECT_FALSE(d.received_data_before_response());
10257 EXPECT_EQ(0, d.bytes_received());
10258
10259 // There should have been no additional uses of the private key.
10260 EXPECT_EQ(1, private_key->sign_count());
10261 }
10262}
10263
10264// Test that cached private keys that fail to sign anything trigger a
10265// retry. This is so we handle unplugged smartcards
10266// gracefully. https://crbug.com/813022.
10267TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
10268 std::unique_ptr<FakeClientCertIdentity> identity =
10269 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10270 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10271 ASSERT_TRUE(identity);
10272 scoped_refptr<TestSSLPrivateKey> private_key =
10273 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10274
10275 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10276 net::SSLServerConfig ssl_config;
10277 ssl_config.client_cert_type =
10278 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10279 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10280 test_server.AddDefaultHandlers(
10281 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10282 ASSERT_TRUE(test_server.Start());
10283
10284 // Connect with a client certificate to put it in the client auth cache.
10285 {
10286 SSLClientAuthTestDelegate d;
10287 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10288 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10289 TRAFFIC_ANNOTATION_FOR_TESTS));
10290
10291 r->Start();
10292 EXPECT_TRUE(r->is_pending());
10293
Wez0e717112018-06-18 23:09:2210294 d.RunUntilCertificateRequested();
10295 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810296
10297 EXPECT_EQ(1, d.on_certificate_requested_count());
10298 EXPECT_FALSE(d.received_data_before_response());
10299 EXPECT_EQ(0, d.bytes_received());
10300
10301 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510302 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810303
10304 EXPECT_EQ(OK, d.request_status());
10305 EXPECT_EQ(1, d.response_started_count());
10306 EXPECT_FALSE(d.received_data_before_response());
10307 EXPECT_NE(0, d.bytes_received());
10308
10309 // The private key should have been used.
10310 EXPECT_EQ(1, private_key->sign_count());
10311 }
10312
10313 // Close all connections and clear the session cache to force a new handshake.
10314 default_context_.http_transaction_factory()
10315 ->GetSession()
10316 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710317 default_context_.http_transaction_factory()
10318 ->GetSession()
10319 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810320
10321 // Cause the private key to fail. Connecting again should attempt to use it,
10322 // notice the failure, and then request a new identity via
10323 // OnCertificateRequested.
10324 private_key->set_fail_signing(true);
10325
10326 {
10327 SSLClientAuthTestDelegate d;
10328 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10329 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10330 TRAFFIC_ANNOTATION_FOR_TESTS));
10331
10332 r->Start();
10333 EXPECT_TRUE(r->is_pending());
10334
Wez0e717112018-06-18 23:09:2210335 d.RunUntilCertificateRequested();
10336 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810337
10338 // There was an additional signing call on the private key (the one which
10339 // failed).
10340 EXPECT_EQ(2, private_key->sign_count());
10341
10342 // That caused another OnCertificateRequested call.
10343 EXPECT_EQ(1, d.on_certificate_requested_count());
10344 EXPECT_FALSE(d.received_data_before_response());
10345 EXPECT_EQ(0, d.bytes_received());
10346 }
10347}
10348
[email protected]316c1e5e2012-09-12 15:17:4410349TEST_F(HTTPSRequestTest, ResumeTest) {
10350 // Test that we attempt a session resume when making two connections to the
10351 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:2210352 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410353 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210354 SpawnedTestServer test_server(
10355 SpawnedTestServer::TYPE_HTTPS,
10356 ssl_options,
10357 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410358 ASSERT_TRUE(test_server.Start());
10359
Daniel McArdle3a663d62019-01-31 00:48:4710360 default_context_.http_transaction_factory()
10361 ->GetSession()
10362 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4410363
10364 {
10365 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610366 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610367 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10368 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410369
[email protected]f7022f32014-08-21 16:32:1910370 r->Start();
10371 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410372
Wez2a31b222018-06-07 22:07:1510373 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410374
10375 EXPECT_EQ(1, d.response_started_count());
10376 }
10377
10378 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10379 CloseAllConnections();
10380
10381 {
10382 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610383 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610384 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10385 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410386
[email protected]f7022f32014-08-21 16:32:1910387 r->Start();
10388 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410389
Wez2a31b222018-06-07 22:07:1510390 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410391
10392 // The response will look like;
Steven Valdez0ef94d02018-11-19 23:28:1310393 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]316c1e5e2012-09-12 15:17:4410394 // insert abc
10395 // lookup abc
10396 // insert xyz
10397 //
10398 // With a newline at the end which makes the split think that there are
10399 // four lines.
10400
10401 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2910402 std::vector<std::string> lines = base::SplitString(
10403 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Steven Valdez0ef94d02018-11-19 23:28:1310404 ASSERT_EQ(5u, lines.size()) << d.data_received();
[email protected]316c1e5e2012-09-12 15:17:4410405
10406 std::string session_id;
10407
Steven Valdez0ef94d02018-11-19 23:28:1310408 for (size_t i = 0; i < 3; i++) {
brettw3a2c6902015-07-06 19:43:2910409 std::vector<std::string> parts = base::SplitString(
10410 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410411 ASSERT_EQ(2u, parts.size());
Steven Valdez0ef94d02018-11-19 23:28:1310412 if (i % 2 == 1) {
[email protected]316c1e5e2012-09-12 15:17:4410413 EXPECT_EQ("insert", parts[0]);
10414 session_id = parts[1];
10415 } else {
10416 EXPECT_EQ("lookup", parts[0]);
Steven Valdez0ef94d02018-11-19 23:28:1310417 if (i != 0)
10418 EXPECT_EQ(session_id, parts[1]);
[email protected]316c1e5e2012-09-12 15:17:4410419 }
10420 }
10421 }
10422}
10423
10424TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
10425 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
10426 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2210427 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410428 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210429 SpawnedTestServer test_server(
10430 SpawnedTestServer::TYPE_HTTPS,
10431 ssl_options,
10432 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410433 ASSERT_TRUE(test_server.Start());
10434
Daniel McArdle3a663d62019-01-31 00:48:4710435 default_context_.http_transaction_factory()
10436 ->GetSession()
10437 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4410438
10439 {
10440 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610441 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0410442 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1610443 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410444
[email protected]f7022f32014-08-21 16:32:1910445 r->Start();
10446 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410447
Wez2a31b222018-06-07 22:07:1510448 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410449
10450 EXPECT_EQ(1, d.response_started_count());
10451 }
10452
10453 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4110454 HttpNetworkSession::Context session_context;
10455 session_context.host_resolver = default_context_.host_resolver();
10456 session_context.cert_verifier = default_context_.cert_verifier();
10457 session_context.transport_security_state =
10458 default_context_.transport_security_state();
10459 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2010460 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4110461 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5910462 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4110463 session_context.ssl_config_service = default_context_.ssl_config_service();
10464 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4410465 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4110466 session_context.http_server_properties =
10467 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4410468
mmenke6ddfbea2017-05-31 21:48:4110469 HttpNetworkSession network_session(HttpNetworkSession::Params(),
10470 session_context);
zhongyi4928bd52017-02-08 02:16:2710471 std::unique_ptr<HttpCache> cache(
10472 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
10473 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4410474
10475 default_context_.set_http_transaction_factory(cache.get());
10476
10477 {
10478 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610479 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610480 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10481 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410482
[email protected]f7022f32014-08-21 16:32:1910483 r->Start();
10484 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410485
Wez2a31b222018-06-07 22:07:1510486 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410487
[email protected]316c1e5e2012-09-12 15:17:4410488 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0410489 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]316c1e5e2012-09-12 15:17:4410490 }
10491}
10492
Daniel McArdleda3fa942019-02-15 16:41:2110493// Test that sessions started with privacy mode enabled cannot be resumed when
10494// it is disabled, and vice versa.
10495TEST_F(HTTPSRequestTest, NoSessionResumptionBetweenPrivacyModes) {
10496 // Start a server.
10497 SpawnedTestServer test_server(
10498 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(),
10499 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10500 ASSERT_TRUE(test_server.Start());
10501 const auto url = test_server.GetURL("/");
10502
10503 auto ConnectAndCheckHandshake = [this, url](bool allow_credentials,
10504 auto expected_handshake) {
10505 // Construct request and indirectly set the privacy mode.
10506 TestDelegate d;
10507 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10508 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
10509 r->set_allow_credentials(allow_credentials);
10510
10511 // Start the request and check the SSL handshake type.
10512 r->Start();
10513 EXPECT_TRUE(r->is_pending());
10514 d.RunUntilComplete();
10515 EXPECT_EQ(1, d.response_started_count());
10516 EXPECT_EQ(expected_handshake, r->ssl_info().handshake_type);
10517 };
10518
10519 // Exhaustively check all pairs of privacy mode values. Note that we are using
10520 // allow_credentials to indirectly enable/disable privacy mode.
10521 const bool kAllowCredentialsValues[] = {false, true};
10522 for (const auto allow_creds_1 : kAllowCredentialsValues) {
10523 for (const auto allow_creds_2 : kAllowCredentialsValues) {
10524 SCOPED_TRACE(base::StringPrintf("allow_creds_1=%d, allow_creds_2=%d",
10525 allow_creds_1, allow_creds_2));
10526
10527 // The session cache starts off empty, so we expect a full handshake.
10528 ConnectAndCheckHandshake(allow_creds_1, SSLInfo::HANDSHAKE_FULL);
10529
10530 // The second handshake depends on whether we are using the same session
10531 // cache as the first request.
10532 ConnectAndCheckHandshake(allow_creds_2, allow_creds_1 == allow_creds_2
10533 ? SSLInfo::HANDSHAKE_RESUME
10534 : SSLInfo::HANDSHAKE_FULL);
10535 // Flush both session caches.
10536 auto* network_session =
10537 default_context_.http_transaction_factory()->GetSession();
10538 network_session->ClearSSLSessionCache();
10539 }
10540 }
10541}
10542
Bence Béky98447b12018-05-08 03:14:0110543class HTTPSFallbackTest : public TestWithScopedTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:5510544 public:
fdorayf33fede2017-05-11 21:18:1010545 HTTPSFallbackTest() : context_(true) {
Nick Harper2243e8002018-09-28 20:33:2610546 ssl_config_service_ = std::make_unique<TestSSLConfigService>();
davidben095ebb52017-04-12 22:23:3410547 context_.set_ssl_config_service(ssl_config_service_.get());
10548 }
Chris Watkins7a41d3552017-12-01 02:13:2710549 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5510550
10551 protected:
davidben095ebb52017-04-12 22:23:3410552 TestSSLConfigService* ssl_config_service() {
10553 return ssl_config_service_.get();
10554 }
10555
[email protected]48d2b7c52014-06-27 01:16:5510556 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
10557 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0010558 context_.Init();
10559 delegate_.set_allow_certificate_errors(true);
10560
[email protected]48d2b7c52014-06-27 01:16:5510561 SpawnedTestServer test_server(
10562 SpawnedTestServer::TYPE_HTTPS,
10563 ssl_options,
10564 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10565 ASSERT_TRUE(test_server.Start());
10566
tommycli59a63432015-11-06 00:10:5510567 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1610568 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5510569 request_->Start();
10570
Wez2a31b222018-06-07 22:07:1510571 delegate_.RunUntilComplete();
[email protected]48d2b7c52014-06-27 01:16:5510572 }
10573
davidben095ebb52017-04-12 22:23:3410574 void ExpectConnection(int version) {
10575 EXPECT_EQ(1, delegate_.response_started_count());
10576 EXPECT_NE(0, delegate_.bytes_received());
10577 EXPECT_EQ(version, SSLConnectionStatusToVersion(
10578 request_->ssl_info().connection_status));
10579 }
10580
[email protected]48d2b7c52014-06-27 01:16:5510581 void ExpectFailure(int error) {
10582 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5010583 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5510584 }
10585
10586 private:
Ryan Sleevib8449e02018-07-15 04:31:0710587 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5510588 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4710589 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610590 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:5510591};
10592
davidbenb127ca82015-06-15 19:05:4210593// Tests the TLS 1.0 fallback doesn't happen.
10594TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5510595 SpawnedTestServer::SSLOptions ssl_options(
10596 SpawnedTestServer::SSLOptions::CERT_OK);
10597 ssl_options.tls_intolerant =
10598 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
10599
10600 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5510601 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4210602}
10603
davidben5a312152016-06-27 22:11:4710604// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5510605TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4210606 SpawnedTestServer::SSLOptions ssl_options(
10607 SpawnedTestServer::SSLOptions::CERT_OK);
10608 ssl_options.tls_intolerant =
10609 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
10610
10611 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5510612 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
10613}
10614
davidben095ebb52017-04-12 22:23:3410615// Tests that TLS 1.3 interference results in a dedicated error code.
10616TEST_F(HTTPSFallbackTest, TLSv1_3Interference) {
10617 SpawnedTestServer::SSLOptions ssl_options(
10618 SpawnedTestServer::SSLOptions::CERT_OK);
10619 ssl_options.tls_intolerant =
10620 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10621 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
10622
10623 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10624 ExpectFailure(ERR_SSL_VERSION_INTERFERENCE);
10625}
10626
10627// Tests that disabling TLS 1.3 leaves TLS 1.3 interference unnoticed.
10628TEST_F(HTTPSFallbackTest, TLSv1_3InterferenceDisableVersion) {
10629 SpawnedTestServer::SSLOptions ssl_options(
10630 SpawnedTestServer::SSLOptions::CERT_OK);
10631 ssl_options.tls_intolerant =
10632 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10633 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_2);
10634
10635 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10636 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_2);
10637}
10638
Bence Béky98447b12018-05-08 03:14:0110639class HTTPSSessionTest : public TestWithScopedTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:2410640 public:
fdorayf33fede2017-05-11 21:18:1010641 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5910642 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410643
10644 default_context_.set_network_delegate(&default_network_delegate_);
10645 default_context_.set_cert_verifier(&cert_verifier_);
10646 default_context_.Init();
10647 }
Chris Watkins7a41d3552017-12-01 02:13:2710648 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2410649
10650 protected:
10651 MockCertVerifier cert_verifier_;
10652 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
10653 TestURLRequestContext default_context_;
10654};
10655
10656// Tests that session resumption is not attempted if an invalid certificate
10657// is presented.
10658TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
10659 SpawnedTestServer::SSLOptions ssl_options;
10660 ssl_options.record_resume = true;
10661 SpawnedTestServer test_server(
10662 SpawnedTestServer::TYPE_HTTPS,
10663 ssl_options,
10664 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10665 ASSERT_TRUE(test_server.Start());
10666
Daniel McArdle3a663d62019-01-31 00:48:4710667 default_context_.http_transaction_factory()
10668 ->GetSession()
10669 ->ClearSSLSessionCache();
[email protected]a8fed1742013-12-27 02:14:2410670
10671 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5910672 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2410673 {
10674 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610675 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0410676 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1610677 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410678
[email protected]f7022f32014-08-21 16:32:1910679 r->Start();
10680 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410681
Wez2a31b222018-06-07 22:07:1510682 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410683
10684 EXPECT_EQ(1, d.response_started_count());
10685 }
10686
10687 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10688 CloseAllConnections();
10689
10690 // Now change the certificate to be acceptable (so that the response is
10691 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910692 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410693 {
10694 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610695 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610696 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10697 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410698
[email protected]f7022f32014-08-21 16:32:1910699 r->Start();
10700 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410701
Wez2a31b222018-06-07 22:07:1510702 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410703
[email protected]a8fed1742013-12-27 02:14:2410704 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0410705 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]a8fed1742013-12-27 02:14:2410706 }
10707}
10708
[email protected]dffe8242012-03-20 15:14:2710709// This the fingerprint of the "Testing CA" certificate used by the testserver.
10710// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5810711static const SHA256HashValue kOCSPTestCertFingerprint = {{
10712 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
10713 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
10714 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1510715}};
[email protected]dffe8242012-03-20 15:14:2710716
[email protected]51523f52013-07-31 21:57:2810717// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
10718// testserver.
mattm0b12a6f2016-11-29 19:57:1610719static const SHA256HashValue kOCSPTestCertSPKI = {{
10720 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
10721 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
10722 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
10723}};
[email protected]51523f52013-07-31 21:57:2810724
[email protected]dffe8242012-03-20 15:14:2710725// This is the policy OID contained in the certificates that testserver
10726// generates.
10727static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
10728
10729class HTTPSOCSPTest : public HTTPSRequestTest {
10730 public:
10731 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0910732 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0810733 ev_test_policy_(
10734 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
10735 kOCSPTestCertFingerprint,
10736 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0210737 }
10738
dcheng67be2b1f2014-10-27 21:47:2910739 void SetUp() override {
Ryan Sleevi8a9c9c12018-05-09 02:36:2310740 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
[email protected]ef2bf422012-05-11 03:27:0910741 context_.Init();
[email protected]dffe8242012-03-20 15:14:2710742
Ryan Sleevi24fe2682018-08-16 21:33:4610743 context_.cert_verifier()->SetConfig(GetCertVerifierConfig());
10744
[email protected]cba24642014-08-15 20:49:5910745 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2010746 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
Raul Tambre94493c652019-03-11 17:18:3510747 CHECK_NE(static_cast<X509Certificate*>(nullptr), root_cert.get());
[email protected]90499482013-06-01 00:39:5010748 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2710749
Matt Muellerfb271992018-01-30 18:10:4810750#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510751 SetGlobalCertNetFetcherForTesting(net::CreateCertNetFetcher(&context_));
10752#endif
10753
svaldez2135be52016-04-20 16:34:5310754#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0910755 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2710756#endif
10757 }
10758
dadrian612337a2016-07-20 22:36:5810759 void DoConnectionWithDelegate(
10760 const SpawnedTestServer::SSLOptions& ssl_options,
10761 TestDelegate* delegate,
10762 SSLInfo* out_ssl_info) {
10763 // Always overwrite |out_ssl_info|.
10764 out_ssl_info->Reset();
10765
[email protected]ce7d0cbc2013-05-03 18:57:2210766 SpawnedTestServer test_server(
10767 SpawnedTestServer::TYPE_HTTPS,
10768 ssl_options,
10769 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2710770 ASSERT_TRUE(test_server.Start());
10771
dadrian612337a2016-07-20 22:36:5810772 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1610773 std::unique_ptr<URLRequest> r(
10774 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
10775 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910776 r->Start();
[email protected]dffe8242012-03-20 15:14:2710777
Wez2a31b222018-06-07 22:07:1510778 delegate->RunUntilComplete();
dadrian612337a2016-07-20 22:36:5810779 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2710780
dadrian612337a2016-07-20 22:36:5810781 *out_ssl_info = r->ssl_info();
10782 }
10783
10784 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
10785 CertStatus* out_cert_status) {
10786 // Always overwrite |out_cert_status|.
10787 *out_cert_status = 0;
10788
10789 TestDelegate d;
10790 SSLInfo ssl_info;
10791 ASSERT_NO_FATAL_FAILURE(
10792 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
10793
10794 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2710795 }
10796
dcheng67be2b1f2014-10-27 21:47:2910797 ~HTTPSOCSPTest() override {
Matt Muellerfb271992018-01-30 18:10:4810798#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510799 ShutdownGlobalCertNetFetcher();
10800#endif
10801
svaldez2135be52016-04-20 16:34:5310802#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1810803 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2710804#endif
10805 }
10806
[email protected]a13234c2012-03-20 21:45:0210807 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4610808 // GetCertVerifierConfig() configures the URLRequestContext that will be used
10809 // for making connections to the testserver. This can be overridden in test
10810 // subclasses for different behaviour.
10811 virtual CertVerifier::Config GetCertVerifierConfig() {
10812 CertVerifier::Config config;
10813 config.enable_rev_checking = true;
10814 return config;
[email protected]a13234c2012-03-20 21:45:0210815 }
10816
danakj8522a25b2016-04-16 00:17:3610817 std::unique_ptr<ScopedTestRoot> test_root_;
Ryan Sleevib8449e02018-07-15 04:31:0710818 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]ef2bf422012-05-11 03:27:0910819 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610820 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2710821};
10822
[email protected]a13234c2012-03-20 21:45:0210823static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2010824#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0210825 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
10826 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0410827 // TODO(eroman): Should this also be the return value for
10828 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0210829 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
10830#else
10831 return 0;
10832#endif
10833}
10834
[email protected]3a86a712013-07-30 07:16:2010835// SystemSupportsHardFailRevocationChecking returns true iff the current
10836// operating system supports revocation checking and can distinguish between
10837// situations where a given certificate lacks any revocation information (eg:
10838// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
10839// revocation information cannot be obtained (eg: the CRL was unreachable).
10840// If it does not, then tests which rely on 'hard fail' behaviour should be
10841// skipped.
10842static bool SystemSupportsHardFailRevocationChecking() {
Eric Roman1b628daa2017-10-19 19:52:0410843#if defined(OS_WIN) || defined(USE_NSS_CERTS) || \
10844 defined(USE_BUILTIN_CERT_VERIFIER)
[email protected]3a86a712013-07-30 07:16:2010845 return true;
10846#else
10847 return false;
10848#endif
10849}
10850
[email protected]a13234c2012-03-20 21:45:0210851// SystemUsesChromiumEVMetadata returns true iff the current operating system
10852// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
10853// several tests are effected because our testing EV certificate won't be
10854// recognised as EV.
10855static bool SystemUsesChromiumEVMetadata() {
Eric Roman5f8d9d22017-10-17 02:32:5210856#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0110857 return true;
Eric Roman5f8d9d22017-10-17 02:32:5210858#else
10859 return false;
[email protected]05454a432012-03-20 20:04:0110860#endif
10861}
10862
mattmaf868e72016-09-23 23:25:2010863// Returns the expected CertStatus for tests that expect an online revocation
10864// check failure as a result of checking a test EV cert, which will not
10865// actually trigger an online revocation check on some platforms.
10866static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
10867 if (SystemUsesChromiumEVMetadata()) {
10868 return ExpectedCertStatusForFailedOnlineRevocationCheck();
10869 } else {
10870 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
10871 // be enabled, and thus there will not be a revocation check to fail.
10872 return 0u;
10873 }
10874}
10875
[email protected]b6f2de32012-08-17 04:35:0810876static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3910877#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0210878 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
10879 return false;
10880#else
10881 return true;
10882#endif
10883}
10884
davidbend1fb2f12014-11-08 02:51:0010885static bool SystemSupportsOCSPStapling() {
Eric Roman1b628daa2017-10-19 19:52:0410886#if defined(USE_NSS_CERTS) || defined(OS_WIN) || \
10887 defined(USE_BUILTIN_CERT_VERIFIER)
mathpc992e602015-10-21 20:34:0310888 return true;
mathpc992e602015-10-21 20:34:0310889#else
10890 return false;
10891#endif
davidbend1fb2f12014-11-08 02:51:0010892}
10893
[email protected]dffe8242012-03-20 15:14:2710894TEST_F(HTTPSOCSPTest, Valid) {
10895 if (!SystemSupportsOCSP()) {
10896 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10897 return;
10898 }
10899
[email protected]ce7d0cbc2013-05-03 18:57:2210900 SpawnedTestServer::SSLOptions ssl_options(
10901 SpawnedTestServer::SSLOptions::CERT_AUTO);
10902 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2710903
[email protected]924e9f92012-12-16 22:00:5310904 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210905 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710906
10907 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10908
[email protected]a13234c2012-03-20 21:45:0210909 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10910 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2710911
10912 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10913}
10914
10915TEST_F(HTTPSOCSPTest, Revoked) {
10916 if (!SystemSupportsOCSP()) {
10917 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10918 return;
10919 }
10920
[email protected]ce7d0cbc2013-05-03 18:57:2210921 SpawnedTestServer::SSLOptions ssl_options(
10922 SpawnedTestServer::SSLOptions::CERT_AUTO);
10923 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2710924
10925 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210926 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710927
[email protected]dffe8242012-03-20 15:14:2710928 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2710929 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10930 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10931}
10932
10933TEST_F(HTTPSOCSPTest, Invalid) {
10934 if (!SystemSupportsOCSP()) {
10935 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10936 return;
10937 }
10938
[email protected]ce7d0cbc2013-05-03 18:57:2210939 SpawnedTestServer::SSLOptions ssl_options(
10940 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810941 ssl_options.ocsp_status =
10942 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2710943
[email protected]924e9f92012-12-16 22:00:5310944 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210945 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710946
Eric Roman1b628daa2017-10-19 19:52:0410947#if defined(USE_BUILTIN_CERT_VERIFIER)
10948 // TODO(649017): This test uses soft-fail revocation checking, but returns an
10949 // invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
10950 // doesn't consider this a candidate for soft-fail (only considers
10951 // network-level failures as skippable).
10952 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
10953 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
10954#else
[email protected]a13234c2012-03-20 21:45:0210955 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2710956 cert_status & CERT_STATUS_ALL_ERRORS);
Eric Roman1b628daa2017-10-19 19:52:0410957#endif
[email protected]dffe8242012-03-20 15:14:2710958
10959 // Without a positive OCSP response, we shouldn't show the EV status.
10960 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10961 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10962}
[email protected]a13234c2012-03-20 21:45:0210963
Matt Mueller5339d862018-05-02 18:53:5710964TEST_F(HTTPSOCSPTest, IntermediateValid) {
10965 if (!SystemSupportsOCSP()) {
10966 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10967 return;
10968 }
10969
10970 SpawnedTestServer::SSLOptions ssl_options(
10971 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
10972 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10973 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10974
10975 CertStatus cert_status;
10976 DoConnection(ssl_options, &cert_status);
10977
10978 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10979
10980 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10981 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10982
10983 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10984}
10985
10986TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
10987 if (!SystemSupportsOCSP()) {
10988 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10989 return;
10990 }
10991
10992 SpawnedTestServer::SSLOptions ssl_options(
10993 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
10994 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10995 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10996 // Use an OCSP response for the intermediate that would be too old for a leaf
10997 // cert, but is still valid for an intermediate.
10998 ssl_options.ocsp_intermediate_date =
10999 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
11000
11001 CertStatus cert_status;
11002 DoConnection(ssl_options, &cert_status);
11003
11004 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11005
11006 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11007 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11008
11009 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11010}
11011
11012TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
11013 if (!SystemSupportsOCSP()) {
11014 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11015 return;
11016 }
11017
11018 SpawnedTestServer::SSLOptions ssl_options(
11019 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11020 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11021 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11022 ssl_options.ocsp_intermediate_date =
11023 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
11024
11025 CertStatus cert_status;
11026 DoConnection(ssl_options, &cert_status);
11027
11028#if defined(USE_BUILTIN_CERT_VERIFIER)
11029 // The builtin verifier enforces the baseline requirements for max age of an
11030 // intermediate's OCSP response.
11031 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11032 cert_status & CERT_STATUS_ALL_ERRORS);
11033 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11034#else
11035 // The platform verifiers are more lenient.
11036 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11037 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11038 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11039#endif
11040 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11041}
11042
11043TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
11044 if (!SystemSupportsOCSP()) {
11045 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11046 return;
11047 }
11048
11049 SpawnedTestServer::SSLOptions ssl_options(
11050 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11051 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11052 ssl_options.ocsp_intermediate_status =
11053 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11054
11055 CertStatus cert_status;
11056 DoConnection(ssl_options, &cert_status);
11057
11058#if defined(OS_WIN)
11059 // TODO(mattm): why does CertVerifyProcWin accept this?
11060 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11061#else
11062 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11063#endif
11064 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11065 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11066}
11067
davidbend1fb2f12014-11-08 02:51:0011068TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0311069 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011070 LOG(WARNING)
11071 << "Skipping test because system doesn't support OCSP stapling";
11072 return;
11073 }
11074
11075 SpawnedTestServer::SSLOptions ssl_options(
11076 SpawnedTestServer::SSLOptions::CERT_AUTO);
11077 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11078 ssl_options.staple_ocsp_response = true;
11079 ssl_options.ocsp_server_unavailable = true;
11080
11081 CertStatus cert_status;
11082 DoConnection(ssl_options, &cert_status);
11083
11084 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11085
11086 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11087 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11088
11089 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11090}
11091
davidben6c3191b2014-11-21 22:38:0411092// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4811093#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0411094#define MAYBE_RevokedStapled DISABLED_RevokedStapled
11095#else
11096#define MAYBE_RevokedStapled RevokedStapled
11097#endif
11098TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0311099 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011100 LOG(WARNING)
11101 << "Skipping test because system doesn't support OCSP stapling";
11102 return;
11103 }
11104
11105 SpawnedTestServer::SSLOptions ssl_options(
11106 SpawnedTestServer::SSLOptions::CERT_AUTO);
11107 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11108 ssl_options.staple_ocsp_response = true;
11109 ssl_options.ocsp_server_unavailable = true;
11110
11111 CertStatus cert_status;
11112 DoConnection(ssl_options, &cert_status);
11113
11114 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11115 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11116 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11117}
11118
dadrian612337a2016-07-20 22:36:5811119static const struct OCSPVerifyTestData {
11120 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
11121 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
11122 OCSPVerifyResult::ResponseStatus response_status;
11123 bool has_revocation_status;
11124 OCSPRevocationStatus cert_status;
11125} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3111126 // 0
dadrian612337a2016-07-20 22:36:5811127 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11128 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11129 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11130 OCSPVerifyResult::PROVIDED,
11131 true,
11132 OCSPRevocationStatus::GOOD},
11133
Eric Roman8673b812017-09-20 18:57:3111134 // 1
dadrian612337a2016-07-20 22:36:5811135 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11136 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11137 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11138 OCSPVerifyResult::INVALID_DATE,
11139 false,
11140 OCSPRevocationStatus::UNKNOWN},
11141
Eric Roman8673b812017-09-20 18:57:3111142 // 2
dadrian612337a2016-07-20 22:36:5811143 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11144 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11145 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11146 OCSPVerifyResult::INVALID_DATE,
11147 false,
11148 OCSPRevocationStatus::UNKNOWN},
11149
Eric Roman8673b812017-09-20 18:57:3111150 // 3
dadrian612337a2016-07-20 22:36:5811151 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11152 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11153 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11154 OCSPVerifyResult::INVALID_DATE,
11155 false,
11156 OCSPRevocationStatus::UNKNOWN},
11157
Eric Roman8673b812017-09-20 18:57:3111158 // 4
dadrian612337a2016-07-20 22:36:5811159 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11160 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11161 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11162 OCSPVerifyResult::INVALID_DATE,
11163 false,
11164 OCSPRevocationStatus::UNKNOWN},
11165
Eric Roman8673b812017-09-20 18:57:3111166 // 5
dadrian612337a2016-07-20 22:36:5811167 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
11168 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11169 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11170 OCSPVerifyResult::ERROR_RESPONSE,
11171 false,
11172 OCSPRevocationStatus::UNKNOWN},
11173
Eric Roman8673b812017-09-20 18:57:3111174 // 6
dadrian612337a2016-07-20 22:36:5811175 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
11176 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11177 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11178 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
11179 false,
11180 OCSPRevocationStatus::UNKNOWN},
11181
Eric Roman8673b812017-09-20 18:57:3111182 // 7
dadrian612337a2016-07-20 22:36:5811183 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
11184 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11185 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11186 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
11187 false,
11188 OCSPRevocationStatus::UNKNOWN},
11189
Eric Roman8673b812017-09-20 18:57:3111190 // 8
dadrian612337a2016-07-20 22:36:5811191 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11192 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11193 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11194 OCSPVerifyResult::INVALID_DATE,
11195 false,
11196 OCSPRevocationStatus::UNKNOWN},
11197
Eric Roman8673b812017-09-20 18:57:3111198 // 9
dadrian612337a2016-07-20 22:36:5811199 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11200 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11201 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11202 OCSPVerifyResult::PROVIDED,
11203 true,
11204 OCSPRevocationStatus::UNKNOWN},
11205
Eric Roman8673b812017-09-20 18:57:3111206 // 10
dadrian612337a2016-07-20 22:36:5811207 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11208 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11209 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11210 OCSPVerifyResult::INVALID_DATE,
11211 false,
11212 OCSPRevocationStatus::UNKNOWN},
11213
Eric Roman8673b812017-09-20 18:57:3111214 // 11
dadrian612337a2016-07-20 22:36:5811215 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11216 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11217 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11218 OCSPVerifyResult::INVALID_DATE,
11219 false,
11220 OCSPRevocationStatus::UNKNOWN},
11221
Eric Roman8673b812017-09-20 18:57:3111222 // 12
dadrian612337a2016-07-20 22:36:5811223 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11224 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11225 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
11226 OCSPVerifyResult::BAD_PRODUCED_AT,
11227 false,
11228 OCSPRevocationStatus::UNKNOWN},
11229
Eric Roman8673b812017-09-20 18:57:3111230 // 13
dadrian612337a2016-07-20 22:36:5811231 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11232 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11233 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11234 OCSPVerifyResult::BAD_PRODUCED_AT,
11235 false,
11236 OCSPRevocationStatus::UNKNOWN},
11237
Eric Roman8673b812017-09-20 18:57:3111238 // 14
dadrian612337a2016-07-20 22:36:5811239 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11240 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11241 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11242 OCSPVerifyResult::BAD_PRODUCED_AT,
11243 false,
11244 OCSPRevocationStatus::UNKNOWN},
11245
Eric Roman8673b812017-09-20 18:57:3111246 // 15
dadrian612337a2016-07-20 22:36:5811247 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11248 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11249 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11250 OCSPVerifyResult::PROVIDED,
11251 true,
11252 OCSPRevocationStatus::GOOD},
11253
Eric Roman8673b812017-09-20 18:57:3111254 // 16
dadrian612337a2016-07-20 22:36:5811255 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11256 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11257 {SpawnedTestServer::SSLOptions::OCSP_OK,
11258 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11259 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11260 OCSPVerifyResult::PROVIDED,
11261 true,
11262 OCSPRevocationStatus::GOOD},
11263
Eric Roman8673b812017-09-20 18:57:3111264 // 17
dadrian612337a2016-07-20 22:36:5811265 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11266 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11267 {SpawnedTestServer::SSLOptions::OCSP_OK,
11268 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11269 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11270 OCSPVerifyResult::PROVIDED,
11271 true,
11272 OCSPRevocationStatus::GOOD},
11273
Eric Roman8673b812017-09-20 18:57:3111274 // 18
dadrian612337a2016-07-20 22:36:5811275 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11276 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11277 {SpawnedTestServer::SSLOptions::OCSP_OK,
11278 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11279 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11280 OCSPVerifyResult::PROVIDED,
11281 true,
11282 OCSPRevocationStatus::GOOD},
11283
Eric Roman8673b812017-09-20 18:57:3111284 // 19
dadrian612337a2016-07-20 22:36:5811285 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11286 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11287 {SpawnedTestServer::SSLOptions::OCSP_OK,
11288 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11289 {SpawnedTestServer::SSLOptions::OCSP_OK,
11290 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11291 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11292 OCSPVerifyResult::INVALID_DATE,
11293 false,
11294 OCSPRevocationStatus::UNKNOWN},
11295
Eric Roman8673b812017-09-20 18:57:3111296 // 20
dadrian612337a2016-07-20 22:36:5811297 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11298 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11299 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11300 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11301 {SpawnedTestServer::SSLOptions::OCSP_OK,
11302 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11303 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11304 OCSPVerifyResult::PROVIDED,
11305 true,
11306 OCSPRevocationStatus::REVOKED},
11307
Eric Roman8673b812017-09-20 18:57:3111308 // 21
dadrian612337a2016-07-20 22:36:5811309 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11310 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11311 {SpawnedTestServer::SSLOptions::OCSP_OK,
11312 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11313 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11314 OCSPVerifyResult::PROVIDED,
11315 true,
11316 OCSPRevocationStatus::UNKNOWN},
11317
Eric Roman8673b812017-09-20 18:57:3111318 // 22
dadrian612337a2016-07-20 22:36:5811319 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11320 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11321 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11322 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11323 {SpawnedTestServer::SSLOptions::OCSP_OK,
11324 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11325 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11326 OCSPVerifyResult::PROVIDED,
11327 true,
11328 OCSPRevocationStatus::UNKNOWN},
11329
Eric Roman8673b812017-09-20 18:57:3111330 // 23
dadrian612337a2016-07-20 22:36:5811331 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11332 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11333 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11334 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11335 false,
11336 OCSPRevocationStatus::UNKNOWN},
11337
Eric Roman8673b812017-09-20 18:57:3111338 // 24
dadrian612337a2016-07-20 22:36:5811339 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11340 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11341 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11342 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11343 false,
11344 OCSPRevocationStatus::UNKNOWN},
11345
Eric Roman8673b812017-09-20 18:57:3111346// These tests fail when using NSS for certificate verification, as NSS fails
11347// and doesn't return the partial path. As a result the OCSP checks being done
11348// at the CertVerifyProc layer cannot access the issuer certificate.
11349#if !defined(USE_NSS_CERTS)
11350 // 25
11351 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11352 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11353 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11354 OCSPVerifyResult::PROVIDED,
11355 true,
11356 OCSPRevocationStatus::REVOKED},
11357
11358 // 26
11359 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11360 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11361 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11362 OCSPVerifyResult::INVALID_DATE,
11363 false,
11364 OCSPRevocationStatus::UNKNOWN},
11365
11366 // 27
11367 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11368 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11369 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11370 OCSPVerifyResult::INVALID_DATE,
11371 false,
11372 OCSPRevocationStatus::UNKNOWN},
11373#endif
dadrian612337a2016-07-20 22:36:5811374};
11375
11376class HTTPSOCSPVerifyTest
11377 : public HTTPSOCSPTest,
11378 public testing::WithParamInterface<OCSPVerifyTestData> {};
11379
11380TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
11381 SpawnedTestServer::SSLOptions ssl_options(
11382 SpawnedTestServer::SSLOptions::CERT_AUTO);
11383 OCSPVerifyTestData test = GetParam();
11384
11385 ssl_options.ocsp_responses = test.ocsp_responses;
11386 ssl_options.ocsp_produced = test.ocsp_produced;
11387 ssl_options.staple_ocsp_response = true;
11388
11389 SSLInfo ssl_info;
11390 OCSPErrorTestDelegate delegate;
11391 ASSERT_NO_FATAL_FAILURE(
11392 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
11393
11394 // The SSLInfo must be extracted from |delegate| on error, due to how
11395 // URLRequest caches certificate errors.
11396 if (delegate.have_certificate_errors()) {
11397 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
11398 ssl_info = delegate.ssl_info();
11399 }
11400
11401 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
11402
11403 if (test.has_revocation_status)
11404 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
11405}
11406
Victor Costan8fb98f6f2019-02-01 17:08:2911407INSTANTIATE_TEST_SUITE_P(OCSPVerify,
11408 HTTPSOCSPVerifyTest,
11409 testing::ValuesIn(kOCSPVerifyData));
dadrian612337a2016-07-20 22:36:5811410
mattm0b12a6f2016-11-29 19:57:1611411class HTTPSAIATest : public HTTPSOCSPTest {
11412 public:
Ryan Sleevi24fe2682018-08-16 21:33:4611413 CertVerifier::Config GetCertVerifierConfig() override {
11414 CertVerifier::Config config;
11415 return config;
mattm0b12a6f2016-11-29 19:57:1611416 }
11417};
11418
11419TEST_F(HTTPSAIATest, AIAFetching) {
11420 SpawnedTestServer::SSLOptions ssl_options(
11421 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
11422 SpawnedTestServer test_server(
11423 SpawnedTestServer::TYPE_HTTPS, ssl_options,
11424 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11425 ASSERT_TRUE(test_server.Start());
11426
Ryan Sleevi5b4702a2018-04-06 22:23:5611427 // Unmark the certificate's OID as EV, which will disable revocation
11428 // checking.
11429 ev_test_policy_.reset();
11430
mattm0b12a6f2016-11-29 19:57:1611431 TestDelegate d;
11432 d.set_allow_certificate_errors(true);
11433 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611434 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11435 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611436
11437 r->Start();
11438 EXPECT_TRUE(r->is_pending());
11439
Wez2a31b222018-06-07 22:07:1511440 d.RunUntilComplete();
mattm0b12a6f2016-11-29 19:57:1611441
11442 EXPECT_EQ(1, d.response_started_count());
11443
11444 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4811445 EXPECT_EQ(OK, d.request_status());
11446 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11447 ASSERT_TRUE(r->ssl_info().cert);
11448 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611449 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3411450 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611451}
11452
[email protected]3a86a712013-07-30 07:16:2011453class HTTPSHardFailTest : public HTTPSOCSPTest {
11454 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611455 CertVerifier::Config GetCertVerifierConfig() override {
11456 CertVerifier::Config config;
11457 config.require_rev_checking_local_anchors = true;
11458 return config;
[email protected]3a86a712013-07-30 07:16:2011459 }
11460};
11461
[email protected]3a86a712013-07-30 07:16:2011462TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
11463 if (!SystemSupportsOCSP()) {
11464 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11465 return;
11466 }
11467
11468 if (!SystemSupportsHardFailRevocationChecking()) {
11469 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
11470 << "revocation checking";
11471 return;
11472 }
11473
11474 SpawnedTestServer::SSLOptions ssl_options(
11475 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811476 ssl_options.ocsp_status =
11477 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2011478
11479 CertStatus cert_status;
11480 DoConnection(ssl_options, &cert_status);
11481
Eric Roman1b628daa2017-10-19 19:52:0411482#if defined(USE_BUILTIN_CERT_VERIFIER)
11483 // TODO(crbug.com/649017): Should we consider invalid response as
11484 // affirmatively revoked?
11485 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11486 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11487#else
11488 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
11489#endif
[email protected]3a86a712013-07-30 07:16:2011490
11491 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0411492 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2011493 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11494}
11495
[email protected]a13234c2012-03-20 21:45:0211496class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
11497 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611498 CertVerifier::Config GetCertVerifierConfig() override {
11499 CertVerifier::Config config;
11500 return config;
[email protected]a13234c2012-03-20 21:45:0211501 }
11502};
11503
11504TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
11505 if (!SystemSupportsOCSP()) {
11506 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11507 return;
11508 }
11509
[email protected]ce7d0cbc2013-05-03 18:57:2211510 SpawnedTestServer::SSLOptions ssl_options(
11511 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811512 ssl_options.ocsp_status =
11513 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211514
[email protected]924e9f92012-12-16 22:00:5311515 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211516 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211517
mattmaf868e72016-09-23 23:25:2011518 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211519 cert_status & CERT_STATUS_ALL_ERRORS);
11520
11521 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811522 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11523 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211524}
11525
[email protected]be0fff62013-08-29 23:37:4811526TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
11527 if (!SystemSupportsOCSP()) {
11528 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11529 return;
11530 }
11531
11532 SpawnedTestServer::SSLOptions ssl_options(
11533 SpawnedTestServer::SSLOptions::CERT_AUTO);
11534 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]be0fff62013-08-29 23:37:4811535
11536 CertStatus cert_status;
11537 DoConnection(ssl_options, &cert_status);
11538
mattm1a282f52016-11-10 21:49:4211539// Currently only works for Windows and OS X. When using NSS, it's not
11540// possible to determine whether the check failed because of actual
11541// revocation or because there was an OCSP failure.
11542#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4811543 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11544#else
11545 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11546#endif
11547
11548 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11549 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11550 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11551}
11552
[email protected]a13234c2012-03-20 21:45:0211553TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
11554 if (!SystemSupportsOCSP()) {
11555 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11556 return;
11557 }
11558
[email protected]ce7d0cbc2013-05-03 18:57:2211559 SpawnedTestServer::SSLOptions ssl_options(
11560 SpawnedTestServer::SSLOptions::CERT_AUTO);
11561 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0211562
11563 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211564 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211565
11566 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11567
11568 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11569 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0811570 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11571 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211572}
11573
11574TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
11575 if (!SystemSupportsOCSP()) {
11576 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11577 return;
11578 }
11579
[email protected]ce7d0cbc2013-05-03 18:57:2211580 SpawnedTestServer::SSLOptions ssl_options(
11581 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811582 ssl_options.ocsp_status =
11583 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211584 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11585 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11586 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211587
11588 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211589 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211590
mattmaf868e72016-09-23 23:25:2011591 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211592 cert_status & CERT_STATUS_ALL_ERRORS);
11593
11594 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811595 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11596 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211597}
11598
[email protected]51523f52013-07-31 21:57:2811599TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
11600 if (!SystemSupportsOCSP()) {
11601 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11602 return;
11603 }
11604
11605 SpawnedTestServer::SSLOptions ssl_options(
11606 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811607 ssl_options.ocsp_status =
11608 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211609 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11610 cert_verifier_config.crl_set =
11611 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {});
11612 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2811613
11614 CertStatus cert_status;
11615 DoConnection(ssl_options, &cert_status);
11616
11617 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
11618 // revocation check for EV.
11619 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11620 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11621 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11622 EXPECT_FALSE(
11623 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11624}
11625
11626TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
11627 if (!SystemSupportsOCSP()) {
11628 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11629 return;
11630 }
11631
[email protected]ce7d0cbc2013-05-03 18:57:2211632 SpawnedTestServer::SSLOptions ssl_options(
11633 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811634 ssl_options.ocsp_status =
11635 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211636 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11637 cert_verifier_config.crl_set = CRLSet::EmptyCRLSetForTesting();
11638 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211639
[email protected]51523f52013-07-31 21:57:2811640 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1211641 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211642
[email protected]51523f52013-07-31 21:57:2811643 // Even with a fresh CRLSet, we should still do online revocation checks when
11644 // the certificate chain isn't covered by the CRLSet, which it isn't in this
11645 // test.
mattmaf868e72016-09-23 23:25:2011646 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2811647 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0211648
[email protected]51523f52013-07-31 21:57:2811649 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0211650 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2811651 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211652}
11653
11654class HTTPSCRLSetTest : public HTTPSOCSPTest {
11655 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611656 CertVerifier::Config GetCertVerifierConfig() override {
11657 CertVerifier::Config config;
11658 return config;
Ryan Sleevi5b4702a2018-04-06 22:23:5611659 }
11660
11661 void SetUp() override {
11662 HTTPSOCSPTest::SetUp();
11663
11664 // Unmark the certificate's OID as EV, which should disable revocation
11665 // checking (as per the user preference).
11666 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0211667 }
11668};
11669
11670TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2211671 SpawnedTestServer::SSLOptions ssl_options(
11672 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811673 ssl_options.ocsp_status =
11674 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211675 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11676 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11677 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211678
[email protected]924e9f92012-12-16 22:00:5311679 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211680 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211681
11682 // If we're not trying EV verification then, even if the CRLSet has expired,
11683 // we don't fall back to online revocation checks.
11684 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11685 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11686 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11687}
[email protected]51523f52013-07-31 21:57:2811688
Ryan Sleevi5b4702a2018-04-06 22:23:5611689TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
11690 // Test that when online revocation checking is disabled, and the leaf
11691 // certificate is not EV, that no revocation checking actually happens.
11692 if (!SystemSupportsOCSP()) {
11693 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11694 return;
11695 }
11696
11697 SpawnedTestServer::SSLOptions ssl_options(
11698 SpawnedTestServer::SSLOptions::CERT_AUTO);
11699 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Ryan Sleevib369d712018-08-20 16:43:2211700
11701 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11702 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11703 context_.cert_verifier()->SetConfig(cert_verifier_config);
Ryan Sleevi5b4702a2018-04-06 22:23:5611704
11705 CertStatus cert_status;
11706 DoConnection(ssl_options, &cert_status);
11707
11708 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11709
11710 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11711 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11712}
11713
[email protected]51523f52013-07-31 21:57:2811714TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2511715#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2811716 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11717 return;
11718#endif
11719
11720 SpawnedTestServer::SSLOptions ssl_options(
11721 SpawnedTestServer::SSLOptions::CERT_AUTO);
11722 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11723 ssl_options.cert_serial = 10;
Ryan Sleevib369d712018-08-20 16:43:2211724
11725 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11726 cert_verifier_config.crl_set =
11727 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {});
11728 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2811729
11730 CertStatus cert_status = 0;
11731 DoConnection(ssl_options, &cert_status);
11732
11733 // If the certificate is recorded as revoked in the CRLSet, that should be
11734 // reflected without online revocation checking.
11735 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11736 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5611737 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2811738}
Adam Langleyea6d6782017-12-05 23:57:3311739
11740TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
11741#if defined(OS_ANDROID)
11742 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11743 return;
11744#endif
11745
11746 SpawnedTestServer::SSLOptions ssl_options(
11747 SpawnedTestServer::SSLOptions::CERT_AUTO);
11748 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11749 static const char kCommonName[] = "Test CN";
11750 ssl_options.cert_common_name = kCommonName;
11751
11752 {
Ryan Sleevib369d712018-08-20 16:43:2211753 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11754 cert_verifier_config.crl_set =
11755 CRLSet::ForTesting(false, nullptr, "", kCommonName, {});
11756 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3311757
11758 CertStatus cert_status = 0;
11759 DoConnection(ssl_options, &cert_status);
11760
11761 // If the certificate is recorded as revoked in the CRLSet, that should be
11762 // reflected without online revocation checking.
11763 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11764 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5611765 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3311766 }
11767
11768 const uint8_t kTestServerSPKISHA256[32] = {
11769 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
11770 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
11771 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
11772 };
11773 const std::string spki_hash(
11774 reinterpret_cast<const char*>(kTestServerSPKISHA256),
11775 sizeof(kTestServerSPKISHA256));
11776
11777 {
Ryan Sleevib369d712018-08-20 16:43:2211778 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11779 cert_verifier_config.crl_set =
11780 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash});
11781 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3311782
11783 CertStatus cert_status = 0;
11784 DoConnection(ssl_options, &cert_status);
11785
11786 // When the correct SPKI hash is specified, the connection should succeed
11787 // even though the subject is listed in the CRLSet.
11788 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11789 }
11790}
[email protected]316c1e5e2012-09-12 15:17:4411791#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2711792
Sergey Ulanovc4580e72017-09-13 23:30:1111793#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
11794 !defined(OS_FUCHSIA)
11795// FTP uses a second TCP connection with the port number allocated dynamically
11796// on the server side, so it would be hard to make RemoteTestServer proxy FTP
11797// connections reliably. FTP tests are disabled on platforms that use
11798// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3111799class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1111800 public:
[email protected]d9fca99a2012-02-24 16:16:2011801 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0511802 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5511803 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4711804 // Can't use |default_context_|'s HostResolver to set up the
11805 // FTPTransactionFactory because it hasn't been created yet.
Ryan Sleevib8449e02018-07-15 04:31:0711806 default_context().set_host_resolver(&host_resolver_);
mmenke9f2ec60c2015-06-01 20:59:4711807 }
11808
11809 // URLRequestTest interface:
11810 void SetUpFactory() override {
11811 // Add FTP support to the default URLRequestContext.
11812 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0511813 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4711814 }
11815
11816 std::string GetTestFileContents() {
11817 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1911818 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4711819 path = path.Append(kTestFilePath);
11820 path = path.AppendASCII(kFtpTestFile);
11821 std::string contents;
11822 EXPECT_TRUE(base::ReadFileToString(path, &contents));
11823 return contents;
[email protected]95409e12010-08-17 20:07:1111824 }
11825
[email protected]b89ca032009-08-31 21:41:3111826 protected:
mmenke9f2ec60c2015-06-01 20:59:4711827 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4711828
tommycli59a63432015-11-06 00:10:5511829 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3111830};
11831
[email protected]d2a133182012-08-05 16:44:0811832// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0911833TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0811834 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0811835
11836 TestDelegate d;
11837 {
Ryan Sleevib8449e02018-07-15 04:31:0711838 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611839 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911840 r->Start();
11841 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0811842
Wez2a31b222018-06-07 22:07:1511843 d.RunUntilComplete();
[email protected]d2a133182012-08-05 16:44:0811844
[email protected]f7022f32014-08-21 16:32:1911845 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5011846 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0811847 }
11848}
11849
mmenke9f2ec60c2015-06-01 20:59:4711850TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5511851 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111852
[email protected]a25e90e2009-09-09 17:05:3711853 TestDelegate d;
11854 {
Ryan Sleevib8449e02018-07-15 04:31:0711855 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611856 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
11857 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911858 r->Start();
11859 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711860
Wez2a31b222018-06-07 22:07:1511861 d.RunUntilComplete();
[email protected]a25e90e2009-09-09 17:05:3711862
[email protected]f7022f32014-08-21 16:32:1911863 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711864 EXPECT_EQ(1, d.response_started_count());
11865 EXPECT_FALSE(d.received_data_before_response());
11866 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5511867 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711868 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5511869 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711870 r->GetResponseRemoteEndpoint().port());
[email protected]a25e90e2009-09-09 17:05:3711871 }
11872}
11873
mmenke9f2ec60c2015-06-01 20:59:4711874TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5511875 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111876
[email protected]dd265012009-01-08 20:45:2711877 TestDelegate d;
11878 {
Ryan Sleevib8449e02018-07-15 04:31:0711879 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611880 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
11881 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911882 r->Start();
11883 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711884
Wez2a31b222018-06-07 22:07:1511885 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711886
[email protected]f7022f32014-08-21 16:32:1911887 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711888 EXPECT_EQ(1, d.response_started_count());
11889 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711890 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511891 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711892 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5511893 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711894 r->GetResponseRemoteEndpoint().port());
[email protected]dd265012009-01-08 20:45:2711895 }
11896}
11897
Mike West80462a12018-11-27 16:05:0611898TEST_F(URLRequestTestFTP, FTPMimeType) {
11899 ASSERT_TRUE(ftp_test_server_.Start());
11900
11901 struct {
11902 const char* path;
11903 const char* mime;
11904 } test_cases[] = {
11905 {"/", "text/vnd.chromium.ftp-dir"},
11906 {kFtpTestFile, "application/octet-stream"},
11907 };
11908
11909 for (const auto test : test_cases) {
11910 TestDelegate d;
11911
11912 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
11913 ftp_test_server_.GetURL(test.path), DEFAULT_PRIORITY, &d,
11914 TRAFFIC_ANNOTATION_FOR_TESTS));
11915 r->Start();
11916 EXPECT_TRUE(r->is_pending());
11917
11918 d.RunUntilComplete();
11919
11920 std::string mime;
11921 r->GetMimeType(&mime);
11922 EXPECT_EQ(test.mime, mime);
11923 }
11924}
11925
mmenke9f2ec60c2015-06-01 20:59:4711926TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5511927 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111928
[email protected]dd265012009-01-08 20:45:2711929 TestDelegate d;
11930 {
Ryan Sleevib8449e02018-07-15 04:31:0711931 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511932 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11933 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611934 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911935 r->Start();
11936 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711937
Wez2a31b222018-06-07 22:07:1511938 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711939
[email protected]f7022f32014-08-21 16:32:1911940 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4711941 EXPECT_EQ(1, d.response_started_count());
11942 EXPECT_FALSE(d.received_data_before_response());
11943 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511944 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711945 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5511946 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711947 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:2511948
11949 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1911950 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2511951 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2711952 }
11953}
11954
mmenke9f2ec60c2015-06-01 20:59:4711955TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5511956 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111957
[email protected]dd265012009-01-08 20:45:2711958 TestDelegate d;
11959 {
Ryan Sleevib8449e02018-07-15 04:31:0711960 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511961 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11962 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611963 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911964 r->Start();
11965 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711966
Wez2a31b222018-06-07 22:07:1511967 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711968
[email protected]f7022f32014-08-21 16:32:1911969 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711970 EXPECT_EQ(1, d.response_started_count());
11971 EXPECT_FALSE(d.received_data_before_response());
11972 EXPECT_EQ(d.bytes_received(), 0);
11973 }
11974}
11975
mmenke9f2ec60c2015-06-01 20:59:4711976TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5511977 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111978
[email protected]8b8a197d2009-08-26 15:57:5811979 TestDelegate d;
11980 // Set correct login credentials. The delegate will be asked for them when
11981 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811982 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811983 {
Ryan Sleevib8449e02018-07-15 04:31:0711984 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511985 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11986 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611987 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911988 r->Start();
11989 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811990
Wez2a31b222018-06-07 22:07:1511991 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5811992
[email protected]f7022f32014-08-21 16:32:1911993 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811994 EXPECT_EQ(1, d.response_started_count());
11995 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711996 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811997 }
11998}
11999
mmenke9f2ec60c2015-06-01 20:59:4712000TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5512001 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112002
[email protected]dd265012009-01-08 20:45:2712003 TestDelegate d;
12004 {
Ryan Sleevib8449e02018-07-15 04:31:0712005 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512006 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12007 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612008 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912009 r->Start();
12010 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712011
Wez2a31b222018-06-07 22:07:1512012 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712013
[email protected]f7022f32014-08-21 16:32:1912014 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712015 EXPECT_EQ(1, d.response_started_count());
12016 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712017 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2712018 }
12019}
[email protected]8b8a197d2009-08-26 15:57:5812020
mmenke9f2ec60c2015-06-01 20:59:4712021TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5512022 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112023
[email protected]8b8a197d2009-08-26 15:57:5812024 TestDelegate d;
12025 // Set correct login credentials. The delegate will be asked for them when
12026 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812027 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812028 {
Ryan Sleevib8449e02018-07-15 04:31:0712029 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512030 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12031 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612032 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912033 r->Start();
12034 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812035
Wez2a31b222018-06-07 22:07:1512036 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812037
[email protected]f7022f32014-08-21 16:32:1912038 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812039 EXPECT_EQ(1, d.response_started_count());
12040 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712041 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812042 }
12043}
[email protected]60a3df52009-09-22 16:13:2412044
mmenke9f2ec60c2015-06-01 20:59:4712045TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5512046 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112047
danakj8522a25b2016-04-16 00:17:3612048 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412049 {
12050 // Pass correct login identity in the URL.
Ryan Sleevib8449e02018-07-15 04:31:0712051 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512052 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12053 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612054 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912055 r->Start();
12056 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412057
Wez2a31b222018-06-07 22:07:1512058 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412059
[email protected]f7022f32014-08-21 16:32:1912060 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412061 EXPECT_EQ(1, d->response_started_count());
12062 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712063 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412064 }
12065
12066 d.reset(new TestDelegate);
12067 {
12068 // This request should use cached identity from previous request.
Ryan Sleevib8449e02018-07-15 04:31:0712069 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612070 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12071 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912072 r->Start();
12073 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412074
Wez2a31b222018-06-07 22:07:1512075 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412076
[email protected]f7022f32014-08-21 16:32:1912077 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412078 EXPECT_EQ(1, d->response_started_count());
12079 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712080 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412081 }
12082}
12083
mmenke9f2ec60c2015-06-01 20:59:4712084TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5512085 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112086
danakj8522a25b2016-04-16 00:17:3612087 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412088 // Set correct login credentials. The delegate will be asked for them when
12089 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812090 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2412091 {
Ryan Sleevib8449e02018-07-15 04:31:0712092 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512093 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12094 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612095 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912096 r->Start();
12097 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412098
Wez2a31b222018-06-07 22:07:1512099 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412100
[email protected]f7022f32014-08-21 16:32:1912101 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412102 EXPECT_EQ(1, d->response_started_count());
12103 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712104 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412105 }
12106
12107 // Use a new delegate without explicit credentials. The cached ones should be
12108 // used.
12109 d.reset(new TestDelegate);
12110 {
12111 // Don't pass wrong credentials in the URL, they would override valid cached
12112 // ones.
Ryan Sleevib8449e02018-07-15 04:31:0712113 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612114 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12115 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912116 r->Start();
12117 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412118
Wez2a31b222018-06-07 22:07:1512119 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412120
[email protected]f7022f32014-08-21 16:32:1912121 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412122 EXPECT_EQ(1, d->response_started_count());
12123 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712124 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412125 }
12126}
ricea3a1c71f2016-06-17 10:05:2612127
12128TEST_F(URLRequestTestFTP, RawBodyBytes) {
12129 ASSERT_TRUE(ftp_test_server_.Start());
12130
12131 TestDelegate d;
12132 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612133 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12134 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2612135 req->Start();
Wez2a31b222018-06-07 22:07:1512136 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:2612137
12138 EXPECT_EQ(6, req->GetRawBodyBytes());
12139}
12140
brettwa1228ebb2016-10-28 03:51:3412141#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5112142
ttuttlec0c828492015-05-15 01:25:5512143TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
12144 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712145 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612146 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512147
12148 EXPECT_FALSE(req->response_info().network_accessed);
12149
12150 req->Start();
Wez2a31b222018-06-07 22:07:1512151 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512152
12153 EXPECT_EQ(1, default_network_delegate_.completed_requests());
12154 EXPECT_FALSE(req->response_info().network_accessed);
12155}
12156
12157TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
12158 MockHostResolver host_resolver;
12159 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
12160 TestURLRequestContext context(true);
12161 context.set_network_delegate(&network_delegate);
12162 context.set_host_resolver(&host_resolver);
12163 host_resolver.rules()->AddSimulatedFailure("*");
12164 context.Init();
12165
12166 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612167 std::unique_ptr<URLRequest> req(
12168 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
12169 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512170
12171 EXPECT_FALSE(req->response_info().network_accessed);
12172
12173 req->Start();
Wez2a31b222018-06-07 22:07:1512174 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512175 EXPECT_TRUE(req->response_info().network_accessed);
12176}
12177
mmenkeed0498b2015-12-08 23:20:4212178// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2212179// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4212180TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2212181 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712182 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612183 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
12184 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2212185
danakj8522a25b2016-04-16 00:17:3612186 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2212187 req.get(), &default_network_delegate_,
12188 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4212189 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
12190 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2212191
12192 req->Start();
12193 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2212194 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5012195 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2212196 EXPECT_EQ(0, d.received_redirect_count());
12197}
12198
Andrey Kosyakov2e893e62017-08-31 17:00:5212199TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412200 ASSERT_TRUE(http_test_server()->Start());
12201 TestURLRequestContext context;
12202 GURL url(http_test_server()->GetURL("/cachetime"));
12203 TestDelegate delegate;
12204 HttpRequestHeaders extra_headers;
12205 extra_headers.SetHeader("X-Foo", "bar");
12206
12207 {
Andrey Kosyakov2e893e62017-08-31 17:00:5212208 HttpRawRequestHeaders raw_req_headers;
12209 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12210
Andrey Kosyakov83a6eee2017-08-14 19:20:0412211 std::unique_ptr<URLRequest> r(context.CreateRequest(
12212 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12213 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212214 r->SetRequestHeadersCallback(base::Bind(
12215 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
12216 r->SetResponseHeadersCallback(base::Bind(
12217 [](scoped_refptr<const HttpResponseHeaders>* left,
12218 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12219 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412220 r->Start();
12221 while (!delegate.response_started_count())
12222 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5212223 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412224 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212225 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412226 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212227 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412228 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212229 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
12230 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
12231 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
12232 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412233 }
12234 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412235 std::unique_ptr<URLRequest> r(context.CreateRequest(
12236 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12237 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212238 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412239 FAIL() << "Callback should not be called unless request is sent";
12240 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212241 r->SetResponseHeadersCallback(
12242 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
12243 FAIL() << "Callback should not be called unless request is sent";
12244 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412245 r->Start();
Wez2a31b222018-06-07 22:07:1512246 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412247 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412248 }
12249}
12250
Andrey Kosyakov2e893e62017-08-31 17:00:5212251TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412252 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5212253 HttpRawRequestHeaders raw_req_headers;
12254 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12255
Andrey Kosyakov83a6eee2017-08-14 19:20:0412256 TestURLRequestContext context;
12257 TestDelegate delegate;
12258 HttpRequestHeaders extra_headers;
12259 extra_headers.SetHeader("X-Foo", "bar");
Andrey Kosyakov83a6eee2017-08-14 19:20:0412260 GURL url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:0712261 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412262 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12263 r->SetExtraRequestHeaders(extra_headers);
12264 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5212265 base::Unretained(&raw_req_headers)));
12266 r->SetResponseHeadersCallback(base::Bind(
12267 [](scoped_refptr<const HttpResponseHeaders>* left,
12268 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12269 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412270 r->Start();
Wez0e717112018-06-18 23:09:2212271 delegate.RunUntilRedirect();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412272
12273 ASSERT_EQ(1, delegate.received_redirect_count());
12274 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212275 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412276 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212277 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412278 EXPECT_EQ("gzip, deflate", value);
12279 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5212280 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
12281 raw_req_headers.request_line());
12282 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
12283 EXPECT_EQ(302, raw_resp_headers->response_code());
12284 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412285
Andrey Kosyakov2e893e62017-08-31 17:00:5212286 raw_req_headers = HttpRawRequestHeaders();
12287 raw_resp_headers = nullptr;
Arthur Sonzognib8465ff72019-01-04 18:44:3512288 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
12289 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:1512290 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212291 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412292 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212293 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412294 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212295 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
12296 raw_req_headers.request_line());
12297 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412298}
12299
Andrey Kosyakov2e893e62017-08-31 17:00:5212300TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412301 TestDelegate request_delegate;
12302
Ryan Sleevib8449e02018-07-15 04:31:0712303 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412304 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
12305 TRAFFIC_ANNOTATION_FOR_TESTS));
12306 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
12307 FAIL() << "Callback should not be called unless request is sent";
12308 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212309 r->SetResponseHeadersCallback(
12310 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12311 FAIL() << "Callback should not be called unless request is sent";
12312 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412313 r->Start();
Wez2a31b222018-06-07 22:07:1512314 request_delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412315 EXPECT_FALSE(r->is_pending());
12316}
12317
Andrey Kosyakov2e893e62017-08-31 17:00:5212318TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412319 ASSERT_TRUE(http_test_server()->Start());
12320 GURL url(http_test_server()->GetURL("/auth-basic"));
12321
12322 TestURLRequestContext context;
12323 TestDelegate delegate;
12324
12325 delegate.set_credentials(AuthCredentials(kUser, kSecret));
12326 HttpRequestHeaders extra_headers;
12327 extra_headers.SetHeader("X-Foo", "bar");
12328
Andrey Kosyakov2e893e62017-08-31 17:00:5212329 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
12330 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0412331
Andrey Kosyakov2e893e62017-08-31 17:00:5212332 using RespHeadersVector =
12333 std::vector<scoped_refptr<const HttpResponseHeaders>>;
12334 RespHeadersVector raw_resp_headers;
12335
12336 auto req_headers_callback = base::Bind(
12337 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
12338 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
12339 },
12340 &raw_req_headers);
12341 auto resp_headers_callback = base::Bind(
12342 [](RespHeadersVector* vec,
12343 scoped_refptr<const HttpResponseHeaders> headers) {
12344 vec->push_back(headers);
12345 },
12346 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412347 std::unique_ptr<URLRequest> r(context.CreateRequest(
12348 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12349 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212350 r->SetRequestHeadersCallback(req_headers_callback);
12351 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412352 r->Start();
Wez2a31b222018-06-07 22:07:1512353 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412354 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5212355 ASSERT_EQ(raw_req_headers.size(), 2u);
12356 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412357 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212358 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
12359 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412360 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212361 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
12362 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412363 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212364 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
12365 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
12366 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
12367 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
12368
12369 std::unique_ptr<URLRequest> r2(context.CreateRequest(
12370 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12371 r2->SetExtraRequestHeaders(extra_headers);
12372 r2->SetRequestHeadersCallback(req_headers_callback);
12373 r2->SetResponseHeadersCallback(resp_headers_callback);
12374 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
12375 r2->Start();
Wez2a31b222018-06-07 22:07:1512376 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212377 EXPECT_FALSE(r2->is_pending());
12378 ASSERT_EQ(raw_req_headers.size(), 3u);
12379 ASSERT_EQ(raw_resp_headers.size(), 3u);
12380 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
12381 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
12382 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
12383 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412384}
12385
Andrey Kosyakov2e893e62017-08-31 17:00:5212386TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412387 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
12388 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712389 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412390 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12391 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5212392 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0412393 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212394 r->SetResponseHeadersCallback(
12395 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12396 FAIL() << "Callback should not be called for non-HTTP schemes";
12397 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412398 r->Start();
Wez2a31b222018-06-07 22:07:1512399 d.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412400 EXPECT_FALSE(r->is_pending());
12401}
12402
Carlos ILaef65d62018-06-04 21:24:1312403TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
12404 TestDelegate d;
12405 BlockingNetworkDelegate network_delegate(
12406 BlockingNetworkDelegate::SYNCHRONOUS);
12407 const GURL kOriginalUrl("https://original.test");
12408 const GURL kRedirectUrl("http://redirect.test");
12409 network_delegate.set_redirect_url(kRedirectUrl);
12410 TestURLRequestContext context(true /* delay_initialization */);
12411 context.set_network_delegate(&network_delegate);
12412 context.Init();
12413
12414 std::unique_ptr<URLRequest> r(context.CreateRequest(
12415 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12416 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312417 r->Start();
Wez0e717112018-06-18 23:09:2212418 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312419 GURL::Replacements replacements;
12420 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12421 // was set.
12422 replacements.SetSchemeStr("https");
12423 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12424 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412425 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312426}
12427
12428TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
12429 TestDelegate d;
12430 BlockingNetworkDelegate network_delegate(
12431 BlockingNetworkDelegate::SYNCHRONOUS);
12432 const GURL kOriginalUrl("https://original.test");
12433 const GURL kRedirectUrl("http://redirect.test:80");
12434 network_delegate.set_redirect_url(kRedirectUrl);
12435 TestURLRequestContext context(true /* delay_initialization */);
12436 context.set_network_delegate(&network_delegate);
12437 context.Init();
12438
12439 std::unique_ptr<URLRequest> r(context.CreateRequest(
12440 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12441 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312442 r->Start();
Wez0e717112018-06-18 23:09:2212443 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312444 GURL::Replacements replacements;
12445 // The URL host should have not been changed.
12446 EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
12447 // The scheme should now be https, and the effective port should now be 443.
12448 EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
12449 EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
Carlos IL0d67fc72018-06-22 17:18:4412450 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312451}
12452
12453TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
12454 TestDelegate d;
12455 BlockingNetworkDelegate network_delegate(
12456 BlockingNetworkDelegate::SYNCHRONOUS);
12457 const GURL kOriginalUrl("https://original.test");
12458 const GURL kRedirectUrl("http://redirect.test:1234");
12459 network_delegate.set_redirect_url(kRedirectUrl);
12460 TestURLRequestContext context(true /* delay_initialization */);
12461 context.set_network_delegate(&network_delegate);
12462 context.Init();
12463
12464 std::unique_ptr<URLRequest> r(context.CreateRequest(
12465 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12466 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312467 r->Start();
Wez0e717112018-06-18 23:09:2212468 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312469 GURL::Replacements replacements;
12470 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12471 // was set, nonstandard port should not have been modified.
12472 replacements.SetSchemeStr("https");
12473 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12474 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412475 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312476}
12477
12478TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
12479 TestDelegate d;
12480 BlockingNetworkDelegate network_delegate(
12481 BlockingNetworkDelegate::SYNCHRONOUS);
12482 const GURL kOriginalUrl("https://original.test");
12483 const GURL kRedirectUrl("http://redirect.test");
12484 network_delegate.set_redirect_url(kRedirectUrl);
12485 TestURLRequestContext context(true /* delay_initialization */);
12486 context.set_network_delegate(&network_delegate);
12487 context.Init();
12488 std::unique_ptr<URLRequest> r(context.CreateRequest(
12489 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12490 r->set_upgrade_if_insecure(false);
Carlos ILaef65d62018-06-04 21:24:1312491 r->Start();
Wez0e717112018-06-18 23:09:2212492 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312493 // The redirect URL should not be changed if the upgrade_if_insecure flag is
12494 // not set.
12495 EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412496 EXPECT_FALSE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312497}
12498
Paul Jensen60e45532018-02-19 16:04:1812499// Test that URLRequests get properly tagged.
12500#if defined(OS_ANDROID)
12501TEST_F(URLRequestTestHTTP, TestTagging) {
Peter Collingbourne8ccab722019-02-12 18:10:4812502 if (!CanGetTaggedBytes()) {
12503 DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
12504 return;
12505 }
12506
Paul Jensen60e45532018-02-19 16:04:1812507 ASSERT_TRUE(http_test_server()->Start());
12508
12509 // The tag under which the system reports untagged traffic.
12510 static const int32_t UNTAGGED_TAG = 0;
12511
12512 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
12513
12514 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
12515 TestDelegate delegate;
Ryan Sleevib8449e02018-07-15 04:31:0712516 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Paul Jensen60e45532018-02-19 16:04:1812517 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
12518 TRAFFIC_ANNOTATION_FOR_TESTS));
12519 EXPECT_EQ(SocketTag(), req->socket_tag());
12520 req->Start();
Wez2a31b222018-06-07 22:07:1512521 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812522
12523 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
12524
12525 int32_t tag_val1 = 0x12345678;
12526 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
12527 old_traffic = GetTaggedBytes(tag_val1);
12528
12529 // Test specific tag value.
Ryan Sleevib8449e02018-07-15 04:31:0712530 req = default_context().CreateRequest(http_test_server()->GetURL("/"),
12531 DEFAULT_PRIORITY, &delegate,
12532 TRAFFIC_ANNOTATION_FOR_TESTS);
Paul Jensen60e45532018-02-19 16:04:1812533 req->set_socket_tag(tag1);
12534 EXPECT_EQ(tag1, req->socket_tag());
12535 req->Start();
Wez2a31b222018-06-07 22:07:1512536 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812537
12538 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
12539}
12540#endif
12541
[email protected]7461a402011-03-24 23:19:5112542} // namespace net