blob: 6133fc4b481de877018e98676babb8e3bd1bd268 [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"
David Benjamina7fde612019-03-15 14:20:5856#include "net/base/escape.h"
Aaron Tagliaboschi028009e2019-03-07 16:28:0657#include "net/base/layered_network_delegate.h"
initial.commit586acc5fe2008-07-26 22:42:5258#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2559#include "net/base/load_timing_info.h"
60#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0661#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5262#include "net/base/net_module.h"
Lily Houghton582d4622018-01-22 22:43:4063#include "net/base/proxy_server.h"
[email protected]2ca01e52013-10-31 22:05:1964#include "net/base/request_priority.h"
zhongyi18ddddd2017-02-03 19:06:3665#include "net/base/test_completion_callback.h"
[email protected]f288ef02012-12-15 20:28:2866#include "net/base/upload_bytes_element_reader.h"
67#include "net/base/upload_data_stream.h"
68#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4469#include "net/base/url_util.h"
Ryan Sleevib369d712018-08-20 16:43:2270#include "net/cert/crl_set.h"
rsleevid6de8302016-06-21 01:33:2071#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4772#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3673#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1174#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2475#include "net/cert/mock_cert_verifier.h"
zhongyi18ddddd2017-02-03 19:06:3676#include "net/cert/multi_log_ct_verifier.h"
eranmdcec9632016-10-10 14:16:1077#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1178#include "net/cert/test_root_certs.h"
[email protected]aa84a7e2012-03-15 21:29:0679#include "net/cookies/cookie_monster.h"
80#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5281#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5382#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3883#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5284#include "net/http/http_cache.h"
85#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1986#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2587#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2188#include "net/http/http_response_headers.h"
zhongyi18ddddd2017-02-03 19:06:3689#include "net/http/http_server_properties_impl.h"
[email protected]e50efea2014-03-24 18:41:0090#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0091#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1992#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5193#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4694#include "net/log/test_net_log_entry.h"
95#include "net/log/test_net_log_util.h"
Scott Violet0caaaf432018-03-24 00:43:5996#include "net/net_buildflags.h"
Lily Houghtonffe89daa02018-03-09 18:30:0397#include "net/proxy_resolution/proxy_resolution_service.h"
Ryan Hamiltona3ee93a72018-08-01 22:03:0898#include "net/quic/mock_crypto_client_stream_factory.h"
99#include "net/quic/quic_server_info.h"
zhongyi18ddddd2017-02-03 19:06:36100#include "net/socket/socket_test_util.h"
[email protected]c3456bb2011-12-12 22:22:19101#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:14102#include "net/ssl/channel_id_service.h"
David Benjamin76a40ad2018-02-24 22:22:08103#include "net/ssl/client_cert_identity_test_util.h"
nharperb7441ef2016-01-25 23:54:14104#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:57105#include "net/ssl/ssl_connection_status_flags.h"
David Benjamin76a40ad2018-02-24 22:22:08106#include "net/ssl/ssl_private_key.h"
tommycli59a63432015-11-06 00:10:55107#include "net/ssl/ssl_server_config.h"
[email protected]6e7845ae2013-03-29 21:48:11108#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:36109#include "net/test/embedded_test_server/embedded_test_server.h"
110#include "net/test/embedded_test_server/http_request.h"
111#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:01112#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21113#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43114#include "net/test/test_data_directory.h"
Bence Béky98447b12018-05-08 03:14:01115#include "net/test/test_with_scoped_task_environment.h"
mmenkefb18c772015-09-30 22:22:50116#include "net/test/url_request/url_request_failed_job.h"
Carlos ILaef65d62018-06-04 21:24:13117#include "net/test/url_request/url_request_mock_http_job.h"
rhalavatib7bd7c792017-04-27 05:25:16118#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34119#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43120#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52121#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50122#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14123#include "net/url_request/url_request_http_job.h"
Thiemo Nagel0793b9c532018-04-18 16:57:58124#include "net/url_request/url_request_http_job_histogram.h"
bengr1bf8e942014-11-07 01:36:50125#include "net/url_request/url_request_intercepting_job_factory.h"
126#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49127#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51128#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47129#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44130#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01131#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52132#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15133#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52134
Eric Romanefddd0a2017-10-10 02:14:25135#if defined(OS_FUCHSIA)
136#define USE_BUILTIN_CERT_VERIFIER
137#endif
138
brettwa1228ebb2016-10-28 03:51:34139#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55140#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29141#include "net/url_request/file_protocol_handler.h"
142#include "net/url_request/url_request_file_dir_job.h"
143#endif
144
brettwa1228ebb2016-10-28 03:51:34145#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47146#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29147#include "net/url_request/ftp_protocol_handler.h"
148#endif
149
[email protected]dffe8242012-03-20 15:14:27150#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48151#include "base/win/scoped_com_initializer.h"
[email protected]dffe8242012-03-20 15:14:27152#endif
153
mmenkefd9d15c2017-06-29 13:45:54154#if BUILDFLAG(ENABLE_REPORTING)
Julia Tuttlecba7d222018-02-23 19:37:27155#include "net/network_error_logging/network_error_logging_service.h"
Lily Chenfec60d92019-01-24 01:16:42156#include "net/network_error_logging/network_error_logging_test_util.h"
mmenkefd9d15c2017-06-29 13:45:54157#endif // BUILDFLAG(ENABLE_REPORTING)
158
Matt Muellerfb271992018-01-30 18:10:48159#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:25160#include "net/cert/cert_net_fetcher.h"
161#include "net/cert_net/cert_net_fetcher_impl.h"
162#endif
163
164#if defined(USE_NSS_CERTS)
165#include "net/cert_net/nss_ocsp.h"
166#endif
167
robpercival214763f2016-07-01 23:27:01168using net::test::IsError;
169using net::test::IsOk;
170
[email protected]ad65a3e2013-12-25 18:18:01171using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33172using base::Time;
halton.huoe4e45742014-12-08 07:55:46173using std::string;
[email protected]e1acf6f2008-10-27 20:43:33174
[email protected]7461a402011-03-24 23:19:51175namespace net {
176
initial.commit586acc5fe2008-07-26 22:42:52177namespace {
178
Martijn Croonenb1383da2017-10-11 11:56:35179namespace test_default {
180#include "net/http/transport_security_state_static_unittest_default.h"
xunjieli815ad5b2017-07-18 15:51:35181}
182
[email protected]42cba2fb2013-03-29 19:58:57183const base::string16 kChrome(ASCIIToUTF16("chrome"));
184const base::string16 kSecret(ASCIIToUTF16("secret"));
185const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44186
mmenke9f2ec60c2015-06-01 20:59:47187const base::FilePath::CharType kTestFilePath[] =
188 FILE_PATH_LITERAL("net/data/url_request_unittest");
189
Sergey Ulanovc4580e72017-09-13 23:30:11190#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
191 !defined(OS_FUCHSIA)
mmenke9f2ec60c2015-06-01 20:59:47192// Test file used in most FTP tests.
193const char kFtpTestFile[] = "BullRunSpeech.txt";
194#endif
195
[email protected]2bba3252013-04-08 19:50:59196// Tests load timing information in the case a fresh connection was used, with
197// no proxy.
[email protected]cba24642014-08-15 20:49:59198void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25199 int connect_timing_flags) {
200 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19201 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25202
203 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
204 EXPECT_FALSE(load_timing_info.request_start.is_null());
205
206 EXPECT_LE(load_timing_info.request_start,
207 load_timing_info.connect_timing.connect_start);
208 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
209 connect_timing_flags);
210 EXPECT_LE(load_timing_info.connect_timing.connect_end,
211 load_timing_info.send_start);
212 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38213 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
214 EXPECT_LE(load_timing_info.receive_headers_start,
215 load_timing_info.receive_headers_end);
[email protected]58e32bb2013-01-21 18:23:25216
[email protected]58e32bb2013-01-21 18:23:25217 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
218 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
219}
220
[email protected]2bba3252013-04-08 19:50:59221// Same as above, but with proxy times.
222void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59223 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59224 int connect_timing_flags) {
225 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19226 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59227
228 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
229 EXPECT_FALSE(load_timing_info.request_start.is_null());
230
231 EXPECT_LE(load_timing_info.request_start,
232 load_timing_info.proxy_resolve_start);
233 EXPECT_LE(load_timing_info.proxy_resolve_start,
234 load_timing_info.proxy_resolve_end);
235 EXPECT_LE(load_timing_info.proxy_resolve_end,
236 load_timing_info.connect_timing.connect_start);
237 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
238 connect_timing_flags);
239 EXPECT_LE(load_timing_info.connect_timing.connect_end,
240 load_timing_info.send_start);
241 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38242 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
243 EXPECT_LE(load_timing_info.receive_headers_start,
244 load_timing_info.receive_headers_end);
[email protected]2bba3252013-04-08 19:50:59245}
246
247// Same as above, but with a reused socket and proxy times.
248void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59249 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59250 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19251 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59252
253 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
254 EXPECT_FALSE(load_timing_info.request_start.is_null());
255
256 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
257
258 EXPECT_LE(load_timing_info.request_start,
259 load_timing_info.proxy_resolve_start);
260 EXPECT_LE(load_timing_info.proxy_resolve_start,
261 load_timing_info.proxy_resolve_end);
262 EXPECT_LE(load_timing_info.proxy_resolve_end,
263 load_timing_info.send_start);
264 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38265 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
266 EXPECT_LE(load_timing_info.receive_headers_start,
267 load_timing_info.receive_headers_end);
[email protected]2bba3252013-04-08 19:50:59268}
269
brettwa1228ebb2016-10-28 03:51:34270#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25271// Tests load timing information in the case of a cache hit, when no cache
272// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17273base::StringPiece TestNetResourceProvider(int key) {
274 return "header";
275}
276
277void FillBuffer(char* buffer, size_t len) {
278 static bool called = false;
279 if (!called) {
280 called = true;
281 int seed = static_cast<int>(Time::Now().ToInternalValue());
282 srand(seed);
283 }
284
285 for (size_t i = 0; i < len; i++) {
286 buffer[i] = static_cast<char>(rand());
287 if (!buffer[i])
288 buffer[i] = 'g';
289 }
290}
xunjielia6888202015-04-14 21:34:25291#endif
[email protected]e3a85452013-11-14 01:46:17292
[email protected]3b23a222013-05-15 21:33:25293void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59294 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25295 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19296 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25297
298 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
299 EXPECT_FALSE(load_timing_info.request_start.is_null());
300
301 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
302 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
303 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38304 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
305 EXPECT_LE(load_timing_info.receive_headers_start,
306 load_timing_info.receive_headers_end);
[email protected]3b23a222013-05-15 21:33:25307
308 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
309 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
310}
311
Sergey Ulanovc4580e72017-09-13 23:30:11312#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
313 !defined(OS_FUCHSIA)
[email protected]3b23a222013-05-15 21:33:25314// Tests load timing in the case that there is no HTTP response. This can be
315// used to test in the case of errors or non-HTTP requests.
316void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59317 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25318 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19319 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25320
321 // Only the request times should be non-null.
322 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
323 EXPECT_FALSE(load_timing_info.request_start.is_null());
324
325 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
326
327 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
328 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
329 EXPECT_TRUE(load_timing_info.send_start.is_null());
330 EXPECT_TRUE(load_timing_info.send_end.is_null());
Andrew Comminos1f2ff1cc2018-12-14 05:22:38331 EXPECT_TRUE(load_timing_info.receive_headers_start.is_null());
[email protected]58e32bb2013-01-21 18:23:25332 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
333}
xunjielia6888202015-04-14 21:34:25334#endif
[email protected]58e32bb2013-01-21 18:23:25335
mmenkefb18c772015-09-30 22:22:50336// Test power monitor source that can simulate entering suspend mode. Can't use
337// the one in base/ because it insists on bringing its own MessageLoop.
338class TestPowerMonitorSource : public base::PowerMonitorSource {
339 public:
Chris Watkins7a41d3552017-12-01 02:13:27340 TestPowerMonitorSource() = default;
341 ~TestPowerMonitorSource() override = default;
mmenkefb18c772015-09-30 22:22:50342
Colin Blundellc46597f2018-06-14 16:43:10343 void Shutdown() override {}
344
mmenkefb18c772015-09-30 22:22:50345 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
346
347 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
348
349 bool IsOnBatteryPowerImpl() override { return false; }
350
351 private:
352 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
353};
354
mmenkeed0498b2015-12-08 23:20:42355// Job that allows monitoring of its priority.
356class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
357 public:
358 // The latest priority of the job is always written to |request_priority_|.
359 PriorityMonitoringURLRequestJob(URLRequest* request,
360 NetworkDelegate* network_delegate,
361 RequestPriority* request_priority)
362 : URLRequestTestJob(request, network_delegate),
363 request_priority_(request_priority) {
364 *request_priority_ = DEFAULT_PRIORITY;
365 }
366
367 void SetPriority(RequestPriority priority) override {
368 *request_priority_ = priority;
369 URLRequestTestJob::SetPriority(priority);
370 }
371
372 private:
373 RequestPriority* const request_priority_;
374};
375
[email protected]71c64f62008-11-15 04:36:51376// Do a case-insensitive search through |haystack| for |needle|.
377bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50378 std::string::const_iterator it = std::search(
379 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
380 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51381 return it != haystack.end();
382}
383
danakj8522a25b2016-04-16 00:17:36384std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
385 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28386 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48387 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23388}
389
[email protected]96adadb2010-08-28 01:16:17390// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51391void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17392 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14393 uint16_t cipher_suite =
394 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29395 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17396}
397
[email protected]79e1fd62013-06-20 06:50:04398void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
399 const GURL& host_url) {
400 std::string sent_value;
401
402 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
403 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
404
405 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
406 EXPECT_EQ("keep-alive", sent_value);
407}
408
[email protected]dc5a5cf2012-09-26 02:49:30409// A network delegate that allows the user to choose a subset of request stages
410// to block in. When blocking, the delegate can do one of the following:
411// * synchronously return a pre-specified error code, or
412// * asynchronously return that value via an automatically called callback,
413// or
414// * block and wait for the user to do a callback.
415// Additionally, the user may also specify a redirect URL -- then each request
416// with the current URL different from the redirect target will be redirected
417// to that target, in the on-before-URL-request stage, independent of whether
418// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12419class BlockingNetworkDelegate : public TestNetworkDelegate {
420 public:
[email protected]dc5a5cf2012-09-26 02:49:30421 // Stages in which the delegate can block.
422 enum Stage {
[email protected]9045b8822012-01-13 20:35:35423 NOT_BLOCKED = 0,
424 ON_BEFORE_URL_REQUEST = 1 << 0,
425 ON_BEFORE_SEND_HEADERS = 1 << 1,
426 ON_HEADERS_RECEIVED = 1 << 2,
427 ON_AUTH_REQUIRED = 1 << 3
428 };
429
[email protected]dc5a5cf2012-09-26 02:49:30430 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59431 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30432 enum BlockMode {
433 SYNCHRONOUS, // No callback, returns specified return values.
434 AUTO_CALLBACK, // |this| posts a task to run the callback using the
435 // specified return codes.
436 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
437 // |auth_retval_| are ignored. In every blocking stage the
438 // message loop is quit.
439 };
440
441 // Creates a delegate which does not block at all.
442 explicit BlockingNetworkDelegate(BlockMode block_mode);
443
Wez2a31b222018-06-07 22:07:15444 // Runs the message loop until the delegate blocks.
445 void RunUntilBlocked();
446
[email protected]dc5a5cf2012-09-26 02:49:30447 // For users to trigger a callback returning |response|.
448 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
449 // Only call if |block_mode_| == USER_CALLBACK.
450 void DoCallback(int response);
451 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
452
453 // Setters.
454 void set_retval(int retval) {
455 ASSERT_NE(USER_CALLBACK, block_mode_);
456 ASSERT_NE(ERR_IO_PENDING, retval);
457 ASSERT_NE(OK, retval);
458 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35459 }
460
[email protected]dc5a5cf2012-09-26 02:49:30461 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
462 // |auth_credentials_| will be passed with the response.
463 void set_auth_retval(AuthRequiredResponse auth_retval) {
464 ASSERT_NE(USER_CALLBACK, block_mode_);
465 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
466 auth_retval_ = auth_retval;
467 }
468 void set_auth_credentials(const AuthCredentials& auth_credentials) {
469 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35470 }
471
[email protected]dc5a5cf2012-09-26 02:49:30472 void set_redirect_url(const GURL& url) {
473 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35474 }
475
[email protected]dc5a5cf2012-09-26 02:49:30476 void set_block_on(int block_on) {
477 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35478 }
479
[email protected]dc5a5cf2012-09-26 02:49:30480 // Allows the user to check in which state did we block.
481 Stage stage_blocked_for_callback() const {
482 EXPECT_EQ(USER_CALLBACK, block_mode_);
483 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35484 }
485
486 private:
Wez2a31b222018-06-07 22:07:15487 void OnBlocked();
488
David Benjamind1f287bf2018-06-12 01:57:20489 void RunCallback(int response, CompletionOnceCallback callback);
490 void RunAuthCallback(AuthRequiredResponse response, AuthCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30491
[email protected]9045b8822012-01-13 20:35:35492 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20493 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20494 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:20495 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35496
ryansturm2343cb62016-06-15 01:09:00497 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20498 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:00499 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35500
dchengb03027d2014-10-21 12:00:20501 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35502 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20503 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32504 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16505 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13506 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35507
dchengb03027d2014-10-21 12:00:20508 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35509 URLRequest* request,
510 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20511 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:13512 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35513
[email protected]dc5a5cf2012-09-26 02:49:30514 // Resets the callbacks and |stage_blocked_for_callback_|.
515 void Reset();
[email protected]9045b8822012-01-13 20:35:35516
[email protected]dc5a5cf2012-09-26 02:49:30517 // Checks whether we should block in |stage|. If yes, returns an error code
518 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
David Benjamind1f287bf2018-06-12 01:57:20519 int MaybeBlockStage(Stage stage, CompletionOnceCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30520
521 // Configuration parameters, can be adjusted by public methods:
522 const BlockMode block_mode_;
523
524 // Values returned on blocking stages when mode is SYNCHRONOUS or
525 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
526 int retval_; // To be returned in non-auth stages.
527 AuthRequiredResponse auth_retval_;
528
[email protected]5f714132014-03-26 10:41:16529 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30530 int block_on_; // Bit mask: in which stages to block.
531
532 // |auth_credentials_| will be copied to |*target_auth_credential_| on
533 // callback.
534 AuthCredentials auth_credentials_;
535 AuthCredentials* target_auth_credentials_;
536
537 // Internal variables, not set by not the user:
538 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
539 // USER_CALLBACK).
540 Stage stage_blocked_for_callback_;
541
542 // Callback objects stored during blocking stages.
David Benjamind1f287bf2018-06-12 01:57:20543 CompletionOnceCallback callback_;
[email protected]9045b8822012-01-13 20:35:35544 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30545
Wez2a31b222018-06-07 22:07:15546 // Closure to run to exit RunUntilBlocked().
547 base::OnceClosure on_blocked_;
548
[email protected]dc5a5cf2012-09-26 02:49:30549 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
550
551 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35552};
553
[email protected]dc5a5cf2012-09-26 02:49:30554BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
555 : block_mode_(block_mode),
556 retval_(OK),
557 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
558 block_on_(0),
Raul Tambre94493c652019-03-11 17:18:35559 target_auth_credentials_(nullptr),
[email protected]dc5a5cf2012-09-26 02:49:30560 stage_blocked_for_callback_(NOT_BLOCKED),
Raul Tambre94493c652019-03-11 17:18:35561 weak_factory_(this) {}
[email protected]dc5a5cf2012-09-26 02:49:30562
Wez2a31b222018-06-07 22:07:15563void BlockingNetworkDelegate::RunUntilBlocked() {
564 base::RunLoop run_loop;
565 on_blocked_ = run_loop.QuitClosure();
566 run_loop.Run();
567}
568
[email protected]dc5a5cf2012-09-26 02:49:30569void BlockingNetworkDelegate::DoCallback(int response) {
570 ASSERT_EQ(USER_CALLBACK, block_mode_);
571 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
572 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20573 CompletionOnceCallback callback = std::move(callback_);
[email protected]dc5a5cf2012-09-26 02:49:30574 Reset();
Wez2a31b222018-06-07 22:07:15575
576 // |callback| may trigger completion of a request, so post it as a task, so
577 // it will run under a subsequent TestDelegate::RunUntilComplete() loop.
578 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20579 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
580 weak_factory_.GetWeakPtr(), response,
581 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30582}
583
584void BlockingNetworkDelegate::DoAuthCallback(
585 NetworkDelegate::AuthRequiredResponse response) {
586 ASSERT_EQ(USER_CALLBACK, block_mode_);
587 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20588 AuthCallback auth_callback = std::move(auth_callback_);
[email protected]dc5a5cf2012-09-26 02:49:30589 Reset();
David Benjamind1f287bf2018-06-12 01:57:20590 RunAuthCallback(response, std::move(auth_callback));
[email protected]dc5a5cf2012-09-26 02:49:30591}
592
Wez2a31b222018-06-07 22:07:15593void BlockingNetworkDelegate::OnBlocked() {
594 // If this fails due to |on_blocked_| being null then OnBlocked() was run by
595 // a RunLoop other than RunUntilBlocked(), indicating a bug in the calling
596 // test.
597 std::move(on_blocked_).Run();
598}
599
[email protected]dc5a5cf2012-09-26 02:49:30600void BlockingNetworkDelegate::RunCallback(int response,
David Benjamind1f287bf2018-06-12 01:57:20601 CompletionOnceCallback callback) {
602 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30603}
604
605void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
David Benjamind1f287bf2018-06-12 01:57:20606 AuthCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30607 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
Raul Tambre94493c652019-03-11 17:18:35608 ASSERT_TRUE(target_auth_credentials_ != nullptr);
[email protected]dc5a5cf2012-09-26 02:49:30609 *target_auth_credentials_ = auth_credentials_;
610 }
David Benjamind1f287bf2018-06-12 01:57:20611 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30612}
613
David Benjamind1f287bf2018-06-12 01:57:20614int BlockingNetworkDelegate::OnBeforeURLRequest(URLRequest* request,
615 CompletionOnceCallback callback,
616 GURL* new_url) {
[email protected]dc5a5cf2012-09-26 02:49:30617 if (redirect_url_ == request->url())
618 return OK; // We've already seen this request and redirected elsewhere.
619
David Benjamind1f287bf2018-06-12 01:57:20620 // TestNetworkDelegate always completes synchronously.
621 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
622 request, base::NullCallback(), new_url));
[email protected]dc5a5cf2012-09-26 02:49:30623
624 if (!redirect_url_.is_empty())
625 *new_url = redirect_url_;
626
David Benjamind1f287bf2018-06-12 01:57:20627 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30628}
629
ryansturm2343cb62016-06-15 01:09:00630int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30631 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20632 CompletionOnceCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30633 HttpRequestHeaders* headers) {
David Benjamind1f287bf2018-06-12 01:57:20634 // TestNetworkDelegate always completes synchronously.
635 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
636 request, base::NullCallback(), headers));
[email protected]dc5a5cf2012-09-26 02:49:30637
David Benjamind1f287bf2018-06-12 01:57:20638 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30639}
640
641int BlockingNetworkDelegate::OnHeadersReceived(
642 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20643 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32644 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16645 scoped_refptr<HttpResponseHeaders>* override_response_headers,
646 GURL* allowed_unsafe_redirect_url) {
David Benjamind1f287bf2018-06-12 01:57:20647 // TestNetworkDelegate always completes synchronously.
648 CHECK_NE(ERR_IO_PENDING,
649 TestNetworkDelegate::OnHeadersReceived(
650 request, base::NullCallback(), original_response_headers,
651 override_response_headers, allowed_unsafe_redirect_url));
[email protected]dc5a5cf2012-09-26 02:49:30652
David Benjamind1f287bf2018-06-12 01:57:20653 return MaybeBlockStage(ON_HEADERS_RECEIVED, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30654}
655
656NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
657 URLRequest* request,
658 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20659 AuthCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30660 AuthCredentials* credentials) {
David Benjamind1f287bf2018-06-12 01:57:20661 // TestNetworkDelegate always completes synchronously.
662 CHECK_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING,
663 TestNetworkDelegate::OnAuthRequired(
664 request, auth_info, base::NullCallback(), credentials));
[email protected]dc5a5cf2012-09-26 02:49:30665 // Check that the user has provided callback for the previous blocked stage.
666 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
667
668 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
669 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
670 }
671
672 target_auth_credentials_ = credentials;
673
674 switch (block_mode_) {
675 case SYNCHRONOUS:
676 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
677 *target_auth_credentials_ = auth_credentials_;
678 return auth_retval_;
679
680 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45681 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20682 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunAuthCallback,
683 weak_factory_.GetWeakPtr(), auth_retval_,
684 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30685 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
686
687 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20688 auth_callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30689 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
Wez2a31b222018-06-07 22:07:15690 // We may reach here via a callback prior to RunUntilBlocked(), so post
691 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45692 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15693 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
694 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30695 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
696 }
697 NOTREACHED();
698 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
699}
700
701void BlockingNetworkDelegate::Reset() {
702 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
703 stage_blocked_for_callback_ = NOT_BLOCKED;
704 callback_.Reset();
705 auth_callback_.Reset();
706}
707
708int BlockingNetworkDelegate::MaybeBlockStage(
709 BlockingNetworkDelegate::Stage stage,
David Benjamind1f287bf2018-06-12 01:57:20710 CompletionOnceCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30711 // Check that the user has provided callback for the previous blocked stage.
712 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
713
714 if ((block_on_ & stage) == 0) {
715 return OK;
716 }
717
718 switch (block_mode_) {
719 case SYNCHRONOUS:
720 EXPECT_NE(OK, retval_);
721 return retval_;
722
723 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45724 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20725 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
726 weak_factory_.GetWeakPtr(), retval_,
727 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30728 return ERR_IO_PENDING;
729
730 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20731 callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30732 stage_blocked_for_callback_ = stage;
Wez2a31b222018-06-07 22:07:15733 // We may reach here via a callback prior to RunUntilBlocked(), so post
734 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45735 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15736 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
737 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30738 return ERR_IO_PENDING;
739 }
740 NOTREACHED();
741 return 0;
742}
743
[email protected]d5a4dd62012-05-23 01:41:04744class TestURLRequestContextWithProxy : public TestURLRequestContext {
745 public:
746 // Does not own |delegate|.
747 TestURLRequestContextWithProxy(const std::string& proxy,
748 NetworkDelegate* delegate)
749 : TestURLRequestContext(true) {
Lily Houghton8c2f97d2018-01-22 05:06:59750 context_storage_.set_proxy_resolution_service(
Ramin Halavatica8d5252018-03-12 05:33:49751 ProxyResolutionService::CreateFixed(proxy,
752 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]d5a4dd62012-05-23 01:41:04753 set_network_delegate(delegate);
754 Init();
755 }
Chris Watkins7a41d3552017-12-01 02:13:27756 ~TestURLRequestContextWithProxy() override = default;
[email protected]d5a4dd62012-05-23 01:41:04757};
758
stefanocsbd5be5202016-06-10 03:37:55759// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01760// URI and report to be sent.
761class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55762 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01763 public:
Chris Watkins7a41d3552017-12-01 02:13:27764 MockCertificateReportSender() = default;
765 ~MockCertificateReportSender() override = default;
estark06e0dac2015-08-07 21:56:01766
meacer5d4dc5a2017-04-27 20:37:48767 void Send(const GURL& report_uri,
768 base::StringPiece content_type,
769 base::StringPiece report,
770 const base::Callback<void()>& success_callback,
771 const base::Callback<void(const GURL&, int, int)>& error_callback)
772 override {
estark06e0dac2015-08-07 21:56:01773 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44774 report.CopyToString(&latest_report_);
775 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01776 }
estark06e0dac2015-08-07 21:56:01777 const GURL& latest_report_uri() { return latest_report_uri_; }
778 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44779 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01780
781 private:
782 GURL latest_report_uri_;
783 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44784 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01785};
786
dadrian612337a2016-07-20 22:36:58787// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
788// This is needed because after the certificate failure, the URLRequest will
789// retry the connection, and return a partial SSLInfo with a cached cert status.
790// The partial SSLInfo does not have the OCSP information filled out.
791class OCSPErrorTestDelegate : public TestDelegate {
792 public:
793 void OnSSLCertificateError(URLRequest* request,
794 const SSLInfo& ssl_info,
795 bool fatal) override {
796 ssl_info_ = ssl_info;
797 on_ssl_certificate_error_called_ = true;
798 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
799 }
800
801 bool on_ssl_certificate_error_called() {
802 return on_ssl_certificate_error_called_;
803 }
804
805 SSLInfo ssl_info() { return ssl_info_; }
806
807 private:
808 bool on_ssl_certificate_error_called_ = false;
809 SSLInfo ssl_info_;
810};
811
[email protected]d5a4dd62012-05-23 01:41:04812} // namespace
813
[email protected]a592c0432012-12-01 18:10:29814// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
Bence Béky98447b12018-05-08 03:14:01815class URLRequestTest : public PlatformTest, public WithScopedTaskEnvironment {
[email protected]abb26092010-11-11 22:19:00816 public:
Ryan Sleevib8449e02018-07-15 04:31:07817 URLRequestTest()
818 : default_context_(std::make_unique<TestURLRequestContext>(true)) {
819 default_context_->set_network_delegate(&default_network_delegate_);
820 default_context_->set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50821 job_factory_impl_ = new URLRequestJobFactoryImpl();
822 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50823 }
bengr1bf8e942014-11-07 01:36:50824
dcheng67be2b1f2014-10-27 21:47:29825 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18826 // URLRequestJobs may post clean-up tasks on destruction.
827 base::RunLoop().RunUntilIdle();
Martijn Croonenb1383da2017-10-11 11:56:35828
829 SetTransportSecurityStateSourceForTesting(nullptr);
[email protected]e4034ad2013-09-20 08:36:18830 }
[email protected]87a09a92011-07-14 15:50:50831
dcheng2339883c2014-12-23 00:23:05832 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50833 SetUpFactory();
Ryan Sleevib8449e02018-07-15 04:31:07834 default_context_->set_job_factory(job_factory_.get());
835 default_context_->Init();
bengr1bf8e942014-11-07 01:36:50836 PlatformTest::SetUp();
837 }
838
Ryan Sleevib8449e02018-07-15 04:31:07839 void TearDown() override { default_context_.reset(); }
840
bengr1bf8e942014-11-07 01:36:50841 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20842 job_factory_impl_->SetProtocolHandler(
Bence Béky8f9d7d3952017-10-09 19:58:04843 "data", std::make_unique<DataProtocolHandler>());
brettwa1228ebb2016-10-28 03:51:34844#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50845 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19846 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07847 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50848#endif
849 }
850
851 TestNetworkDelegate* default_network_delegate() {
852 return &default_network_delegate_;
853 }
854
Ryan Sleevib8449e02018-07-15 04:31:07855 TestURLRequestContext& default_context() const { return *default_context_; }
bengr1bf8e942014-11-07 01:36:50856
[email protected]3c5ca8c2011-09-29 01:14:51857 // Adds the TestJobInterceptor to the default context.
858 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23859 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20860 job_factory_impl_->SetProtocolHandler("http", nullptr);
861 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36862 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23863 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51864 }
865
Sergey Ulanov2e49f492017-09-14 19:37:51866 // Creates a temp test file and writes |data| to the file. The file will be
867 // deleted after the test completes.
868 void CreateTestFile(const char* data,
869 size_t data_size,
870 base::FilePath* test_file) {
871 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
872 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
873 // now, Mac and Android bots return a path with a symbolic link.
874 base::FilePath absolute_temp_dir =
875 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
876
877 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
878 ASSERT_EQ(static_cast<int>(data_size),
879 base::WriteFile(*test_file, data, data_size));
880 }
881
[email protected]87a09a92011-07-14 15:50:50882 protected:
vishal.b62985ca92015-04-17 08:45:51883 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24884 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50885 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36886 std::unique_ptr<URLRequestJobFactory> job_factory_;
Ryan Sleevib8449e02018-07-15 04:31:07887 std::unique_ptr<TestURLRequestContext> default_context_;
Sergey Ulanov2e49f492017-09-14 19:37:51888 base::ScopedTempDir temp_dir_;
[email protected]7a0bb4bf2008-11-19 21:41:48889};
890
satoruxddac0442017-05-29 06:06:18891// This NetworkDelegate is picky about what files are accessible. Only
892// whitelisted files are allowed.
893class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
894 public:
Chris Watkins7a41d3552017-12-01 02:13:27895 CookieBlockingNetworkDelegate() = default;
satoruxddac0442017-05-29 06:06:18896
897 // Adds |directory| to the access white list.
898 void AddToWhitelist(const base::FilePath& directory) {
899 whitelist_.insert(directory);
900 }
901
902 private:
903 // Returns true if |path| matches the white list.
904 bool OnCanAccessFileInternal(const base::FilePath& path) const {
905 for (const auto& directory : whitelist_) {
906 if (directory == path || directory.IsParent(path))
907 return true;
908 }
909 return false;
910 }
911
912 // Returns true only if both |original_path| and |absolute_path| match the
913 // white list.
914 bool OnCanAccessFile(const URLRequest& request,
915 const base::FilePath& original_path,
916 const base::FilePath& absolute_path) const override {
917 return (OnCanAccessFileInternal(original_path) &&
918 OnCanAccessFileInternal(absolute_path));
919 }
920
921 std::set<base::FilePath> whitelist_;
922
923 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
924};
925
[email protected]316c1e5e2012-09-12 15:17:44926TEST_F(URLRequestTest, AboutBlankTest) {
927 TestDelegate d;
928 {
rhalavatib7bd7c792017-04-27 05:25:16929 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:07930 default_context().CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
931 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44932
[email protected]f7022f32014-08-21 16:32:19933 r->Start();
934 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44935
Wez2a31b222018-06-07 22:07:15936 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44937
[email protected]f7022f32014-08-21 16:32:19938 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44939 EXPECT_FALSE(d.received_data_before_response());
940 EXPECT_EQ(d.bytes_received(), 0);
Tsuyoshi Horo01faed62019-02-20 22:11:37941 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
942 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04943
944 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19945 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44946 }
947}
948
949TEST_F(URLRequestTest, DataURLImageTest) {
950 TestDelegate d;
951 {
952 // Use our nice little Chrome logo.
Ryan Sleevib8449e02018-07-15 04:31:07953 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
danakj8522a25b2016-04-16 00:17:36954 GURL("data:image/png;base64,"
955 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
956 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
957 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
958 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
959 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
960 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
961 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
962 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
963 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
964 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
965 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
966 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
967 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
968 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
969 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
970 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
971 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
972 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
973 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16974 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44975
[email protected]f7022f32014-08-21 16:32:19976 r->Start();
977 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44978
Wez2a31b222018-06-07 22:07:15979 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44980
[email protected]f7022f32014-08-21 16:32:19981 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44982 EXPECT_FALSE(d.received_data_before_response());
983 EXPECT_EQ(d.bytes_received(), 911);
Tsuyoshi Horo01faed62019-02-20 22:11:37984 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
985 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04986
987 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19988 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44989 }
990}
991
brettwa1228ebb2016-10-28 03:51:34992#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44993TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51994 const char kTestFileContent[] = "Hello";
995 base::FilePath test_file;
996 ASSERT_NO_FATAL_FAILURE(
997 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04998
Sergey Ulanov2e49f492017-09-14 19:37:51999 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441000
1001 TestDelegate d;
1002 {
Ryan Sleevib8449e02018-07-15 04:31:071003 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511004 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441005
[email protected]f7022f32014-08-21 16:32:191006 r->Start();
1007 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441008
Wez2a31b222018-06-07 22:07:151009 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441010
[email protected]f7022f32014-08-21 16:32:191011 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441012 EXPECT_EQ(1, d.response_started_count());
1013 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:511014 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
Tsuyoshi Horo01faed62019-02-20 22:11:371015 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
1016 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:041017
1018 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:191019 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:441020 }
1021}
1022
[email protected]ba40bb762012-12-17 07:11:041023TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:511024 const char kTestFileContent[] = "Hello";
1025 base::FilePath test_file;
1026 ASSERT_NO_FATAL_FAILURE(
1027 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
1028
1029 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:041030
1031 TestDelegate d;
1032 {
Ryan Sleevib8449e02018-07-15 04:31:071033 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511034 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:041035
[email protected]f7022f32014-08-21 16:32:191036 r->Start();
1037 EXPECT_TRUE(r->is_pending());
1038 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:041039 }
[email protected]79e1fd62013-06-20 06:50:041040 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:041041 // destroyed.
[email protected]255620da2013-08-19 13:14:291042 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041043}
1044
[email protected]316c1e5e2012-09-12 15:17:441045TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1046 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361047 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441048 FillBuffer(buffer.get(), buffer_size);
1049
Sergey Ulanov2e49f492017-09-14 19:37:511050 base::FilePath test_file;
1051 ASSERT_NO_FATAL_FAILURE(
1052 CreateTestFile(buffer.get(), buffer_size, &test_file));
1053 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441054
1055 const size_t first_byte_position = 500;
1056 const size_t last_byte_position = buffer_size - first_byte_position;
1057 const size_t content_length = last_byte_position - first_byte_position + 1;
1058 std::string partial_buffer_string(buffer.get() + first_byte_position,
1059 buffer.get() + last_byte_position + 1);
1060
1061 TestDelegate d;
1062 {
Ryan Sleevib8449e02018-07-15 04:31:071063 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161064 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441065
1066 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381067 headers.SetHeader(
1068 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591069 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381070 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191071 r->SetExtraRequestHeaders(headers);
1072 r->Start();
1073 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441074
Wez2a31b222018-06-07 22:07:151075 d.RunUntilComplete();
1076
[email protected]f7022f32014-08-21 16:32:191077 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441078 EXPECT_EQ(1, d.response_started_count());
1079 EXPECT_FALSE(d.received_data_before_response());
1080 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1081 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1082 EXPECT_TRUE(partial_buffer_string == d.data_received());
1083 }
[email protected]316c1e5e2012-09-12 15:17:441084}
1085
1086TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1087 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361088 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441089 FillBuffer(buffer.get(), buffer_size);
1090
Sergey Ulanov2e49f492017-09-14 19:37:511091 base::FilePath test_file;
1092 ASSERT_NO_FATAL_FAILURE(
1093 CreateTestFile(buffer.get(), buffer_size, &test_file));
1094 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441095
1096 const size_t first_byte_position = 500;
1097 const size_t last_byte_position = buffer_size - 1;
1098 const size_t content_length = last_byte_position - first_byte_position + 1;
1099 std::string partial_buffer_string(buffer.get() + first_byte_position,
1100 buffer.get() + last_byte_position + 1);
1101
1102 TestDelegate d;
1103 {
Ryan Sleevib8449e02018-07-15 04:31:071104 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161105 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441106
1107 HttpRequestHeaders headers;
1108 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591109 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381110 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191111 r->SetExtraRequestHeaders(headers);
1112 r->Start();
1113 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441114
[email protected]255620da2013-08-19 13:14:291115 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191116 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441117 EXPECT_EQ(1, d.response_started_count());
1118 EXPECT_FALSE(d.received_data_before_response());
1119 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1120 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1121 EXPECT_TRUE(partial_buffer_string == d.data_received());
1122 }
[email protected]316c1e5e2012-09-12 15:17:441123}
1124
1125TEST_F(URLRequestTest, FileTestMultipleRanges) {
1126 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361127 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441128 FillBuffer(buffer.get(), buffer_size);
1129
Sergey Ulanov2e49f492017-09-14 19:37:511130 base::FilePath test_file;
1131 ASSERT_NO_FATAL_FAILURE(
1132 CreateTestFile(buffer.get(), buffer_size, &test_file));
1133 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441134
1135 TestDelegate d;
1136 {
Ryan Sleevib8449e02018-07-15 04:31:071137 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161138 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441139
1140 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381141 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191142 r->SetExtraRequestHeaders(headers);
1143 r->Start();
1144 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441145
Wez2a31b222018-06-07 22:07:151146 d.RunUntilComplete();
1147
[email protected]316c1e5e2012-09-12 15:17:441148 EXPECT_TRUE(d.request_failed());
1149 }
[email protected]316c1e5e2012-09-12 15:17:441150}
1151
[email protected]3ca8b362013-11-11 22:18:071152TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511153 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071154 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511155 ASSERT_NO_FATAL_FAILURE(
1156 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1157
satoruxddac0442017-05-29 06:06:181158 // The directory part of the path returned from CreateTemporaryFileInDir()
1159 // can be slightly different from |absolute_temp_dir| on Windows.
1160 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1161 // Hence the test should use the directory name of |test_file|, rather than
1162 // |absolute_temp_dir|, for whitelisting.
1163 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591164 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071165 {
1166 TestDelegate d;
satoruxddac0442017-05-29 06:06:181167 CookieBlockingNetworkDelegate network_delegate;
1168 network_delegate.AddToWhitelist(real_temp_dir);
Ryan Sleevib8449e02018-07-15 04:31:071169 default_context().set_network_delegate(&network_delegate);
1170 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161171 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191172 r->Start();
Wez2a31b222018-06-07 22:07:151173 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181174 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071175 EXPECT_FALSE(d.request_failed());
1176 EXPECT_EQ(test_data, d.data_received());
1177 }
1178
1179 {
1180 TestDelegate d;
satoruxddac0442017-05-29 06:06:181181 CookieBlockingNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:071182 default_context().set_network_delegate(&network_delegate);
1183 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161184 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191185 r->Start();
Wez2a31b222018-06-07 22:07:151186 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181187 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071188 EXPECT_TRUE(d.request_failed());
1189 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181190 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071191 }
1192}
1193
Wez35539132018-07-17 11:26:051194#if defined(OS_POSIX) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181195
1196TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511197 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181198 // Get an absolute path since temp_dir can contain a symbolic link.
1199 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511200 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181201
1202 // Create a good directory (will be whitelisted) and a good file.
1203 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1204 ASSERT_TRUE(base::CreateDirectory(good_dir));
1205 base::FilePath good_file;
1206 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1207 std::string good_data("good");
1208 base::WriteFile(good_file, good_data.data(), good_data.size());
1209 // See the comment in AllowFileURLs() for why this is done.
1210 base::FilePath real_good_dir = good_file.DirName();
1211
1212 // Create a bad directory (will not be whitelisted) and a bad file.
1213 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1214 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1215 base::FilePath bad_file;
1216 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1217 std::string bad_data("bad");
1218 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1219
1220 // This symlink will point to the good file. Access to the symlink will be
1221 // allowed as both the symlink and the destination file are in the same
1222 // good directory.
1223 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1224 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1225 GURL good_file_url = FilePathToFileURL(good_symlink);
1226 // This symlink will point to the bad file. Even though the symlink is in
1227 // the good directory, access to the symlink will be rejected since it
1228 // points to the bad file.
1229 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1230 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1231 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1232
1233 CookieBlockingNetworkDelegate network_delegate;
1234 network_delegate.AddToWhitelist(real_good_dir);
1235 {
1236 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071237 default_context().set_network_delegate(&network_delegate);
1238 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371239 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181240 r->Start();
Wez2a31b222018-06-07 22:07:151241 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181242 // good_file_url should be allowed.
1243 EXPECT_FALSE(d.request_failed());
1244 EXPECT_EQ(good_data, d.data_received());
1245 }
1246
1247 {
1248 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071249 default_context().set_network_delegate(&network_delegate);
1250 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371251 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181252 r->Start();
Wez2a31b222018-06-07 22:07:151253 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181254 // bad_file_url should be rejected.
1255 EXPECT_TRUE(d.request_failed());
1256 EXPECT_EQ("", d.data_received());
1257 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1258 }
1259}
1260
1261TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511262 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181263 // Get an absolute path since temp_dir can contain a symbolic link.
1264 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511265 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181266
1267 // Create a good directory (will be whitelisted).
1268 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1269 ASSERT_TRUE(base::CreateDirectory(good_dir));
1270
1271 // Create a bad directory (will not be whitelisted).
1272 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1273 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1274
1275 // This symlink will point to the good directory. Access to the symlink
1276 // will be allowed as the symlink is in the good dir that'll be white
1277 // listed.
1278 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1279 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1280 GURL good_file_url = FilePathToFileURL(good_symlink);
1281 // This symlink will point to the bad directory. Even though the symlink is
1282 // in the good directory, access to the symlink will be rejected since it
1283 // points to the bad directory.
1284 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1285 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1286 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1287
1288 CookieBlockingNetworkDelegate network_delegate;
1289 network_delegate.AddToWhitelist(good_dir);
1290 {
1291 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071292 default_context().set_network_delegate(&network_delegate);
1293 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371294 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181295 r->Start();
Wez2a31b222018-06-07 22:07:151296 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181297 // good_file_url should be allowed.
1298 EXPECT_FALSE(d.request_failed());
1299 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1300 }
1301
1302 {
1303 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071304 default_context().set_network_delegate(&network_delegate);
1305 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371306 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181307 r->Start();
Wez2a31b222018-06-07 22:07:151308 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181309 // bad_file_url should be rejected.
1310 EXPECT_TRUE(d.request_failed());
1311 EXPECT_EQ("", d.data_received());
1312 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1313 }
1314}
1315
Wez35539132018-07-17 11:26:051316#endif // defined(OS_POSIX)
[email protected]316c1e5e2012-09-12 15:17:441317
1318TEST_F(URLRequestTest, FileDirCancelTest) {
1319 // Put in mock resource provider.
1320 NetModule::SetResourceProvider(TestNetResourceProvider);
1321
1322 TestDelegate d;
1323 {
[email protected]6cdfd7f2013-02-08 20:40:151324 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:191325 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
[email protected]316c1e5e2012-09-12 15:17:441326 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1327 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1328
Ryan Sleevib8449e02018-07-15 04:31:071329 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161330 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1331 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191332 req->Start();
1333 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441334
1335 d.set_cancel_in_received_data_pending(true);
1336
Wez2a31b222018-06-07 22:07:151337 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441338 }
1339
1340 // Take out mock resource provider.
Raul Tambre94493c652019-03-11 17:18:351341 NetModule::SetResourceProvider(nullptr);
[email protected]316c1e5e2012-09-12 15:17:441342}
1343
[email protected]5f9581402013-10-30 13:08:321344TEST_F(URLRequestTest, FileDirOutputSanity) {
1345 // Verify the general sanity of the the output of the file:
1346 // directory lister by checking for the output of a known existing
1347 // file.
1348 const char sentinel_name[] = "filedir-sentinel";
1349
1350 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191351 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471352 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321353
1354 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161355 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071356 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1357 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191358 req->Start();
Wez2a31b222018-06-07 22:07:151359 d.RunUntilComplete();
[email protected]5f9581402013-10-30 13:08:321360
1361 // Generate entry for the sentinel file.
1362 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581363 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491364 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321365 EXPECT_GT(info.size, 0);
1366 std::string sentinel_output = GetDirectoryListingEntry(
1367 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181368 std::string(sentinel_name), false /* is_dir */, info.size,
1369
[email protected]5f9581402013-10-30 13:08:321370 info.last_modified);
1371
1372 ASSERT_LT(0, d.bytes_received());
1373 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501374 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321375 // Check for the entry generated for the "sentinel" file.
1376 const std::string& data = d.data_received();
1377 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1378}
1379
[email protected]316c1e5e2012-09-12 15:17:441380TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1381 // There is an implicit redirect when loading a file path that matches a
1382 // directory and does not end with a slash. Ensure that following such
1383 // redirects does not crash. See http://crbug.com/18686.
1384
[email protected]6cdfd7f2013-02-08 20:40:151385 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191386 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471387 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441388
1389 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161390 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071391 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1392 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191393 req->Start();
Wez2a31b222018-06-07 22:07:151394 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441395
1396 ASSERT_EQ(1, d.received_redirect_count());
1397 ASSERT_LT(0, d.bytes_received());
1398 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501399 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441400}
1401
1402#if defined(OS_WIN)
1403// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1404TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1405 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071406 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161407 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191408 req->Start();
Wez2a31b222018-06-07 22:07:151409 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441410
1411 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501412 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441413}
[email protected]5ecf7cb282014-05-11 01:49:551414#endif // defined(OS_WIN)
1415
brettwa1228ebb2016-10-28 03:51:341416#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551417
1418TEST_F(URLRequestTest, InvalidUrlTest) {
1419 TestDelegate d;
1420 {
rhalavatib7bd7c792017-04-27 05:25:161421 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:071422 default_context().CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1423 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551424
[email protected]f7022f32014-08-21 16:32:191425 r->Start();
1426 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551427
Wez2a31b222018-06-07 22:07:151428 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551429 EXPECT_TRUE(d.request_failed());
1430 }
1431}
1432
jochen0e3b3a62014-09-16 18:31:231433TEST_F(URLRequestTest, InvalidReferrerTest) {
1434 TestURLRequestContext context;
1435 TestNetworkDelegate network_delegate;
1436 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1437 context.set_network_delegate(&network_delegate);
1438 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361439 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161440 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1441 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231442 req->SetReferrer("https://somewhere.com/");
1443
1444 req->Start();
Wez2a31b222018-06-07 22:07:151445 d.RunUntilComplete();
jochen0e3b3a62014-09-16 18:31:231446 EXPECT_TRUE(d.request_failed());
1447}
1448
[email protected]5ecf7cb282014-05-11 01:49:551449#if defined(OS_WIN)
1450TEST_F(URLRequestTest, ResolveShortcutTest) {
1451 base::FilePath app_path;
Avi Drissman5c80d832018-05-01 17:01:191452 base::PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471453 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551454 app_path = app_path.AppendASCII("with-headers.html");
1455
jdoerrie6312bf62019-02-01 22:03:421456 base::string16 lnk_path = app_path.value() + FILE_PATH_LITERAL(".lnk");
[email protected]5ecf7cb282014-05-11 01:49:551457
1458 base::win::ScopedCOMInitializer com_initializer;
1459
1460 // Temporarily create a shortcut for test
1461 {
Robert Liaoc88f99d12017-10-17 21:48:331462 Microsoft::WRL::ComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161463 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
Raul Tambre94493c652019-03-11 17:18:351464 CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
Robert Liaoc88f99d12017-10-17 21:48:331465 Microsoft::WRL::ComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001466 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
jdoerriebacc1962019-02-07 13:39:221467 EXPECT_TRUE(SUCCEEDED(shell->SetPath(base::as_wcstr(app_path.value()))));
[email protected]5ecf7cb282014-05-11 01:49:551468 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
jdoerriebacc1962019-02-07 13:39:221469 EXPECT_TRUE(SUCCEEDED(persist->Save(base::as_wcstr(lnk_path), TRUE)));
[email protected]5ecf7cb282014-05-11 01:49:551470 }
1471
1472 TestDelegate d;
1473 {
Ryan Sleevib8449e02018-07-15 04:31:071474 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161475 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1476 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551477
[email protected]f7022f32014-08-21 16:32:191478 r->Start();
1479 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551480
Wez2a31b222018-06-07 22:07:151481 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551482
1483 WIN32_FILE_ATTRIBUTE_DATA data;
jdoerriebacc1962019-02-07 13:39:221484 GetFileAttributesEx(base::as_wcstr(app_path.value()), GetFileExInfoStandard,
jdoerrie6312bf62019-02-01 22:03:421485 &data);
jdoerriebacc1962019-02-07 13:39:221486 HANDLE file = CreateFile(base::as_wcstr(app_path.value()), GENERIC_READ,
Raul Tambre94493c652019-03-11 17:18:351487 FILE_SHARE_READ, nullptr, OPEN_EXISTING,
1488 FILE_ATTRIBUTE_NORMAL, nullptr);
[email protected]5ecf7cb282014-05-11 01:49:551489 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361490 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551491 DWORD read_size;
1492 BOOL result;
Raul Tambre94493c652019-03-11 17:18:351493 result =
1494 ReadFile(file, buffer.get(), data.nFileSizeLow, &read_size, nullptr);
[email protected]5ecf7cb282014-05-11 01:49:551495 std::string content(buffer.get(), read_size);
1496 CloseHandle(file);
1497
[email protected]f7022f32014-08-21 16:32:191498 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551499 EXPECT_EQ(1, d.received_redirect_count());
1500 EXPECT_EQ(content, d.data_received());
1501 }
1502
1503 // Clean the shortcut
jdoerriebacc1962019-02-07 13:39:221504 DeleteFile(base::as_wcstr(lnk_path));
[email protected]5ecf7cb282014-05-11 01:49:551505}
1506#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441507
1508// Custom URLRequestJobs for use with interceptor tests
1509class RestartTestJob : public URLRequestTestJob {
1510 public:
1511 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1512 : URLRequestTestJob(request, network_delegate, true) {}
1513 protected:
dchengb03027d2014-10-21 12:00:201514 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441515 private:
Chris Watkins7a41d3552017-12-01 02:13:271516 ~RestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441517};
1518
1519class CancelTestJob : public URLRequestTestJob {
1520 public:
1521 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1522 : URLRequestTestJob(request, network_delegate, true) {}
1523 protected:
dchengb03027d2014-10-21 12:00:201524 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441525 private:
Chris Watkins7a41d3552017-12-01 02:13:271526 ~CancelTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441527};
1528
1529class CancelThenRestartTestJob : public URLRequestTestJob {
1530 public:
1531 explicit CancelThenRestartTestJob(URLRequest* request,
1532 NetworkDelegate* network_delegate)
1533 : URLRequestTestJob(request, network_delegate, true) {
1534 }
1535 protected:
dchengb03027d2014-10-21 12:00:201536 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441537 request_->Cancel();
1538 this->NotifyRestartRequired();
1539 }
1540 private:
Chris Watkins7a41d3552017-12-01 02:13:271541 ~CancelThenRestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441542};
1543
bengr1bf8e942014-11-07 01:36:501544// An Interceptor for use with interceptor tests.
1545class MockURLRequestInterceptor : public URLRequestInterceptor {
1546 public:
1547 // Static getters for canned response header and data strings.
1548 static std::string ok_data() {
1549 return URLRequestTestJob::test_data_1();
1550 }
1551
1552 static std::string ok_headers() {
1553 return URLRequestTestJob::test_headers();
1554 }
1555
1556 static std::string redirect_data() {
1557 return std::string();
1558 }
1559
1560 static std::string redirect_headers() {
1561 return URLRequestTestJob::test_redirect_headers();
1562 }
1563
1564 static std::string error_data() {
1565 return std::string("ohhh nooooo mr. bill!");
1566 }
1567
1568 static std::string error_headers() {
1569 return URLRequestTestJob::test_error_headers();
1570 }
1571
1572 MockURLRequestInterceptor()
1573 : intercept_main_request_(false), restart_main_request_(false),
1574 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1575 simulate_main_network_error_(false),
1576 intercept_redirect_(false), cancel_redirect_request_(false),
1577 intercept_final_response_(false), cancel_final_request_(false),
1578 use_url_request_http_job_(false),
1579 did_intercept_main_(false), did_restart_main_(false),
1580 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1581 did_simulate_error_main_(false),
1582 did_intercept_redirect_(false), did_cancel_redirect_(false),
1583 did_intercept_final_(false), did_cancel_final_(false) {
1584 }
1585
Chris Watkins7a41d3552017-12-01 02:13:271586 ~MockURLRequestInterceptor() override = default;
bengr1bf8e942014-11-07 01:36:501587
1588 // URLRequestInterceptor implementation:
1589 URLRequestJob* MaybeInterceptRequest(
1590 URLRequest* request,
1591 NetworkDelegate* network_delegate) const override {
1592 if (restart_main_request_) {
1593 restart_main_request_ = false;
1594 did_restart_main_ = true;
1595 return new RestartTestJob(request, network_delegate);
1596 }
1597 if (cancel_main_request_) {
1598 cancel_main_request_ = false;
1599 did_cancel_main_ = true;
1600 return new CancelTestJob(request, network_delegate);
1601 }
1602 if (cancel_then_restart_main_request_) {
1603 cancel_then_restart_main_request_ = false;
1604 did_cancel_then_restart_main_ = true;
1605 return new CancelThenRestartTestJob(request, network_delegate);
1606 }
1607 if (simulate_main_network_error_) {
1608 simulate_main_network_error_ = false;
1609 did_simulate_error_main_ = true;
1610 if (use_url_request_http_job_) {
1611 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1612 }
1613 // This job will result in error since the requested URL is not one of the
1614 // URLs supported by these tests.
1615 return new URLRequestTestJob(request, network_delegate, true);
1616 }
1617 if (!intercept_main_request_)
1618 return nullptr;
1619 intercept_main_request_ = false;
1620 did_intercept_main_ = true;
1621 URLRequestTestJob* job = new URLRequestTestJob(request,
1622 network_delegate,
1623 main_headers_,
1624 main_data_,
1625 true);
1626 job->set_load_timing_info(main_request_load_timing_info_);
1627 return job;
1628 }
1629
1630 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1631 NetworkDelegate* network_delegate,
1632 const GURL& location) const override {
1633 if (cancel_redirect_request_) {
1634 cancel_redirect_request_ = false;
1635 did_cancel_redirect_ = true;
1636 return new CancelTestJob(request, network_delegate);
1637 }
1638 if (!intercept_redirect_)
1639 return nullptr;
1640 intercept_redirect_ = false;
1641 did_intercept_redirect_ = true;
1642 if (use_url_request_http_job_) {
1643 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1644 }
1645 return new URLRequestTestJob(request,
1646 network_delegate,
1647 redirect_headers_,
1648 redirect_data_,
1649 true);
1650 }
1651
1652 URLRequestJob* MaybeInterceptResponse(
1653 URLRequest* request,
1654 NetworkDelegate* network_delegate) const override {
1655 if (cancel_final_request_) {
1656 cancel_final_request_ = false;
1657 did_cancel_final_ = true;
1658 return new CancelTestJob(request, network_delegate);
1659 }
1660 if (!intercept_final_response_)
1661 return nullptr;
1662 intercept_final_response_ = false;
1663 did_intercept_final_ = true;
1664 if (use_url_request_http_job_) {
1665 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1666 }
1667 return new URLRequestTestJob(request,
1668 network_delegate,
1669 final_headers_,
1670 final_data_,
1671 true);
1672 }
1673
1674 void set_intercept_main_request(bool intercept_main_request) {
1675 intercept_main_request_ = intercept_main_request;
1676 }
1677
1678 void set_main_headers(const std::string& main_headers) {
1679 main_headers_ = main_headers;
1680 }
1681
1682 void set_main_data(const std::string& main_data) {
1683 main_data_ = main_data;
1684 }
1685
1686 void set_main_request_load_timing_info(
1687 const LoadTimingInfo& main_request_load_timing_info) {
1688 main_request_load_timing_info_ = main_request_load_timing_info;
1689 }
1690
1691 void set_restart_main_request(bool restart_main_request) {
1692 restart_main_request_ = restart_main_request;
1693 }
1694
1695 void set_cancel_main_request(bool cancel_main_request) {
1696 cancel_main_request_ = cancel_main_request;
1697 }
1698
1699 void set_cancel_then_restart_main_request(
1700 bool cancel_then_restart_main_request) {
1701 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1702 }
1703
1704 void set_simulate_main_network_error(bool simulate_main_network_error) {
1705 simulate_main_network_error_ = simulate_main_network_error;
1706 }
1707
1708 void set_intercept_redirect(bool intercept_redirect) {
1709 intercept_redirect_ = intercept_redirect;
1710 }
1711
1712 void set_redirect_headers(const std::string& redirect_headers) {
1713 redirect_headers_ = redirect_headers;
1714 }
1715
1716 void set_redirect_data(const std::string& redirect_data) {
1717 redirect_data_ = redirect_data;
1718 }
1719
1720 void set_cancel_redirect_request(bool cancel_redirect_request) {
1721 cancel_redirect_request_ = cancel_redirect_request;
1722 }
1723
1724 void set_intercept_final_response(bool intercept_final_response) {
1725 intercept_final_response_ = intercept_final_response;
1726 }
1727
1728 void set_final_headers(const std::string& final_headers) {
1729 final_headers_ = final_headers;
1730 }
1731
1732 void set_final_data(const std::string& final_data) {
1733 final_data_ = final_data;
1734 }
1735
1736 void set_cancel_final_request(bool cancel_final_request) {
1737 cancel_final_request_ = cancel_final_request;
1738 }
1739
1740 void set_use_url_request_http_job(bool use_url_request_http_job) {
1741 use_url_request_http_job_ = use_url_request_http_job;
1742 }
1743
1744 bool did_intercept_main() const {
1745 return did_intercept_main_;
1746 }
1747
1748 bool did_restart_main() const {
1749 return did_restart_main_;
1750 }
1751
1752 bool did_cancel_main() const {
1753 return did_cancel_main_;
1754 }
1755
1756 bool did_cancel_then_restart_main() const {
1757 return did_cancel_then_restart_main_;
1758 }
1759
1760 bool did_simulate_error_main() const {
1761 return did_simulate_error_main_;
1762 }
1763
1764 bool did_intercept_redirect() const {
1765 return did_intercept_redirect_;
1766 }
1767
1768 bool did_cancel_redirect() const {
1769 return did_cancel_redirect_;
1770 }
1771
1772 bool did_intercept_final() const {
1773 return did_intercept_final_;
1774 }
1775
1776 bool did_cancel_final() const {
1777 return did_cancel_final_;
1778 }
1779
1780 private:
1781 // Indicate whether to intercept the main request, and if so specify the
1782 // response to return and the LoadTimingInfo to use.
1783 mutable bool intercept_main_request_;
1784 mutable std::string main_headers_;
1785 mutable std::string main_data_;
1786 mutable LoadTimingInfo main_request_load_timing_info_;
1787
1788 // These indicate actions that can be taken within MaybeInterceptRequest.
1789 mutable bool restart_main_request_;
1790 mutable bool cancel_main_request_;
1791 mutable bool cancel_then_restart_main_request_;
1792 mutable bool simulate_main_network_error_;
1793
1794 // Indicate whether to intercept redirects, and if so specify the response to
1795 // return.
1796 mutable bool intercept_redirect_;
1797 mutable std::string redirect_headers_;
1798 mutable std::string redirect_data_;
1799
1800 // Cancel the request within MaybeInterceptRedirect.
1801 mutable bool cancel_redirect_request_;
1802
1803 // Indicate whether to intercept the final response, and if so specify the
1804 // response to return.
1805 mutable bool intercept_final_response_;
1806 mutable std::string final_headers_;
1807 mutable std::string final_data_;
1808
1809 // Cancel the final request within MaybeInterceptResponse.
1810 mutable bool cancel_final_request_;
1811
1812 // Instruct the interceptor to use a real URLRequestHTTPJob.
1813 mutable bool use_url_request_http_job_;
1814
1815 // These indicate if the interceptor did something or not.
1816 mutable bool did_intercept_main_;
1817 mutable bool did_restart_main_;
1818 mutable bool did_cancel_main_;
1819 mutable bool did_cancel_then_restart_main_;
1820 mutable bool did_simulate_error_main_;
1821 mutable bool did_intercept_redirect_;
1822 mutable bool did_cancel_redirect_;
1823 mutable bool did_intercept_final_;
1824 mutable bool did_cancel_final_;
1825};
1826
1827// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1828class URLRequestInterceptorTest : public URLRequestTest {
1829 public:
Raul Tambre94493c652019-03-11 17:18:351830 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:501831
1832 ~URLRequestInterceptorTest() override {
1833 // URLRequestJobs may post clean-up tasks on destruction.
1834 base::RunLoop().RunUntilIdle();
1835 }
1836
1837 void SetUpFactory() override {
1838 interceptor_ = new MockURLRequestInterceptor();
1839 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361840 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501841 }
1842
1843 MockURLRequestInterceptor* interceptor() const {
1844 return interceptor_;
1845 }
1846
1847 private:
1848 MockURLRequestInterceptor* interceptor_;
1849};
1850
1851TEST_F(URLRequestInterceptorTest, Intercept) {
1852 // Intercept the main request and respond with a simple response.
1853 interceptor()->set_intercept_main_request(true);
1854 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1855 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591856 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361857 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161858 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1859 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501860 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1861 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1862 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091863 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041864 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1865 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501866 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191867 req->Start();
Wez2a31b222018-06-07 22:07:151868 d.RunUntilComplete();
[email protected]2bba3252013-04-08 19:50:591869
bengr1bf8e942014-11-07 01:36:501870 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091871 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501872 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1873 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591874
bengr1bf8e942014-11-07 01:36:501875 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501876 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501877 EXPECT_EQ(200, req->response_headers()->response_code());
1878 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1879 EXPECT_EQ(1, d.response_started_count());
1880 EXPECT_EQ(0, d.received_redirect_count());
1881}
[email protected]2bba3252013-04-08 19:50:591882
bengr1bf8e942014-11-07 01:36:501883TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1884 // Intercept the main request and respond with a redirect.
1885 interceptor()->set_intercept_main_request(true);
1886 interceptor()->set_main_headers(
1887 MockURLRequestInterceptor::redirect_headers());
1888 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1889
1890 // Intercept that redirect and respond with a final OK response.
1891 interceptor()->set_intercept_redirect(true);
1892 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1893 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1894
1895 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361896 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161897 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1898 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501899 req->set_method("GET");
1900 req->Start();
Wez2a31b222018-06-07 22:07:151901 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501902
1903 // Check that the interceptor got called as expected.
1904 EXPECT_TRUE(interceptor()->did_intercept_main());
1905 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1906
1907 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501908 int status = d.request_status();
1909 EXPECT_EQ(OK, status);
1910 if (status == OK)
bengr1bf8e942014-11-07 01:36:501911 EXPECT_EQ(200, req->response_headers()->response_code());
1912
1913 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1914 EXPECT_EQ(1, d.response_started_count());
1915 EXPECT_EQ(0, d.received_redirect_count());
1916}
1917
1918TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1919 // Intercept the main request to generate a server error response.
1920 interceptor()->set_intercept_main_request(true);
1921 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1922 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1923
1924 // Intercept that error and respond with an OK response.
1925 interceptor()->set_intercept_final_response(true);
1926 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1927 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1928
1929 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361930 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161931 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1932 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501933 req->set_method("GET");
1934 req->Start();
Wez2a31b222018-06-07 22:07:151935 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501936
1937 // Check that the interceptor got called as expected.
1938 EXPECT_TRUE(interceptor()->did_intercept_main());
1939 EXPECT_TRUE(interceptor()->did_intercept_final());
1940
1941 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501942 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501943 EXPECT_EQ(200, req->response_headers()->response_code());
1944 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1945 EXPECT_EQ(1, d.response_started_count());
1946 EXPECT_EQ(0, d.received_redirect_count());
1947}
1948
1949TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1950 // Intercept the main request to simulate a network error.
1951 interceptor()->set_simulate_main_network_error(true);
1952
1953 // Intercept that error and respond with an OK response.
1954 interceptor()->set_intercept_final_response(true);
1955 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1956 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1957
1958 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361959 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161960 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1961 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501962 req->set_method("GET");
1963 req->Start();
Wez2a31b222018-06-07 22:07:151964 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501965
1966 // Check that the interceptor got called as expected.
1967 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1968 EXPECT_TRUE(interceptor()->did_intercept_final());
1969
1970 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501971 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501972 EXPECT_EQ(200, req->response_headers()->response_code());
1973 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1974 EXPECT_EQ(1, d.response_started_count());
1975 EXPECT_EQ(0, d.received_redirect_count());
1976}
1977
1978TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1979 // Restart the main request.
1980 interceptor()->set_restart_main_request(true);
1981
1982 // then intercept the new main request and respond with an OK response
1983 interceptor()->set_intercept_main_request(true);
1984 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1985 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1986
1987 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361988 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161989 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1990 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501991 req->set_method("GET");
1992 req->Start();
Wez2a31b222018-06-07 22:07:151993 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501994
1995 // Check that the interceptor got called as expected.
1996 EXPECT_TRUE(interceptor()->did_restart_main());
1997 EXPECT_TRUE(interceptor()->did_intercept_main());
1998
1999 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:502000 int status = d.request_status();
2001 EXPECT_EQ(OK, status);
2002 if (status == OK)
bengr1bf8e942014-11-07 01:36:502003 EXPECT_EQ(200, req->response_headers()->response_code());
2004
2005 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2006 EXPECT_EQ(1, d.response_started_count());
2007 EXPECT_EQ(0, d.received_redirect_count());
2008}
2009
2010TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
2011 // Intercept the main request and cancel from within the restarted job.
2012 interceptor()->set_cancel_main_request(true);
2013
2014 // Set up to intercept the final response and override it with an OK response.
2015 interceptor()->set_intercept_final_response(true);
2016 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2017 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2018
2019 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362020 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162021 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2022 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502023 req->set_method("GET");
2024 req->Start();
Wez2a31b222018-06-07 22:07:152025 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502026
2027 // Check that the interceptor got called as expected.
2028 EXPECT_TRUE(interceptor()->did_cancel_main());
2029 EXPECT_FALSE(interceptor()->did_intercept_final());
2030
2031 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502032 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502033}
2034
2035TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2036 // Intercept the main request and respond with a redirect.
2037 interceptor()->set_intercept_main_request(true);
2038 interceptor()->set_main_headers(
2039 MockURLRequestInterceptor::redirect_headers());
2040 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2041
2042 // Intercept the redirect and cancel from within that job.
2043 interceptor()->set_cancel_redirect_request(true);
2044
2045 // Set up to intercept the final response and override it with an OK response.
2046 interceptor()->set_intercept_final_response(true);
2047 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2048 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2049
2050 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362051 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162052 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2053 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502054 req->set_method("GET");
2055 req->Start();
Wez2a31b222018-06-07 22:07:152056 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502057
2058 // Check that the interceptor got called as expected.
2059 EXPECT_TRUE(interceptor()->did_intercept_main());
2060 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2061 EXPECT_FALSE(interceptor()->did_intercept_final());
2062
2063 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502064 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502065}
2066
2067TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2068 // Intercept the main request to simulate a network error.
2069 interceptor()->set_simulate_main_network_error(true);
2070
2071 // Set up to intercept final the response and cancel from within that job.
2072 interceptor()->set_cancel_final_request(true);
2073
2074 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362075 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162076 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2077 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502078 req->set_method("GET");
2079 req->Start();
Wez2a31b222018-06-07 22:07:152080 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502081
2082 // Check that the interceptor got called as expected.
2083 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2084 EXPECT_TRUE(interceptor()->did_cancel_final());
2085
2086 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502087 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502088}
2089
2090TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2091 // Intercept the main request and cancel then restart from within that job.
2092 interceptor()->set_cancel_then_restart_main_request(true);
2093
2094 // Set up to intercept the final response and override it with an OK response.
2095 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502096 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2097 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502098
2099 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362100 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162101 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2102 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502103 req->set_method("GET");
2104 req->Start();
Wez2a31b222018-06-07 22:07:152105 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502106
2107 // Check that the interceptor got called as expected.
2108 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2109 EXPECT_FALSE(interceptor()->did_intercept_final());
2110
2111 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502112 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592113}
2114
2115// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2116// reused. |connect_time_flags| is used to indicate if there should be dns
2117// or SSL times, and |used_proxy| is used for proxy times.
2118LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2119 int connect_time_flags,
2120 bool used_proxy) {
2121 LoadTimingInfo load_timing;
2122 load_timing.socket_log_id = 1;
2123
2124 if (used_proxy) {
2125 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2126 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2127 }
2128
2129 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2130 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2131 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2132 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2133 }
2134 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2135 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2136 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2137 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2138 }
2139 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2140
2141 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2142 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382143 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2144 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592145 return load_timing;
2146}
2147
2148// Same as above, but in the case of a reused socket.
2149LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2150 bool used_proxy) {
2151 LoadTimingInfo load_timing;
2152 load_timing.socket_log_id = 1;
2153 load_timing.socket_reused = true;
2154
2155 if (used_proxy) {
2156 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2157 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2158 }
2159
2160 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2161 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382162 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2163 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592164 return load_timing;
2165}
2166
bengr1bf8e942014-11-07 01:36:502167LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2168 const LoadTimingInfo& job_load_timing,
2169 const URLRequestContext& context,
2170 MockURLRequestInterceptor* interceptor) {
2171 interceptor->set_intercept_main_request(true);
2172 interceptor->set_main_request_load_timing_info(job_load_timing);
2173 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162174 std::unique_ptr<URLRequest> req(
2175 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2176 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502177 req->Start();
Wez2a31b222018-06-07 22:07:152178 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502179
2180 LoadTimingInfo resulting_load_timing;
2181 req->GetLoadTimingInfo(&resulting_load_timing);
2182
2183 // None of these should be modified by the URLRequest.
2184 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2185 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2186 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2187 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382188 EXPECT_EQ(job_load_timing.receive_headers_start,
2189 resulting_load_timing.receive_headers_start);
bengr1bf8e942014-11-07 01:36:502190 EXPECT_EQ(job_load_timing.receive_headers_end,
2191 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572192 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2193 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502194
2195 return resulting_load_timing;
2196}
2197
[email protected]2bba3252013-04-08 19:50:592198// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502199TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592200 base::TimeTicks now = base::TimeTicks::Now();
2201 LoadTimingInfo job_load_timing =
2202 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2203
[email protected]2ca01e52013-10-31 22:05:192204 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502205 RunURLRequestInterceptorLoadTimingTest(
2206 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592207
2208 // Nothing should have been changed by the URLRequest.
2209 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2210 load_timing_result.proxy_resolve_start);
2211 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2212 load_timing_result.proxy_resolve_end);
2213 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2214 load_timing_result.connect_timing.dns_start);
2215 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2216 load_timing_result.connect_timing.dns_end);
2217 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2218 load_timing_result.connect_timing.connect_start);
2219 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2220 load_timing_result.connect_timing.connect_end);
2221 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2222 load_timing_result.connect_timing.ssl_start);
2223 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2224 load_timing_result.connect_timing.ssl_end);
2225
2226 // Redundant sanity check.
2227 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2228}
2229
2230// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502231TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592232 base::TimeTicks now = base::TimeTicks::Now();
2233 LoadTimingInfo job_load_timing =
2234 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2235
[email protected]2ca01e52013-10-31 22:05:192236 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502237 RunURLRequestInterceptorLoadTimingTest(
2238 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592239
2240 // Nothing should have been changed by the URLRequest.
2241 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2242 load_timing_result.proxy_resolve_start);
2243 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2244 load_timing_result.proxy_resolve_end);
2245 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2246 load_timing_result.connect_timing.dns_start);
2247 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2248 load_timing_result.connect_timing.dns_end);
2249 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2250 load_timing_result.connect_timing.connect_start);
2251 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2252 load_timing_result.connect_timing.connect_end);
2253 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2254 load_timing_result.connect_timing.ssl_start);
2255 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2256 load_timing_result.connect_timing.ssl_end);
2257
2258 // Redundant sanity check.
2259 TestLoadTimingNotReusedWithProxy(load_timing_result,
2260 CONNECT_TIMING_HAS_SSL_TIMES);
2261}
2262
2263// Make sure that URLRequest correctly adjusts proxy times when they're before
2264// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102265// the case of reusing a SPDY session. The connected socket is not considered
2266// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592267//
2268// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502269TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592270 base::TimeTicks now = base::TimeTicks::Now();
2271 LoadTimingInfo job_load_timing =
2272 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2273 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2274 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2275 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2276 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2277 job_load_timing.connect_timing.connect_start =
2278 now - base::TimeDelta::FromDays(2);
2279 job_load_timing.connect_timing.connect_end =
2280 now - base::TimeDelta::FromDays(1);
2281
[email protected]2ca01e52013-10-31 22:05:192282 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502283 RunURLRequestInterceptorLoadTimingTest(
2284 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592285
2286 // Proxy times, connect times, and DNS times should all be replaced with
2287 // request_start.
2288 EXPECT_EQ(load_timing_result.request_start,
2289 load_timing_result.proxy_resolve_start);
2290 EXPECT_EQ(load_timing_result.request_start,
2291 load_timing_result.proxy_resolve_end);
2292 EXPECT_EQ(load_timing_result.request_start,
2293 load_timing_result.connect_timing.dns_start);
2294 EXPECT_EQ(load_timing_result.request_start,
2295 load_timing_result.connect_timing.dns_end);
2296 EXPECT_EQ(load_timing_result.request_start,
2297 load_timing_result.connect_timing.connect_start);
2298 EXPECT_EQ(load_timing_result.request_start,
2299 load_timing_result.connect_timing.connect_end);
2300
2301 // Other times should have been left null.
2302 TestLoadTimingNotReusedWithProxy(load_timing_result,
2303 CONNECT_TIMING_HAS_DNS_TIMES);
2304}
2305
2306// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502307TEST_F(URLRequestInterceptorTest,
2308 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592309 base::TimeTicks now = base::TimeTicks::Now();
2310 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2311 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2312 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2313
[email protected]2ca01e52013-10-31 22:05:192314 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502315 RunURLRequestInterceptorLoadTimingTest(
2316 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592317
2318 // Proxy times and connect times should all be replaced with request_start.
2319 EXPECT_EQ(load_timing_result.request_start,
2320 load_timing_result.proxy_resolve_start);
2321 EXPECT_EQ(load_timing_result.request_start,
2322 load_timing_result.proxy_resolve_end);
2323
2324 // Other times should have been left null.
2325 TestLoadTimingReusedWithProxy(load_timing_result);
2326}
2327
2328// Make sure that URLRequest correctly adjusts connect times when they're before
2329// |request_start|, due to reusing a connected socket. The connected socket is
2330// not considered reused in this test (May be a preconnect).
2331//
2332// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502333TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592334 base::TimeTicks now = base::TimeTicks::Now();
2335 LoadTimingInfo job_load_timing =
2336 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2337 job_load_timing.connect_timing.connect_start =
2338 now - base::TimeDelta::FromDays(1);
2339 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2340 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2341 job_load_timing.connect_timing.connect_end =
2342 now - base::TimeDelta::FromDays(4);
2343
[email protected]2ca01e52013-10-31 22:05:192344 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502345 RunURLRequestInterceptorLoadTimingTest(
2346 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592347
2348 // Connect times, and SSL times should be replaced with request_start.
2349 EXPECT_EQ(load_timing_result.request_start,
2350 load_timing_result.connect_timing.connect_start);
2351 EXPECT_EQ(load_timing_result.request_start,
2352 load_timing_result.connect_timing.ssl_start);
2353 EXPECT_EQ(load_timing_result.request_start,
2354 load_timing_result.connect_timing.ssl_end);
2355 EXPECT_EQ(load_timing_result.request_start,
2356 load_timing_result.connect_timing.connect_end);
2357
2358 // Other times should have been left null.
2359 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2360}
2361
2362// Make sure that URLRequest correctly adjusts connect times when they're before
2363// |request_start|, due to reusing a connected socket in the case that there
2364// are also proxy times. The connected socket is not considered reused in this
2365// test (May be a preconnect).
2366//
2367// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502368TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592369 base::TimeTicks now = base::TimeTicks::Now();
2370 LoadTimingInfo job_load_timing =
2371 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2372 job_load_timing.connect_timing.connect_start =
2373 now - base::TimeDelta::FromDays(1);
2374 job_load_timing.connect_timing.connect_end =
2375 now - base::TimeDelta::FromDays(2);
2376
[email protected]2ca01e52013-10-31 22:05:192377 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502378 RunURLRequestInterceptorLoadTimingTest(
2379 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592380
2381 // Connect times should be replaced with proxy_resolve_end.
2382 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2383 load_timing_result.connect_timing.connect_start);
2384 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2385 load_timing_result.connect_timing.connect_end);
2386
2387 // Other times should have been left null.
2388 TestLoadTimingNotReusedWithProxy(load_timing_result,
2389 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2390}
2391
[email protected]316c1e5e2012-09-12 15:17:442392// Check that two different URL requests have different identifiers.
2393TEST_F(URLRequestTest, Identifiers) {
2394 TestDelegate d;
2395 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362396 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162397 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2398 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362399 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162400 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2401 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442402
mmenke19378d22014-09-09 04:12:592403 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442404}
2405
blundellb8163592f2015-12-16 14:22:422406#if defined(OS_IOS)
2407// TODO(droger): Check that a failure to connect to the proxy is reported to
2408// the network delegate. crbug.com/496743
2409#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2410#else
2411#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2412#endif
2413TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442414 MockHostResolver host_resolver;
2415 host_resolver.rules()->AddSimulatedFailure("*");
2416
[email protected]ceefd7fd2012-11-29 00:36:242417 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442418 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2419
2420 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362421 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162422 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2423 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192424 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442425
[email protected]f7022f32014-08-21 16:32:192426 req->Start();
Wez2a31b222018-06-07 22:07:152427 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442428
2429 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152430 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472431 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502432 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442433
2434 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012435 EXPECT_THAT(network_delegate.last_error(),
2436 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442437 EXPECT_EQ(1, network_delegate.completed_requests());
2438}
2439
[email protected]cba24642014-08-15 20:49:592440// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442441// content is empty.
2442TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2443 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072444 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162445 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192446 req->Start();
Wez2a31b222018-06-07 22:07:152447 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442448 EXPECT_EQ("", d.data_received());
2449 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2450}
2451
[email protected]5033ab82013-03-22 20:17:462452// Make sure that SetPriority actually sets the URLRequest's priority
2453// correctly, both before and after start.
2454TEST_F(URLRequestTest, SetPriorityBasic) {
2455 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072456 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162457 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2458 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192459 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462460
[email protected]f7022f32014-08-21 16:32:192461 req->SetPriority(LOW);
2462 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462463
[email protected]f7022f32014-08-21 16:32:192464 req->Start();
2465 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462466
[email protected]f7022f32014-08-21 16:32:192467 req->SetPriority(MEDIUM);
2468 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462469}
2470
2471// Make sure that URLRequest calls SetPriority on a job before calling
2472// Start on it.
2473TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2474 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072475 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162476 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2477 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192478 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462479
mmenkeed0498b2015-12-08 23:20:422480 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362481 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422482 req.get(), &default_network_delegate_, &job_priority));
2483 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2484 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462485
[email protected]f7022f32014-08-21 16:32:192486 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462487
[email protected]f7022f32014-08-21 16:32:192488 req->Start();
mmenkeed0498b2015-12-08 23:20:422489 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462490}
2491
2492// Make sure that URLRequest passes on its priority updates to its
2493// job.
2494TEST_F(URLRequestTest, SetJobPriority) {
2495 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072496 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162497 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2498 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462499
mmenkeed0498b2015-12-08 23:20:422500 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362501 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422502 req.get(), &default_network_delegate_, &job_priority));
2503 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462504
[email protected]f7022f32014-08-21 16:32:192505 req->SetPriority(LOW);
2506 req->Start();
mmenkeed0498b2015-12-08 23:20:422507 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462508
[email protected]f7022f32014-08-21 16:32:192509 req->SetPriority(MEDIUM);
2510 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422511 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462512}
2513
[email protected]bb1c4662013-11-14 00:00:072514// Setting the IGNORE_LIMITS load flag should be okay if the priority
2515// is MAXIMUM_PRIORITY.
2516TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2517 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072518 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162519 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2520 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192521 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072522
mmenkeed0498b2015-12-08 23:20:422523 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362524 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422525 req.get(), &default_network_delegate_, &job_priority));
2526 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072527
[email protected]f7022f32014-08-21 16:32:192528 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2529 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072530
[email protected]f7022f32014-08-21 16:32:192531 req->SetPriority(MAXIMUM_PRIORITY);
2532 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072533
[email protected]f7022f32014-08-21 16:32:192534 req->Start();
2535 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422536 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072537}
2538
nick5d570de92015-05-04 20:16:162539namespace {
2540
2541// Less verbose way of running a simple testserver for the tests below.
David Benjamin42116f62017-11-20 21:45:392542class HttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442543 public:
David Benjamin42116f62017-11-20 21:45:392544 explicit HttpTestServer(const base::FilePath& document_root) {
tommycli59a63432015-11-06 00:10:552545 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272546 }
tommycli59a63432015-11-06 00:10:552547
David Benjamin42116f62017-11-20 21:45:392548 HttpTestServer() { AddDefaultHandlers(base::FilePath()); }
tommycli59a63432015-11-06 00:10:552549};
tommyclieae5f75f2015-11-05 19:07:272550
nick5d570de92015-05-04 20:16:162551} // namespace
2552
[email protected]f2f31b32013-01-16 23:24:092553TEST_F(URLRequestTest, DelayedCookieCallback) {
David Benjamin42116f62017-11-20 21:45:392554 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442555 ASSERT_TRUE(test_server.Start());
2556
2557 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362558 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502559 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442560
2561 // Set up a cookie.
2562 {
2563 TestNetworkDelegate network_delegate;
2564 context.set_network_delegate(&network_delegate);
2565 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362566 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552567 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162568 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192569 req->Start();
Wez2a31b222018-06-07 22:07:152570 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442571 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2572 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2573 EXPECT_EQ(1, network_delegate.set_cookie_count());
2574 }
2575
2576 // Verify that the cookie is set.
2577 {
2578 TestNetworkDelegate network_delegate;
2579 context.set_network_delegate(&network_delegate);
2580 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362581 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162582 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2583 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192584 req->Start();
Wez2a31b222018-06-07 22:07:152585 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442586
2587 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2588 != std::string::npos);
2589 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2590 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2591 }
2592}
2593
Aaron Tagliaboschi028009e2019-03-07 16:28:062594class FilteringTestLayeredNetworkDelegate : public LayeredNetworkDelegate {
2595 public:
2596 FilteringTestLayeredNetworkDelegate(
2597 std::unique_ptr<NetworkDelegate> network_delegate)
2598 : LayeredNetworkDelegate(std::move((network_delegate))),
2599 set_cookie_called_count_(0),
2600 blocked_set_cookie_count_(0) {}
2601 ~FilteringTestLayeredNetworkDelegate() override = default;
2602
2603 bool OnCanSetCookieInternal(const URLRequest& request,
2604 const net::CanonicalCookie& cookie,
2605 CookieOptions* options,
2606 bool allowed_from_caller) override {
2607 // Filter out cookies with the same name as |cookie_name_filter_| and
2608 // combine with |allowed_from_caller|.
2609 bool allowed =
2610 allowed_from_caller && !(cookie.Name() == cookie_name_filter_);
2611
2612 ++set_cookie_called_count_;
2613
2614 if (!allowed)
2615 ++blocked_set_cookie_count_;
2616
2617 return allowed;
2618 }
2619
2620 void SetCookieFilter(std::string filter) {
2621 cookie_name_filter_ = std::move(filter);
2622 }
2623
2624 int set_cookie_called_count() { return set_cookie_called_count_; }
2625
2626 int blocked_set_cookie_count() { return blocked_set_cookie_count_; }
2627
2628 void ResetSetCookieCalledCount() { set_cookie_called_count_ = 0; }
2629
2630 void ResetBlockedSetCookieCount() { blocked_set_cookie_count_ = 0; }
2631
2632 private:
2633 std::string cookie_name_filter_;
2634 int set_cookie_called_count_;
2635 int blocked_set_cookie_count_;
2636};
2637
2638TEST_F(URLRequestTest, DelayedCookieCallbackAsync) {
2639 HttpTestServer test_server;
2640 ASSERT_TRUE(test_server.Start());
2641
2642 TestURLRequestContext async_context;
2643 std::unique_ptr<DelayedCookieMonster> delayed_cm =
2644 std::make_unique<DelayedCookieMonster>();
2645 async_context.set_cookie_store(delayed_cm.get());
2646 FilteringTestLayeredNetworkDelegate async_filter_network_delegate(
2647 std::make_unique<TestNetworkDelegate>());
2648 async_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
2649 async_context.set_network_delegate(&async_filter_network_delegate);
2650 TestDelegate async_delegate;
2651
2652 TestURLRequestContext sync_context;
2653 std::unique_ptr<CookieMonster> cm =
Nick Harper57142b1c2019-03-14 21:03:592654 std::make_unique<CookieMonster>(nullptr, nullptr);
Aaron Tagliaboschi028009e2019-03-07 16:28:062655 sync_context.set_cookie_store(cm.get());
2656 FilteringTestLayeredNetworkDelegate sync_filter_network_delegate(
2657 std::make_unique<TestNetworkDelegate>());
2658 sync_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
2659 sync_context.set_network_delegate(&sync_filter_network_delegate);
2660 TestDelegate sync_delegate;
2661
2662 // Add a secure cookie so we can try to set an insecure cookie and have
2663 // SetCanonicalCookie (and therefore SetCookieWithOptions) fail.
2664 GURL::Replacements replace_scheme;
2665 replace_scheme.SetSchemeStr("https");
2666 GURL url = test_server.base_url().ReplaceComponents(replace_scheme);
2667
2668 delayed_cm->SetCookieWithOptionsAsync(url, "AlreadySetCookie=1;Secure",
2669 CookieOptions(),
2670 CookieStore::SetCookiesCallback());
2671 cm->SetCookieWithOptionsAsync(url, "AlreadySetCookie=1;Secure",
2672 CookieOptions(),
2673 CookieStore::SetCookiesCallback());
2674
2675 std::vector<std::string> cookie_lines(
2676 {// Fails on CanonicalCookie::Create for trying to create a secure cookie
2677 // on an insecure host.
2678 "CookieNotSet=1;Secure",
2679 // Fail in FilteringTestLayeredNetworkDelegate::CanGetCookie.
2680 "CookieBlockedOnCanGetCookie=1",
2681 // Fails in SetCanonicalCookie for trying to overwrite a secure cookie
2682 // with an insecure cookie.
2683 "AlreadySetCookie=1",
2684 // Succeeds and added cookie to store. Delayed (which makes the callback
2685 // run asynchronously) in DelayedCookieMonster.
2686 "CookieSet=1"});
2687
2688 for (auto first_cookie_line : cookie_lines) {
2689 for (auto second_cookie_line : cookie_lines) {
2690 // Run with the delayed cookie monster.
2691 std::unique_ptr<URLRequest> request = async_context.CreateRequest(
2692 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2693 second_cookie_line),
2694 DEFAULT_PRIORITY, &async_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2695
2696 request->Start();
2697 async_delegate.RunUntilComplete();
2698 EXPECT_THAT(async_delegate.request_status(), IsOk());
2699
2700 // Run with the regular cookie monster.
2701 request = sync_context.CreateRequest(
2702 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2703 second_cookie_line),
2704 DEFAULT_PRIORITY, &sync_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2705
2706 request->Start();
2707 sync_delegate.RunUntilComplete();
2708 EXPECT_THAT(sync_delegate.request_status(), IsOk());
2709
2710 int expected_set_cookie_count = 0;
2711 int expected_blocked_cookie_count = 0;
2712
2713 if (first_cookie_line != "CookieNotSet=1;Secure")
2714 ++expected_set_cookie_count;
2715 if (second_cookie_line != "CookieNotSet=1;Secure")
2716 ++expected_set_cookie_count;
2717
2718 if (first_cookie_line == "CookieBlockedOnCanGetCookie=1")
2719 ++expected_blocked_cookie_count;
2720 if (second_cookie_line == "CookieBlockedOnCanGetCookie=1")
2721 ++expected_blocked_cookie_count;
2722
2723 EXPECT_EQ(expected_set_cookie_count,
2724 async_filter_network_delegate.set_cookie_called_count());
2725 EXPECT_EQ(expected_blocked_cookie_count,
2726 async_filter_network_delegate.blocked_set_cookie_count());
2727
2728 EXPECT_EQ(expected_set_cookie_count,
2729 sync_filter_network_delegate.set_cookie_called_count());
2730 EXPECT_EQ(expected_blocked_cookie_count,
2731 sync_filter_network_delegate.blocked_set_cookie_count());
2732
2733 async_filter_network_delegate.ResetSetCookieCalledCount();
2734 async_filter_network_delegate.ResetBlockedSetCookieCount();
2735
2736 sync_filter_network_delegate.ResetSetCookieCalledCount();
2737 sync_filter_network_delegate.ResetBlockedSetCookieCount();
2738 }
2739 }
2740}
2741
[email protected]f2f31b32013-01-16 23:24:092742TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392743 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442744 ASSERT_TRUE(test_server.Start());
2745
2746 // Set up a cookie.
2747 {
2748 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072749 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442750 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072751 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552752 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162753 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192754 req->Start();
Wez2a31b222018-06-07 22:07:152755 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442756 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2757 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2758 }
2759
2760 // Verify that the cookie is set.
2761 {
2762 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072763 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442764 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072765 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162766 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2767 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192768 req->Start();
Wez2a31b222018-06-07 22:07:152769 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442770
2771 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2772 != std::string::npos);
2773 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2774 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2775 }
2776
2777 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2778 {
2779 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072780 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442781 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072782 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162783 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2784 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192785 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2786 req->Start();
Wez2a31b222018-06-07 22:07:152787 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442788
2789 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2790 == std::string::npos);
2791
2792 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2793 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2794 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2795 }
2796}
2797
2798TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392799 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442800 ASSERT_TRUE(test_server.Start());
2801
2802 // Set up a cookie.
2803 {
2804 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072805 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442806 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072807 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552808 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162809 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192810 req->Start();
Wez2a31b222018-06-07 22:07:152811 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442812
2813 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2814 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2815 EXPECT_EQ(1, network_delegate.set_cookie_count());
2816 }
2817
2818 // Try to set-up another cookie and update the previous cookie.
2819 {
2820 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072821 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442822 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072823 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552824 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162825 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192826 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2827 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442828
Wez2a31b222018-06-07 22:07:152829 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442830
2831 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2832 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2833 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2834 EXPECT_EQ(0, network_delegate.set_cookie_count());
2835 }
2836
2837 // Verify the cookies weren't saved or updated.
2838 {
2839 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072840 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442841 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072842 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162843 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2844 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192845 req->Start();
Wez2a31b222018-06-07 22:07:152846 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442847
2848 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2849 == std::string::npos);
2850 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2851 != std::string::npos);
2852
2853 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2854 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2855 EXPECT_EQ(0, network_delegate.set_cookie_count());
2856 }
2857}
2858
2859TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392860 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442861 ASSERT_TRUE(test_server.Start());
2862
2863 // Set up a cookie.
2864 {
2865 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072866 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442867 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072868 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552869 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162870 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192871 req->Start();
Wez2a31b222018-06-07 22:07:152872 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442873
2874 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2875 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2876 }
2877
2878 // Verify that the cookie is set.
2879 {
2880 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072881 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442882 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072883 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162884 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2885 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192886 req->Start();
Wez2a31b222018-06-07 22:07:152887 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442888
2889 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2890 != std::string::npos);
2891
2892 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2893 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182894 TestNetLogEntry::List entries;
2895 net_log_.GetEntries(&entries);
2896 for (const auto& entry : entries) {
2897 EXPECT_NE(entry.type,
2898 NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE);
2899 }
[email protected]316c1e5e2012-09-12 15:17:442900 }
2901
2902 // Verify that the cookie isn't sent.
2903 {
2904 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072905 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442906 TestDelegate d;
2907 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:072908 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162909 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2910 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192911 req->Start();
Wez2a31b222018-06-07 22:07:152912 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442913
2914 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2915 == std::string::npos);
2916
[email protected]22e045f2013-09-20 03:54:032917 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442918 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182919 TestNetLogEntry::List entries;
2920 net_log_.GetEntries(&entries);
2921 ExpectLogContainsSomewhereAfter(
2922 entries, 0, NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE,
2923 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442924 }
2925}
2926
marqf14fff8d2015-12-02 15:52:292927// TODO(crbug.com/564656) This test is flaky on iOS.
2928#if defined(OS_IOS)
2929#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2930#else
2931#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2932#endif
[email protected]316c1e5e2012-09-12 15:17:442933TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392934 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442935 ASSERT_TRUE(test_server.Start());
2936
2937 // Set up a cookie.
2938 {
2939 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072940 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442941 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072942 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552943 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162944 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192945 req->Start();
Wez2a31b222018-06-07 22:07:152946 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442947
2948 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2949 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182950 TestNetLogEntry::List entries;
2951 net_log_.GetEntries(&entries);
2952 for (const auto& entry : entries) {
2953 EXPECT_NE(entry.type,
2954 NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE);
2955 }
[email protected]316c1e5e2012-09-12 15:17:442956 }
2957
2958 // Try to set-up another cookie and update the previous cookie.
2959 {
2960 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072961 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442962 TestDelegate d;
2963 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:072964 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552965 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162966 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192967 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442968
Wez2a31b222018-06-07 22:07:152969 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442970
2971 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2972 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182973 TestNetLogEntry::List entries;
2974 net_log_.GetEntries(&entries);
2975 ExpectLogContainsSomewhereAfter(
2976 entries, 0, NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE,
2977 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442978 }
2979
2980 // Verify the cookies weren't saved or updated.
2981 {
2982 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072983 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442984 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072985 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162986 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2987 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192988 req->Start();
Wez2a31b222018-06-07 22:07:152989 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442990
2991 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2992 == std::string::npos);
2993 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2994 != std::string::npos);
2995
2996 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2997 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2998 }
2999}
3000
3001TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:393002 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443003 ASSERT_TRUE(test_server.Start());
3004
3005 // Set up an empty cookie.
3006 {
3007 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073008 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443009 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073010 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163011 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
3012 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193013 req->Start();
Wez2a31b222018-06-07 22:07:153014 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443015
3016 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3017 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3018 EXPECT_EQ(0, network_delegate.set_cookie_count());
3019 }
3020}
3021
3022TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393023 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443024 ASSERT_TRUE(test_server.Start());
3025
3026 // Set up a cookie.
3027 {
3028 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073029 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443030 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073031 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553032 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163033 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193034 req->Start();
Wez2a31b222018-06-07 22:07:153035 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443036
3037 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3038 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3039 }
3040
3041 // Verify that the cookie is set.
3042 {
3043 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073044 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443045 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073046 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163047 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3048 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193049 req->Start();
Wez2a31b222018-06-07 22:07:153050 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443051
3052 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
3053 != std::string::npos);
3054
3055 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3056 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3057 }
3058
3059 // Verify that the cookie isn't sent.
3060 {
3061 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073062 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443063 TestDelegate d;
3064 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:073065 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163066 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3067 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193068 req->Start();
Wez2a31b222018-06-07 22:07:153069 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443070
3071 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
3072 == std::string::npos);
3073
[email protected]22e045f2013-09-20 03:54:033074 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:443075 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3076 }
3077}
3078
3079TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393080 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443081 ASSERT_TRUE(test_server.Start());
3082
3083 // Set up a cookie.
3084 {
3085 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073086 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443087 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073088 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553089 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163090 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193091 req->Start();
Wez2a31b222018-06-07 22:07:153092 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443093
3094 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3095 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3096 }
3097
3098 // Try to set-up another cookie and update the previous cookie.
3099 {
3100 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073101 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443102 TestDelegate d;
3103 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:073104 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553105 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:163106 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193107 req->Start();
[email protected]316c1e5e2012-09-12 15:17:443108
Wez2a31b222018-06-07 22:07:153109 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443110
3111 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3112 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
3113 }
3114
3115 // Verify the cookies weren't saved or updated.
3116 {
3117 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073118 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443119 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073120 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163121 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3122 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193123 req->Start();
Wez2a31b222018-06-07 22:07:153124 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443125
3126 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
3127 == std::string::npos);
3128 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
3129 != std::string::npos);
3130
3131 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3132 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3133 }
3134}
3135
mkwstc5fa7762016-03-28 09:28:233136TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:393137 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:263138 ASSERT_TRUE(test_server.Start());
3139
mkwst202534e32016-01-15 16:07:153140 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073141 default_context().set_network_delegate(&network_delegate);
mkwst202534e32016-01-15 16:07:153142
mkwstf71d0bd2016-03-21 14:15:243143 const std::string kHost = "example.test";
3144 const std::string kSubHost = "subdomain.example.test";
3145 const std::string kCrossHost = "cross-origin.test";
3146
3147 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:263148 {
mkwst3f3daac2015-02-26 20:15:263149 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073150 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
mkwstf71d0bd2016-03-21 14:15:243151 test_server.GetURL(kHost,
3152 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3153 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:163154 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst3f3daac2015-02-26 20:15:263155 req->Start();
Wez2a31b222018-06-07 22:07:153156 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263157 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3158 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:243159 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:263160 }
3161
mkwstf71d0bd2016-03-21 14:15:243162 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:263163 {
mkwst3f3daac2015-02-26 20:15:263164 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073165 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163166 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3167 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463168 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463169 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263170 req->Start();
Wez2a31b222018-06-07 22:07:153171 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263172
mkwstf71d0bd2016-03-21 14:15:243173 EXPECT_NE(std::string::npos,
3174 d.data_received().find("StrictSameSiteCookie=1"));
3175 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263176 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3177 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3178 }
3179
clamyfd58ca072016-12-21 17:18:323180 // Verify that both cookies are sent when the request has no initiator (can
3181 // happen for main frame browser-initiated navigations).
3182 {
3183 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073184 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163185 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3186 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463187 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:323188 req->Start();
Wez2a31b222018-06-07 22:07:153189 d.RunUntilComplete();
clamyfd58ca072016-12-21 17:18:323190
3191 EXPECT_NE(std::string::npos,
3192 d.data_received().find("StrictSameSiteCookie=1"));
3193 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3194 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3195 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3196 }
3197
mkwstf71d0bd2016-03-21 14:15:243198 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263199 {
mkwst3f3daac2015-02-26 20:15:263200 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073201 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163202 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3203 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463204 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463205 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153206 req->Start();
Wez2a31b222018-06-07 22:07:153207 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153208
mkwstf71d0bd2016-03-21 14:15:243209 EXPECT_NE(std::string::npos,
3210 d.data_received().find("StrictSameSiteCookie=1"));
3211 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153212 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3213 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3214 }
3215
mkwstf71d0bd2016-03-21 14:15:243216 // Verify that neither cookie is not sent for cross-site requests.
3217 {
3218 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073219 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163220 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3221 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463222 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463223 req->set_initiator(
3224 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243225 req->Start();
Wez2a31b222018-06-07 22:07:153226 d.RunUntilComplete();
mkwstf71d0bd2016-03-21 14:15:243227
3228 EXPECT_EQ(std::string::npos,
3229 d.data_received().find("StrictSameSiteCookie=1"));
3230 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3231 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3232 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3233 }
3234
3235 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153236 // method is "safe".
3237 {
3238 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073239 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163240 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3241 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463242 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463243 req->set_initiator(
3244 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243245 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153246 req->Start();
Wez2a31b222018-06-07 22:07:153247 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153248
mkwstf71d0bd2016-03-21 14:15:243249 EXPECT_EQ(std::string::npos,
3250 d.data_received().find("StrictSameSiteCookie=1"));
3251 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153252 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3253 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3254 }
3255
mkwstf71d0bd2016-03-21 14:15:243256 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153257 // method is unsafe (e.g. POST).
3258 {
3259 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073260 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163261 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3262 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463263 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463264 req->set_initiator(
3265 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153266 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263267 req->Start();
Wez2a31b222018-06-07 22:07:153268 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263269
mkwstf71d0bd2016-03-21 14:15:243270 EXPECT_EQ(std::string::npos,
3271 d.data_received().find("StrictSameSiteCookie=1"));
3272 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263273 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3274 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3275 }
3276}
3277
estark557a5eb82015-12-01 22:57:103278// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363279TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553280 EmbeddedTestServer http_server;
3281 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363282 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553283 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3284 https_server.AddDefaultHandlers(
3285 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3286 ASSERT_TRUE(http_server.Start());
3287 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363288
estarkb15166b2015-12-18 16:56:383289 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363290 TestURLRequestContext context(true);
3291 context.set_network_delegate(&network_delegate);
3292 context.Init();
3293
estarkb15166b2015-12-18 16:56:383294 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363295 {
3296 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363297 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103298 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163299 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363300 req->Start();
Wez2a31b222018-06-07 22:07:153301 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363302 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3303 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3304 }
3305
3306 // Verify that the cookie is not set.
3307 {
3308 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363309 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163310 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3311 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363312 req->Start();
Wez2a31b222018-06-07 22:07:153313 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363314
jww79aceda2015-12-07 01:56:343315 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3316 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363317 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3318 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3319 }
3320}
3321
estarkb15166b2015-12-18 16:56:383322TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553323 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3324 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363325 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553326 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363327
3328 TestNetworkDelegate network_delegate;
3329 TestURLRequestContext context(true);
3330 context.set_network_delegate(&network_delegate);
3331 context.Init();
3332
estarkb15166b2015-12-18 16:56:383333 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363334 {
3335 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163336 std::unique_ptr<URLRequest> req(context.CreateRequest(
3337 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3338 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363339 req->Start();
Wez2a31b222018-06-07 22:07:153340 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583341 EXPECT_EQ(0, network_delegate.set_cookie_count());
estarkcd39c11f2015-10-19 19:46:363342 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3343 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3344 }
3345
3346 // Verify that the cookie is not set.
3347 {
3348 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363349 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163350 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3351 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363352 req->Start();
Wez2a31b222018-06-07 22:07:153353 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363354
jww79aceda2015-12-07 01:56:343355 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363356 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3357 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3358 }
3359}
3360
estarkb15166b2015-12-18 16:56:383361TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553362 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3363 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363364 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553365 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363366
estarkb15166b2015-12-18 16:56:383367 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363368 TestURLRequestContext context(true);
3369 context.set_network_delegate(&network_delegate);
3370 context.Init();
3371
estarkb15166b2015-12-18 16:56:383372 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363373 {
3374 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363375 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103376 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163377 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363378 req->Start();
Wez2a31b222018-06-07 22:07:153379 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363380 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3381 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3382 }
3383
3384 // Verify that the cookie is set.
3385 {
3386 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363387 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163388 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3389 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363390 req->Start();
Wez2a31b222018-06-07 22:07:153391 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363392
jww79aceda2015-12-07 01:56:343393 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3394 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3395 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3396 }
3397}
3398
3399// Tests that secure cookies can't be set on non-secure origins if strict secure
3400// cookies are enabled.
3401TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3402 EmbeddedTestServer http_server;
3403 http_server.AddDefaultHandlers(
3404 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3405 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3406 https_server.AddDefaultHandlers(
3407 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3408 ASSERT_TRUE(http_server.Start());
3409 ASSERT_TRUE(https_server.Start());
3410
Matt Menkebe9b6eb2018-10-18 12:11:443411 TestNetworkDelegate network_delegate;
jww79aceda2015-12-07 01:56:343412 TestURLRequestContext context(true);
3413 context.set_network_delegate(&network_delegate);
3414 context.Init();
3415
3416 // Try to set a Secure cookie, with experimental features enabled.
3417 {
3418 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363419 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343420 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163421 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343422 req->Start();
Wez2a31b222018-06-07 22:07:153423 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343424 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3425 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3426 }
3427
3428 // Verify that the cookie is not set.
3429 {
3430 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363431 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163432 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3433 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343434 req->Start();
Wez2a31b222018-06-07 22:07:153435 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343436
3437 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3438 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3439 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3440 }
3441}
3442
Thiemo Nagel0793b9c532018-04-18 16:57:583443// The parameter is true for same-site and false for cross-site requests.
3444class URLRequestTestParameterizedSameSite
3445 : public URLRequestTest,
3446 public ::testing::WithParamInterface<bool> {
3447 protected:
3448 URLRequestTestParameterizedSameSite() {
3449 auto params = std::make_unique<HttpNetworkSession::Params>();
3450 params->ignore_certificate_errors = true;
3451 context_.set_http_network_session_params(std::move(params));
3452 context_.set_network_delegate(&network_delegate_);
3453 https_server_.AddDefaultHandlers(
3454 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3455 EXPECT_TRUE(https_server_.Start());
3456 }
3457
3458 // To be called after configuration of |context_| has been finalized.
3459 void InitContext() { context_.Init(); }
3460
3461 const std::string kHost_ = "example.test";
3462 const std::string kCrossHost_ = "cross-site.test";
3463 TestURLRequestContext context_{true};
3464 TestNetworkDelegate network_delegate_;
3465 base::HistogramTester histograms_;
3466 EmbeddedTestServer https_server_{EmbeddedTestServer::TYPE_HTTPS};
3467};
3468
Victor Costan8fb98f6f2019-02-01 17:08:293469INSTANTIATE_TEST_SUITE_P(URLRequestTest,
3470 URLRequestTestParameterizedSameSite,
3471 ::testing::Bool());
Thiemo Nagel0793b9c532018-04-18 16:57:583472
3473TEST_P(URLRequestTestParameterizedSameSite, CookieAgeMetrics) {
3474 const bool same_site = GetParam();
3475 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3476 InitContext();
3477
Mike West86149882017-07-28 10:41:493478 EmbeddedTestServer http_server;
3479 http_server.AddDefaultHandlers(
3480 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
Thiemo Nagel23e0b322018-04-18 12:46:543481 ASSERT_TRUE(http_server.Start());
3482
Thiemo Nagel0793b9c532018-04-18 16:57:583483 // Set two test cookies.
Thiemo Nagel23e0b322018-04-18 12:46:543484 {
3485 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583486 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3487 http_server.GetURL(kHost_, "/set-cookie?cookie=value&cookie2=value2"),
Thiemo Nagel23e0b322018-04-18 12:46:543488 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3489 req->Start();
Wez2a31b222018-06-07 22:07:153490 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583491 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3492 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3493 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3494 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3495 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 0);
3496 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3497 0);
3498 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3499 0);
3500 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3501 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 0);
Thiemo Nagel23e0b322018-04-18 12:46:543502 }
3503
Thiemo Nagel0793b9c532018-04-18 16:57:583504 // Make a secure request.
Thiemo Nagel23e0b322018-04-18 12:46:543505 {
3506 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583507 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3508 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3509 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3510 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103511 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583512 url::Origin::Create(https_server_.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103513 req->Start();
Wez2a31b222018-06-07 22:07:153514 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583515 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3516 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3517 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3518 !same_site);
3519 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3520 same_site);
3521 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3522 0);
3523 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3524 0);
3525 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3526 same_site ? 0 : 2);
3527 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3528 same_site ? 2 : 0);
3529 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3530 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
Mohsen Izadiad6f7592018-04-18 15:57:103531 }
3532
Thiemo Nagel0793b9c532018-04-18 16:57:583533 // Make a non-secure request.
Mohsen Izadiad6f7592018-04-18 15:57:103534 {
3535 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583536 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3537 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
Mohsen Izadiad6f7592018-04-18 15:57:103538 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel0793b9c532018-04-18 16:57:583539 req->set_site_for_cookies(http_server.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103540 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583541 url::Origin::Create(http_server.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103542 req->Start();
Wez2a31b222018-06-07 22:07:153543 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583544 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest",
3545 !same_site);
3546 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest",
3547 same_site);
3548 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3549 !same_site);
3550 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3551 same_site);
3552 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3553 same_site ? 0 : 2);
3554 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3555 same_site ? 2 : 0);
3556 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3557 same_site ? 0 : 2);
3558 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3559 same_site ? 2 : 0);
3560 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3561 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
3562 }
3563}
3564
3565// Cookies with secure attribute (no HSTS) --> k1pSecureAttribute
3566TEST_P(URLRequestTestParameterizedSameSite,
3567 CookieNetworkSecurityMetricSecureAttribute) {
3568 const bool same_site = GetParam();
3569 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3570 InitContext();
3571
3572 // Set cookies.
3573 {
3574 TestDelegate d;
3575 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3576 https_server_.GetURL(kHost_,
3577 "/set-cookie?session-cookie=value;Secure&"
3578 "longlived-cookie=value;Secure;domain=" +
3579 kHost_ + ";Max-Age=360000"),
3580 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3581 req->Start();
Wez2a31b222018-06-07 22:07:153582 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583583 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3584 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3585 }
3586
3587 // Verify that the cookies fall into the correct metrics bucket.
3588 {
3589 TestDelegate d;
3590 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3591 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3592 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3593 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3594 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3595 req->Start();
Wez2a31b222018-06-07 22:07:153596 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583597 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3598 // Static cast of boolean required for MSVC 1911.
3599 histograms_.ExpectBucketCount(
3600 "Cookie.NetworkSecurity",
3601 static_cast<int>(CookieNetworkSecurity::k1pSecureAttribute) |
3602 static_cast<int>(!same_site),
3603 2);
3604 }
3605}
3606
3607// Short-lived host cookie --> k1pHSTSHostCookie
3608TEST_P(URLRequestTestParameterizedSameSite,
3609 CookieNetworkSecurityMetricShortlivedHostCookie) {
3610 const bool same_site = GetParam();
3611 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3612
3613 TransportSecurityState transport_security_state;
3614 transport_security_state.AddHSTS(
3615 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3616 false /* include_subdomains */);
3617 context_.set_transport_security_state(&transport_security_state);
3618 InitContext();
3619
3620 // Set cookie.
3621 {
3622 TestDelegate d;
3623 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3624 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;Max-Age=3600"),
3625 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3626 req->Start();
Wez2a31b222018-06-07 22:07:153627 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583628 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3629 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3630 }
3631
3632 // Verify that the cookie falls into the correct metrics bucket.
3633 {
3634 TestDelegate d;
3635 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3636 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3637 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3638 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3639 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3640 req->Start();
Wez2a31b222018-06-07 22:07:153641 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583642 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3643 // Static cast of boolean required for MSVC 1911.
3644 histograms_.ExpectBucketCount(
3645 "Cookie.NetworkSecurity",
3646 static_cast<int>(CookieNetworkSecurity::k1pHSTSHostCookie) |
3647 static_cast<int>(!same_site),
3648 1);
3649 }
3650}
3651
3652// Long-lived (either due to expiry or due to being a session cookie) host
3653// cookies --> k1pExpiringHSTSHostCookie
3654TEST_P(URLRequestTestParameterizedSameSite,
3655 CookieNetworkSecurityMetricLonglivedHostCookie) {
3656 const bool same_site = GetParam();
3657 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3658
3659 TransportSecurityState transport_security_state;
3660 transport_security_state.AddHSTS(
3661 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3662 false /* include_subdomains */);
3663 context_.set_transport_security_state(&transport_security_state);
3664 InitContext();
3665
3666 // Set cookies.
3667 {
3668 TestDelegate d;
3669 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3670 https_server_.GetURL(kHost_,
3671 "/set-cookie?session-cookie=value&"
3672 "longlived-cookie=value;Max-Age=360000"),
3673 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3674 req->Start();
Wez2a31b222018-06-07 22:07:153675 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583676 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3677 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3678 }
3679
3680 // Verify that the cookies fall into the correct metrics bucket.
3681 {
3682 TestDelegate d;
3683 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3684 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3685 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3686 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3687 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3688 req->Start();
Wez2a31b222018-06-07 22:07:153689 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583690 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3691 // Static cast of boolean required for MSVC 1911.
3692 histograms_.ExpectBucketCount(
3693 "Cookie.NetworkSecurity",
3694 static_cast<int>(CookieNetworkSecurity::k1pExpiringHSTSHostCookie) |
3695 static_cast<int>(!same_site),
3696 2);
3697 }
3698}
3699
3700// Domain cookie with HSTS subdomains with cookie expiry before HSTS expiry -->
3701// k1pHSTSSubdomainsIncluded
3702TEST_P(URLRequestTestParameterizedSameSite,
3703 CookieNetworkSecurityMetricShortlivedDomainCookie) {
3704 const bool same_site = GetParam();
3705 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3706
3707 TransportSecurityState transport_security_state;
3708 transport_security_state.AddHSTS(
3709 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3710 true /* include_subdomains */);
3711 context_.set_transport_security_state(&transport_security_state);
3712 InitContext();
3713
3714 // Set cookie.
3715 {
3716 TestDelegate d;
3717 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3718 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3719 kHost_ + ";Max-Age=3600"),
3720 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3721 req->Start();
Wez2a31b222018-06-07 22:07:153722 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583723 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3724 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3725 }
3726
3727 // Verify that the cookie falls into the correct metrics bucket.
3728 {
3729 TestDelegate d;
3730 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3731 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3732 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3733 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3734 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3735 req->Start();
Wez2a31b222018-06-07 22:07:153736 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583737 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3738 // Static cast of boolean required for MSVC 1911.
3739 histograms_.ExpectBucketCount(
3740 "Cookie.NetworkSecurity",
3741 static_cast<int>(CookieNetworkSecurity::k1pHSTSSubdomainsIncluded) |
3742 static_cast<int>(!same_site),
3743 1);
3744 }
3745}
3746
3747// Long-lived (either due to expiry or due to being a session cookie) domain
3748// cookies with HSTS subdomains --> k1pExpiringHSTSSubdomainsIncluded
3749TEST_P(URLRequestTestParameterizedSameSite,
3750 CookieNetworkSecurityMetricLonglivedDomainCookie) {
3751 const bool same_site = GetParam();
3752 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3753
3754 TransportSecurityState transport_security_state;
3755 transport_security_state.AddHSTS(
3756 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3757 true /* include_subdomains */);
3758 context_.set_transport_security_state(&transport_security_state);
3759 InitContext();
3760
3761 // Set cookies.
3762 {
3763 TestDelegate d;
3764 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3765 https_server_.GetURL(
3766 kHost_, "/set-cookie?session-cookie=value;domain=" + kHost_ + "&" +
3767 "longlived-cookie=value;domain=" + kHost_ +
3768 ";Max-Age=360000"),
3769 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3770 req->Start();
Wez2a31b222018-06-07 22:07:153771 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583772 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3773 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3774 }
3775
3776 // Verify that the cookies fall into the correct metrics bucket.
3777 {
3778 TestDelegate d;
3779 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3780 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3781 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3782 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3783 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3784 req->Start();
Wez2a31b222018-06-07 22:07:153785 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583786 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3787 // Static cast of boolean required for MSVC 1911.
3788 histograms_.ExpectBucketCount(
3789 "Cookie.NetworkSecurity",
3790 static_cast<int>(
3791 CookieNetworkSecurity::k1pExpiringHSTSSubdomainsIncluded) |
3792 static_cast<int>(!same_site),
3793 2);
3794 }
3795}
3796
3797// Domain cookie with HSTS subdomains not included --> k1pHSTSSpoofable
3798TEST_P(URLRequestTestParameterizedSameSite,
3799 CookieNetworkSecurityMetricSpoofableDomainCookie) {
3800 const bool same_site = GetParam();
3801 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3802
3803 TransportSecurityState transport_security_state;
3804 transport_security_state.AddHSTS(
3805 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3806 false /* include_subdomains */);
3807 context_.set_transport_security_state(&transport_security_state);
3808 InitContext();
3809
3810 // Set cookie.
3811 {
3812 TestDelegate d;
3813 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3814 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3815 kHost_ + ";Max-Age=3600"),
3816 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3817 req->Start();
Wez2a31b222018-06-07 22:07:153818 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583819 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3820 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3821 }
3822
3823 // Verify that the cookie falls into the correct metrics bucket.
3824 {
3825 TestDelegate d;
3826 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3827 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3828 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3829 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3830 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3831 req->Start();
Wez2a31b222018-06-07 22:07:153832 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583833 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3834 // Static cast of boolean required for MSVC 1911.
3835 histograms_.ExpectBucketCount(
3836 "Cookie.NetworkSecurity",
3837 static_cast<int>(CookieNetworkSecurity::k1pHSTSSpoofable) |
3838 static_cast<int>(!same_site),
3839 1);
3840 }
3841}
3842
3843// Cookie without HSTS --> k1p(Non)SecureConnection
3844TEST_P(URLRequestTestParameterizedSameSite, CookieNetworkSecurityMetricNoHSTS) {
3845 const bool same_site = GetParam();
3846 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3847 InitContext();
3848
3849 EmbeddedTestServer http_server;
3850 http_server.AddDefaultHandlers(
3851 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3852 ASSERT_TRUE(http_server.Start());
3853
3854 // Set cookies.
3855 {
3856 TestDelegate d;
3857 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3858 https_server_.GetURL(kHost_,
3859 "/set-cookie?cookie=value;domain=" + kHost_ +
3860 ";Max-Age=3600&host-cookie=value"),
3861 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3862 req->Start();
Wez2a31b222018-06-07 22:07:153863 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583864 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3865 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3866 }
3867
3868 // Verify that the cookie falls into the correct metrics bucket.
3869 {
3870 TestDelegate d;
3871 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3872 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3873 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3874 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3875 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3876 req->Start();
Wez2a31b222018-06-07 22:07:153877 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583878 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3879 // Static cast of boolean required for MSVC 1911.
3880 histograms_.ExpectBucketCount(
3881 "Cookie.NetworkSecurity",
3882 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3883 static_cast<int>(!same_site),
3884 2);
3885 }
3886
3887 // Verify that the cookie falls into the correct metrics bucket.
3888 {
3889 TestDelegate d;
3890 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3891 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3892 TRAFFIC_ANNOTATION_FOR_TESTS));
3893 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3894 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3895 req->Start();
Wez2a31b222018-06-07 22:07:153896 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583897 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 4);
3898 // Static cast of boolean required for MSVC 1911.
3899 histograms_.ExpectBucketCount(
3900 "Cookie.NetworkSecurity",
3901 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3902 static_cast<int>(!same_site),
3903 2);
3904 // Static cast of boolean required for MSVC 1911.
3905 histograms_.ExpectBucketCount(
3906 "Cookie.NetworkSecurity",
3907 static_cast<int>(CookieNetworkSecurity::k1pNonsecureConnection) |
3908 static_cast<int>(!same_site),
3909 2);
Mike West86149882017-07-28 10:41:493910 }
3911}
3912
mmenkefb18c772015-09-30 22:22:503913// Tests that a request is cancelled while entering suspend mode. Uses mocks
3914// rather than a spawned test server because the connection used to talk to
3915// the test server is affected by entering suspend mode on Android.
3916TEST_F(URLRequestTest, CancelOnSuspend) {
3917 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363918 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503919
3920 URLRequestFailedJob::AddUrlHandler();
3921
3922 TestDelegate d;
3923 // Request that just hangs.
3924 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
Ryan Sleevib8449e02018-07-15 04:31:073925 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163926 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mmenkefb18c772015-09-30 22:22:503927 r->Start();
3928
3929 power_monitor_source->Suspend();
3930 // Wait for the suspend notification to cause the request to fail.
Wez2a31b222018-06-07 22:07:153931 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:503932 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503933 EXPECT_TRUE(d.request_failed());
3934 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3935
3936 URLRequestFilter::GetInstance()->ClearHandlers();
3937
3938 // Shouldn't be needed, but just in case.
3939 power_monitor_source->Resume();
3940}
3941
[email protected]5095cd72012-11-01 10:29:163942// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3943// value for the |fixed_date| argument given to the constructor.
3944class FixedDateNetworkDelegate : public TestNetworkDelegate {
3945 public:
3946 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3947 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:273948 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:163949
[email protected]cba24642014-08-15 20:49:593950 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203951 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593952 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:203953 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:593954 const HttpResponseHeaders* original_response_headers,
3955 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133956 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163957
3958 private:
3959 std::string fixed_date_;
3960
3961 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3962};
3963
3964int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593965 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:203966 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:593967 const HttpResponseHeaders* original_response_headers,
3968 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163969 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593970 HttpResponseHeaders* new_response_headers =
3971 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163972
3973 new_response_headers->RemoveHeader("Date");
3974 new_response_headers->AddHeader("Date: " + fixed_date_);
3975
3976 *override_response_headers = new_response_headers;
David Benjamind1f287bf2018-06-12 01:57:203977 return TestNetworkDelegate::OnHeadersReceived(
3978 request, std::move(callback), original_response_headers,
3979 override_response_headers, allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163980}
3981
3982// Test that cookie expiration times are adjusted for server/client clock
3983// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3984// headers by defaulting to GMT. (crbug.com/135131)
3985TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:393986 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:163987 ASSERT_TRUE(test_server.Start());
3988
3989 // Set up an expired cookie.
3990 {
3991 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073992 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:163993 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073994 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193995 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553996 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163997 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193998 req->Start();
Wez2a31b222018-06-07 22:07:153999 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164000 }
4001 // Verify that the cookie is not set.
4002 {
4003 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074004 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164005 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074006 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164007 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4008 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194009 req->Start();
Wez2a31b222018-06-07 22:07:154010 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164011
4012 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
4013 }
4014 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
4015 {
4016 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
Ryan Sleevib8449e02018-07-15 04:31:074017 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164018 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074019 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194020 test_server.GetURL(
tommycli59a63432015-11-06 00:10:554021 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:164022 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194023 req->Start();
Wez2a31b222018-06-07 22:07:154024 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164025 }
4026 // Verify that the cookie is set.
4027 {
4028 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074029 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164030 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074031 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164032 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4033 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194034 req->Start();
Wez2a31b222018-06-07 22:07:154035 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164036
4037 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
4038 }
4039}
4040
4041
[email protected]316c1e5e2012-09-12 15:17:444042// Check that it is impossible to change the referrer in the extra headers of
4043// an URLRequest.
4044TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:394045 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:444046 ASSERT_TRUE(test_server.Start());
4047
4048 // If extra headers contain referer and the request contains a referer,
4049 // only the latter shall be respected.
4050 {
4051 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074052 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164053 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4054 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194055 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:444056
4057 HttpRequestHeaders headers;
4058 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194059 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:444060
[email protected]f7022f32014-08-21 16:32:194061 req->Start();
Wez2a31b222018-06-07 22:07:154062 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444063
4064 EXPECT_EQ("http://foo.com/", d.data_received());
4065 }
4066
4067 // If extra headers contain a referer but the request does not, no referer
4068 // shall be sent in the header.
4069 {
4070 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074071 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164072 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4073 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:444074
4075 HttpRequestHeaders headers;
4076 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194077 req->SetExtraRequestHeaders(headers);
4078 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:444079
[email protected]f7022f32014-08-21 16:32:194080 req->Start();
Wez2a31b222018-06-07 22:07:154081 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444082
4083 EXPECT_EQ("None", d.data_received());
4084 }
4085}
4086
[email protected]b89290212009-08-14 22:37:354087class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:114088 public:
mmenke9f2ec60c2015-06-01 20:59:474089 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:114090
[email protected]b89290212009-08-14 22:37:354091 protected:
[email protected]21184962011-10-26 00:50:304092 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
4093 // |request_method| is the method to use for the initial request.
4094 // |redirect_method| is the method that is expected to be used for the second
4095 // request, after redirection.
4096 // If |include_data| is true, data is uploaded with the request. The
4097 // response body is expected to match it exactly, if and only if
4098 // |request_method| == |redirect_method|.
4099 void HTTPRedirectMethodTest(const GURL& redirect_url,
4100 const std::string& request_method,
4101 const std::string& redirect_method,
4102 bool include_data) {
4103 static const char kData[] = "hello world";
4104 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074105 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164106 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194107 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:304108 if (include_data) {
mmenkecbc2b712014-10-09 20:29:074109 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:304110 HttpRequestHeaders headers;
4111 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244112 base::NumberToString(base::size(kData) - 1));
svaldez5b3a8972015-10-09 23:23:544113 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:194114 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:304115 }
[email protected]f7022f32014-08-21 16:32:194116 req->Start();
Wez2a31b222018-06-07 22:07:154117 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194118 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:504119 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:304120 if (include_data) {
4121 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:544122 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4123 HttpRequestHeaders::kContentLength));
4124 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4125 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304126 EXPECT_EQ(kData, d.data_received());
4127 } else {
svaldez5b3a8972015-10-09 23:23:544128 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4129 HttpRequestHeaders::kContentLength));
4130 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4131 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304132 EXPECT_NE(kData, d.data_received());
4133 }
4134 }
4135 if (HasFailure())
4136 LOG(WARNING) << "Request method was: " << request_method;
4137 }
4138
Alex Clarke1e08882b32017-10-06 14:22:404139 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
4140 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:514141 // |request_method| is the method to use for the initial request.
4142 // |redirect_method| is the method that is expected to be used for the second
4143 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:404144 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:514145 // redirection. If empty, expects that there will be no Origin header.
4146 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
4147 const std::string& request_method,
4148 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:404149 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:514150 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074151 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164152 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:514153 req->set_method(request_method);
4154 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
4155 redirect_url.GetOrigin().spec(), false);
4156 req->Start();
4157
Wez2a31b222018-06-07 22:07:154158 d.RunUntilComplete();
jww5fe460ff2015-03-28 00:22:514159
4160 EXPECT_EQ(redirect_method, req->method());
4161 // Note that there is no check for request success here because, for
4162 // purposes of testing, the request very well may fail. For example, if the
4163 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
4164 // origin, there is not an HTTPS server in this unit test framework, so the
4165 // request would fail. However, that's fine, as long as the request headers
4166 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:404167 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:514168 EXPECT_FALSE(
4169 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
4170 } else {
4171 std::string origin_header;
4172 EXPECT_TRUE(req->extra_request_headers().GetHeader(
4173 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:404174 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:514175 }
4176 }
4177
[email protected]762d2db2010-01-11 19:03:014178 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:014179 const int kMsgSize = 20000; // multiple of 10
4180 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:484181 char* uploadBytes = new char[kMsgSize+1];
4182 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:014183 char marker = 'a';
4184 for (int idx = 0; idx < kMsgSize/10; idx++) {
4185 memcpy(ptr, "----------", 10);
4186 ptr += 10;
4187 if (idx % 100 == 0) {
4188 ptr--;
4189 *ptr++ = marker;
4190 if (++marker > 'z')
4191 marker = 'a';
4192 }
4193 }
4194 uploadBytes[kMsgSize] = '\0';
4195
[email protected]762d2db2010-01-11 19:03:014196 for (int i = 0; i < kIterations; ++i) {
4197 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074198 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164199 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
4200 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194201 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:014202
mmenkecbc2b712014-10-09 20:29:074203 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:014204
[email protected]f7022f32014-08-21 16:32:194205 r->Start();
4206 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:014207
Wez2a31b222018-06-07 22:07:154208 d.RunUntilComplete();
[email protected]762d2db2010-01-11 19:03:014209
maksim.sisovb53724b52016-09-16 05:30:504210 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
4211 << d.request_status();
[email protected]762d2db2010-01-11 19:03:014212
4213 EXPECT_FALSE(d.received_data_before_response());
4214 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:014215 }
4216 delete[] uploadBytes;
4217 }
4218
[email protected]ede03212012-09-07 12:52:264219 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:344220 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074221 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:554222 test_server_.GetURL("/set-many-cookies?" +
Raul Tambre8c1981d2019-02-08 02:22:264223 base::NumberToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:164224 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:344225
[email protected]f7022f32014-08-21 16:32:194226 r->Start();
4227 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:344228
Wez2a31b222018-06-07 22:07:154229 d.RunUntilComplete();
[email protected]263163f2012-06-14 22:40:344230
maksim.sisovb53724b52016-09-16 05:30:504231 if (d.request_status() != OK) {
4232 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
4233 return false;
4234 }
[email protected]263163f2012-06-14 22:40:344235
maksim.sisovb53724b52016-09-16 05:30:504236 return true;
[email protected]263163f2012-06-14 22:40:344237 }
4238
David Benjamin42116f62017-11-20 21:45:394239 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:504240
tommycli59a63432015-11-06 00:10:554241 private:
David Benjamin42116f62017-11-20 21:45:394242 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:354243};
4244
tommycli59a63432015-11-06 00:10:554245namespace {
4246
danakj8522a25b2016-04-16 00:17:364247std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:554248 const test_server::HttpRequest& request) {
4249 if (request.headers.find("Host") == request.headers.end() ||
4250 request.headers.at("Host") != "www.redirect.com" ||
4251 request.method != test_server::METHOD_CONNECT) {
4252 return nullptr;
4253 }
4254
danakj8522a25b2016-04-16 00:17:364255 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554256 new test_server::BasicHttpResponse);
4257 http_response->set_code(HTTP_FOUND);
4258 http_response->AddCustomHeader("Location",
4259 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:484260 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554261}
4262
nharperb7441ef2016-01-25 23:54:144263class TestSSLConfigService : public SSLConfigService {
4264 public:
Nick Harper2243e8002018-09-28 20:33:264265 TestSSLConfigService()
4266 : min_version_(kDefaultSSLVersionMin),
davidben095ebb52017-04-12 22:23:344267 max_version_(kDefaultSSLVersionMax) {}
Ryan Sleevib8449e02018-07-15 04:31:074268 ~TestSSLConfigService() override = default;
nharperb7441ef2016-01-25 23:54:144269
davidben095ebb52017-04-12 22:23:344270 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:144271 void set_min_version(uint16_t version) { min_version_ = version; }
4272
nharperb7441ef2016-01-25 23:54:144273 // SSLConfigService:
4274 void GetSSLConfig(SSLConfig* config) override {
4275 *config = SSLConfig();
davidben095ebb52017-04-12 22:23:344276 config->version_min = min_version_;
4277 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:144278 }
4279
Nick Harper89bc7212018-07-31 19:07:574280 bool CanShareConnectionWithClientCerts(
4281 const std::string& hostname) const override {
4282 return false;
4283 }
4284
nharperb7441ef2016-01-25 23:54:144285 private:
nharperb7441ef2016-01-25 23:54:144286 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:344287 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:144288};
4289
Nick Harper89bc7212018-07-31 19:07:574290} // namespace
4291
nharperb7441ef2016-01-25 23:54:144292// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114293// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:554294// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:114295// follow.
[email protected]f2f31b32013-01-16 23:24:094296TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:554297 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124298 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:554299 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114300
[email protected]ceefd7fd2012-11-29 00:36:244301 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044302 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554303 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504304
[email protected]d1ec59082009-02-11 02:48:154305 TestDelegate d;
4306 {
danakj8522a25b2016-04-16 00:17:364307 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164308 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4309 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194310 r->Start();
4311 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:154312
Wez2a31b222018-06-07 22:07:154313 d.RunUntilComplete();
[email protected]d1ec59082009-02-11 02:48:154314
[email protected]d8fc4722014-06-13 13:17:154315 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474316 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504317 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084318 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:154319 // We should not have followed the redirect.
4320 EXPECT_EQ(0, d.received_redirect_count());
4321 }
4322}
4323
[email protected]8202d0c2011-02-23 08:31:144324// This is the same as the previous test, but checks that the network delegate
4325// registers the error.
[email protected]c044616e2013-02-20 02:01:264326TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554327 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144328
[email protected]ceefd7fd2012-11-29 00:36:244329 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044330 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554331 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504332
[email protected]8202d0c2011-02-23 08:31:144333 TestDelegate d;
4334 {
danakj8522a25b2016-04-16 00:17:364335 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164336 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4337 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194338 r->Start();
4339 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144340
Wez2a31b222018-06-07 22:07:154341 d.RunUntilComplete();
[email protected]8202d0c2011-02-23 08:31:144342
[email protected]d8fc4722014-06-13 13:17:154343 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474344 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:144345 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504346 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144347 // We should not have followed the redirect.
4348 EXPECT_EQ(0, d.received_redirect_count());
4349
4350 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014351 EXPECT_THAT(network_delegate.last_error(),
4352 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144353 }
4354}
4355
[email protected]dc5a5cf2012-09-26 02:49:304356// Tests that we can block and asynchronously return OK in various stages.
4357TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4358 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4359 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4360 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4361 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4362 };
Avi Drissman4365a4782018-12-28 19:26:244363 static const size_t blocking_stages_length = base::size(blocking_stages);
[email protected]dc5a5cf2012-09-26 02:49:304364
tommycli59a63432015-11-06 00:10:554365 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304366
4367 TestDelegate d;
4368 BlockingNetworkDelegate network_delegate(
4369 BlockingNetworkDelegate::USER_CALLBACK);
4370 network_delegate.set_block_on(
4371 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4372 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4373 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4374
4375 TestURLRequestContext context(true);
4376 context.set_network_delegate(&network_delegate);
4377 context.Init();
4378
4379 {
danakj8522a25b2016-04-16 00:17:364380 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164381 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4382 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304383
[email protected]f7022f32014-08-21 16:32:194384 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304385 for (size_t i = 0; i < blocking_stages_length; ++i) {
Wez2a31b222018-06-07 22:07:154386 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304387 EXPECT_EQ(blocking_stages[i],
4388 network_delegate.stage_blocked_for_callback());
4389 network_delegate.DoCallback(OK);
4390 }
Wez2a31b222018-06-07 22:07:154391 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194392 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504393 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304394 EXPECT_EQ(1, network_delegate.created_requests());
4395 EXPECT_EQ(0, network_delegate.destroyed_requests());
4396 }
4397 EXPECT_EQ(1, network_delegate.destroyed_requests());
4398}
4399
[email protected]4c76d7c2011-04-15 19:14:124400// Tests that the network delegate can block and cancel a request.
4401TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554402 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124403
4404 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304405 BlockingNetworkDelegate network_delegate(
4406 BlockingNetworkDelegate::AUTO_CALLBACK);
4407 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4408 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124409
[email protected]d5a4dd62012-05-23 01:41:044410 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554411 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504412
[email protected]4c76d7c2011-04-15 19:14:124413 {
rhalavatib7bd7c792017-04-27 05:25:164414 std::unique_ptr<URLRequest> r(
4415 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4416 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124417
[email protected]f7022f32014-08-21 16:32:194418 r->Start();
Wez2a31b222018-06-07 22:07:154419 d.RunUntilComplete();
[email protected]4c76d7c2011-04-15 19:14:124420
[email protected]d8fc4722014-06-13 13:17:154421 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474422 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504423 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124424 EXPECT_EQ(1, network_delegate.created_requests());
4425 EXPECT_EQ(0, network_delegate.destroyed_requests());
4426 }
4427 EXPECT_EQ(1, network_delegate.destroyed_requests());
4428}
4429
[email protected]b4438d32012-09-27 06:15:304430// Helper function for NetworkDelegateCancelRequestAsynchronously and
4431// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4432// delegate operating in |block_mode| and a request for |url|. It blocks the
4433// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4434void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4435 BlockingNetworkDelegate::Stage stage,
4436 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364437 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304438 BlockingNetworkDelegate network_delegate(block_mode);
4439 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4440 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364441
[email protected]b4438d32012-09-27 06:15:304442 TestURLRequestContext context(true);
4443 context.set_network_delegate(&network_delegate);
4444 context.Init();
[email protected]3cd384c602011-08-31 16:12:364445
4446 {
rhalavatib7bd7c792017-04-27 05:25:164447 std::unique_ptr<URLRequest> r(context.CreateRequest(
4448 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364449
[email protected]f7022f32014-08-21 16:32:194450 r->Start();
Wez2a31b222018-06-07 22:07:154451 d.RunUntilComplete();
[email protected]3cd384c602011-08-31 16:12:364452
[email protected]d8fc4722014-06-13 13:17:154453 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474454 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4455 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4456 EXPECT_FALSE(r->proxy_server().is_valid());
4457 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4458 EXPECT_TRUE(r->proxy_server().is_direct());
4459 } else {
4460 NOTREACHED();
4461 }
maksim.sisovb53724b52016-09-16 05:30:504462 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364463 EXPECT_EQ(1, network_delegate.created_requests());
4464 EXPECT_EQ(0, network_delegate.destroyed_requests());
4465 }
4466 EXPECT_EQ(1, network_delegate.destroyed_requests());
4467}
4468
[email protected]b4438d32012-09-27 06:15:304469// The following 3 tests check that the network delegate can cancel a request
4470// synchronously in various stages of the request.
4471TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554472 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304473 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4474 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554475 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304476}
4477
4478TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554479 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304480 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4481 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554482 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304483}
4484
4485TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554486 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304487 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4488 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554489 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304490}
4491
4492// The following 3 tests check that the network delegate can cancel a request
4493// asynchronously in various stages of the request.
4494TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554495 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304496 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4497 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554498 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304499}
4500
4501TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554502 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304503 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4504 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554505 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304506}
4507
4508TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554509 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304510 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4511 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554512 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304513}
4514
[email protected]4c76d7c2011-04-15 19:14:124515// Tests that the network delegate can block and redirect a request to a new
4516// URL.
4517TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554518 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124519
4520 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304521 BlockingNetworkDelegate network_delegate(
4522 BlockingNetworkDelegate::AUTO_CALLBACK);
4523 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
Eric Romanda790f92018-11-07 19:17:154524 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]4c76d7c2011-04-15 19:14:124525 network_delegate.set_redirect_url(redirect_url);
4526
[email protected]d5a4dd62012-05-23 01:41:044527 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554528 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504529
[email protected]4c76d7c2011-04-15 19:14:124530 {
Eric Romanda790f92018-11-07 19:17:154531 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164532 std::unique_ptr<URLRequest> r(context.CreateRequest(
4533 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124534
[email protected]6be6fa92014-08-06 23:44:564535 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194536 r->Start();
Wez0e717112018-06-18 23:09:224537 d.RunUntilRedirect();
[email protected]4c76d7c2011-04-15 19:14:124538
[email protected]6be6fa92014-08-06 23:44:564539 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194540 EXPECT_EQ(307, r->GetResponseCode());
4541 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564542 std::string location;
Raul Tambre94493c652019-03-11 17:18:354543 ASSERT_TRUE(
4544 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564545 EXPECT_EQ(redirect_url, GURL(location));
4546
4547 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354548 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4549 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154550 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:504551 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474552 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4553 http_test_server()->host_port_pair()),
4554 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094555 // before_send_headers_with_proxy_count only increments for headers sent
4556 // through an untunneled proxy.
4557 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554558 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4559 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274560
maksim.sisovb53724b52016-09-16 05:30:504561 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194562 EXPECT_EQ(redirect_url, r->url());
4563 EXPECT_EQ(original_url, r->original_url());
4564 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124565 EXPECT_EQ(1, network_delegate.created_requests());
4566 EXPECT_EQ(0, network_delegate.destroyed_requests());
4567 }
4568 EXPECT_EQ(1, network_delegate.destroyed_requests());
4569}
4570
[email protected]b813ed72012-04-05 08:21:364571// Tests that the network delegate can block and redirect a request to a new
4572// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4573TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554574 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364575
4576 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304577 BlockingNetworkDelegate network_delegate(
4578 BlockingNetworkDelegate::SYNCHRONOUS);
Eric Romanda790f92018-11-07 19:17:154579 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]b813ed72012-04-05 08:21:364580 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364581
[email protected]d5a4dd62012-05-23 01:41:044582 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554583 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364584
4585 {
Eric Romanda790f92018-11-07 19:17:154586 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164587 std::unique_ptr<URLRequest> r(context.CreateRequest(
4588 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364589
[email protected]6be6fa92014-08-06 23:44:564590 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194591 r->Start();
Wez0e717112018-06-18 23:09:224592 d.RunUntilRedirect();
[email protected]b813ed72012-04-05 08:21:364593
[email protected]6be6fa92014-08-06 23:44:564594 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194595 EXPECT_EQ(307, r->GetResponseCode());
4596 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564597 std::string location;
Raul Tambre94493c652019-03-11 17:18:354598 ASSERT_TRUE(
4599 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564600 EXPECT_EQ(redirect_url, GURL(location));
4601
4602 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354603 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4604 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154605 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564606
maksim.sisovb53724b52016-09-16 05:30:504607 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474608 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4609 http_test_server()->host_port_pair()),
4610 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094611 // before_send_headers_with_proxy_count only increments for headers sent
4612 // through an untunneled proxy.
4613 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554614 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4615 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504616 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194617 EXPECT_EQ(redirect_url, r->url());
4618 EXPECT_EQ(original_url, r->original_url());
4619 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364620 EXPECT_EQ(1, network_delegate.created_requests());
4621 EXPECT_EQ(0, network_delegate.destroyed_requests());
4622 }
4623 EXPECT_EQ(1, network_delegate.destroyed_requests());
4624}
4625
[email protected]3c5ca8c2011-09-29 01:14:514626// Tests that redirects caused by the network delegate preserve POST data.
4627TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554628 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514629
4630 const char kData[] = "hello world";
4631
4632 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304633 BlockingNetworkDelegate network_delegate(
4634 BlockingNetworkDelegate::AUTO_CALLBACK);
4635 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554636 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514637 network_delegate.set_redirect_url(redirect_url);
4638
[email protected]ef2bf422012-05-11 03:27:094639 TestURLRequestContext context(true);
4640 context.set_network_delegate(&network_delegate);
4641 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514642
4643 {
tommycli59a63432015-11-06 00:10:554644 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164645 std::unique_ptr<URLRequest> r(context.CreateRequest(
4646 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194647 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074648 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514649 HttpRequestHeaders headers;
4650 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244651 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194652 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564653
4654 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194655 r->Start();
Wez0e717112018-06-18 23:09:224656 d.RunUntilRedirect();
[email protected]3c5ca8c2011-09-29 01:14:514657
[email protected]6be6fa92014-08-06 23:44:564658 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194659 EXPECT_EQ(307, r->GetResponseCode());
4660 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564661 std::string location;
Raul Tambre94493c652019-03-11 17:18:354662 ASSERT_TRUE(
4663 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564664 EXPECT_EQ(redirect_url, GURL(location));
4665
4666 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354667 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4668 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154669 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564670
maksim.sisovb53724b52016-09-16 05:30:504671 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194672 EXPECT_EQ(redirect_url, r->url());
4673 EXPECT_EQ(original_url, r->original_url());
4674 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514675 EXPECT_EQ(1, network_delegate.created_requests());
4676 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194677 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514678 EXPECT_EQ(kData, d.data_received());
4679 }
4680 EXPECT_EQ(1, network_delegate.destroyed_requests());
4681}
4682
[email protected]5f714132014-03-26 10:41:164683// Tests that the network delegate can block and redirect a request to a new
4684// URL during OnHeadersReceived.
4685TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554686 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164687
4688 TestDelegate d;
4689 BlockingNetworkDelegate network_delegate(
4690 BlockingNetworkDelegate::AUTO_CALLBACK);
4691 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
Eric Romanda790f92018-11-07 19:17:154692 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]5f714132014-03-26 10:41:164693 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4694
4695 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554696 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164697
4698 {
Eric Romanda790f92018-11-07 19:17:154699 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164700 std::unique_ptr<URLRequest> r(context.CreateRequest(
4701 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164702
[email protected]f7022f32014-08-21 16:32:194703 r->Start();
Wez2a31b222018-06-07 22:07:154704 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:164705
maksim.sisovb53724b52016-09-16 05:30:504706 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474707 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4708 http_test_server()->host_port_pair()),
4709 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094710 // before_send_headers_with_proxy_count only increments for headers sent
4711 // through an untunneled proxy.
4712 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554713 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4714 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194715
maksim.sisovb53724b52016-09-16 05:30:504716 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194717 EXPECT_EQ(redirect_url, r->url());
4718 EXPECT_EQ(original_url, r->original_url());
4719 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164720 EXPECT_EQ(2, network_delegate.created_requests());
4721 EXPECT_EQ(0, network_delegate.destroyed_requests());
4722 }
4723 EXPECT_EQ(1, network_delegate.destroyed_requests());
4724}
4725
[email protected]c2911d72011-10-03 22:16:364726// Tests that the network delegate can synchronously complete OnAuthRequired
4727// by taking no action. This indicates that the NetworkDelegate does not want to
4728// handle the challenge, and is passing the buck along to the
4729// URLRequest::Delegate.
4730TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554731 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364732
4733 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304734 BlockingNetworkDelegate network_delegate(
4735 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364736
[email protected]ef2bf422012-05-11 03:27:094737 TestURLRequestContext context(true);
4738 context.set_network_delegate(&network_delegate);
4739 context.Init();
[email protected]c2911d72011-10-03 22:16:364740
[email protected]f3cf9802011-10-28 18:44:584741 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364742
4743 {
tommycli59a63432015-11-06 00:10:554744 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164745 std::unique_ptr<URLRequest> r(context.CreateRequest(
4746 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194747 r->Start();
[email protected]79e1fd62013-06-20 06:50:044748
Wez2a31b222018-06-07 22:07:154749 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044750
maksim.sisovb53724b52016-09-16 05:30:504751 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194752 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044753 EXPECT_TRUE(d.auth_required_called());
4754 EXPECT_EQ(1, network_delegate.created_requests());
4755 EXPECT_EQ(0, network_delegate.destroyed_requests());
4756 }
4757 EXPECT_EQ(1, network_delegate.destroyed_requests());
4758}
4759
4760TEST_F(URLRequestTestHTTP,
4761 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554762 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044763
4764 TestDelegate d;
4765 BlockingNetworkDelegate network_delegate(
4766 BlockingNetworkDelegate::SYNCHRONOUS);
4767
4768 TestURLRequestContext context(true);
4769 context.set_network_delegate(&network_delegate);
4770 context.Init();
4771
4772 d.set_credentials(AuthCredentials(kUser, kSecret));
4773
4774 {
tommycli59a63432015-11-06 00:10:554775 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164776 std::unique_ptr<URLRequest> r(context.CreateRequest(
4777 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194778 r->Start();
[email protected]79e1fd62013-06-20 06:50:044779
Wez2a31b222018-06-07 22:07:154780 d.RunUntilComplete();
shivanisha8061c4202017-06-13 23:35:524781
[email protected]79e1fd62013-06-20 06:50:044782 {
4783 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194784 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524785 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044786 }
4787
maksim.sisovb53724b52016-09-16 05:30:504788 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194789 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364790 EXPECT_TRUE(d.auth_required_called());
4791 EXPECT_EQ(1, network_delegate.created_requests());
4792 EXPECT_EQ(0, network_delegate.destroyed_requests());
4793 }
4794 EXPECT_EQ(1, network_delegate.destroyed_requests());
4795}
4796
4797// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404798// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364799TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554800 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364801
4802 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304803 BlockingNetworkDelegate network_delegate(
4804 BlockingNetworkDelegate::SYNCHRONOUS);
4805 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364806 network_delegate.set_auth_retval(
4807 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4808
[email protected]f3cf9802011-10-28 18:44:584809 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364810
[email protected]ef2bf422012-05-11 03:27:094811 TestURLRequestContext context(true);
4812 context.set_network_delegate(&network_delegate);
4813 context.Init();
[email protected]c2911d72011-10-03 22:16:364814
4815 {
tommycli59a63432015-11-06 00:10:554816 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164817 std::unique_ptr<URLRequest> r(context.CreateRequest(
4818 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194819 r->Start();
Wez2a31b222018-06-07 22:07:154820 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364821
maksim.sisovb53724b52016-09-16 05:30:504822 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194823 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364824 EXPECT_FALSE(d.auth_required_called());
4825 EXPECT_EQ(1, network_delegate.created_requests());
4826 EXPECT_EQ(0, network_delegate.destroyed_requests());
4827 }
4828 EXPECT_EQ(1, network_delegate.destroyed_requests());
4829}
4830
[email protected]79e1fd62013-06-20 06:50:044831// Same as above, but also tests that GetFullRequestHeaders returns the proper
4832// headers (for the first or second request) when called at the proper times.
4833TEST_F(URLRequestTestHTTP,
4834 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554835 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044836
4837 TestDelegate d;
4838 BlockingNetworkDelegate network_delegate(
4839 BlockingNetworkDelegate::SYNCHRONOUS);
4840 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4841 network_delegate.set_auth_retval(
4842 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4843
4844 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4845
4846 TestURLRequestContext context(true);
4847 context.set_network_delegate(&network_delegate);
4848 context.Init();
4849
4850 {
tommycli59a63432015-11-06 00:10:554851 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164852 std::unique_ptr<URLRequest> r(context.CreateRequest(
4853 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194854 r->Start();
Wez2a31b222018-06-07 22:07:154855 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044856
maksim.sisovb53724b52016-09-16 05:30:504857 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194858 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044859 EXPECT_FALSE(d.auth_required_called());
4860 EXPECT_EQ(1, network_delegate.created_requests());
4861 EXPECT_EQ(0, network_delegate.destroyed_requests());
4862
4863 {
4864 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194865 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044866 EXPECT_TRUE(headers.HasHeader("Authorization"));
4867 }
4868 }
4869 EXPECT_EQ(1, network_delegate.destroyed_requests());
4870}
4871
[email protected]c2911d72011-10-03 22:16:364872// Tests that the network delegate can synchronously complete OnAuthRequired
4873// by cancelling authentication.
4874TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554875 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364876
4877 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304878 BlockingNetworkDelegate network_delegate(
4879 BlockingNetworkDelegate::SYNCHRONOUS);
4880 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364881 network_delegate.set_auth_retval(
4882 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4883
[email protected]ef2bf422012-05-11 03:27:094884 TestURLRequestContext context(true);
4885 context.set_network_delegate(&network_delegate);
4886 context.Init();
[email protected]c2911d72011-10-03 22:16:364887
4888 {
tommycli59a63432015-11-06 00:10:554889 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164890 std::unique_ptr<URLRequest> r(context.CreateRequest(
4891 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194892 r->Start();
Wez2a31b222018-06-07 22:07:154893 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364894
maksim.sisovb53724b52016-09-16 05:30:504895 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194896 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364897 EXPECT_FALSE(d.auth_required_called());
4898 EXPECT_EQ(1, network_delegate.created_requests());
4899 EXPECT_EQ(0, network_delegate.destroyed_requests());
4900 }
4901 EXPECT_EQ(1, network_delegate.destroyed_requests());
4902}
4903
4904// Tests that the network delegate can asynchronously complete OnAuthRequired
4905// by taking no action. This indicates that the NetworkDelegate does not want
4906// to handle the challenge, and is passing the buck along to the
4907// URLRequest::Delegate.
4908TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554909 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364910
4911 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304912 BlockingNetworkDelegate network_delegate(
4913 BlockingNetworkDelegate::AUTO_CALLBACK);
4914 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364915
[email protected]ef2bf422012-05-11 03:27:094916 TestURLRequestContext context(true);
4917 context.set_network_delegate(&network_delegate);
4918 context.Init();
[email protected]c2911d72011-10-03 22:16:364919
[email protected]f3cf9802011-10-28 18:44:584920 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364921
4922 {
tommycli59a63432015-11-06 00:10:554923 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164924 std::unique_ptr<URLRequest> r(context.CreateRequest(
4925 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194926 r->Start();
Wez2a31b222018-06-07 22:07:154927 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364928
maksim.sisovb53724b52016-09-16 05:30:504929 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194930 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364931 EXPECT_TRUE(d.auth_required_called());
4932 EXPECT_EQ(1, network_delegate.created_requests());
4933 EXPECT_EQ(0, network_delegate.destroyed_requests());
4934 }
4935 EXPECT_EQ(1, network_delegate.destroyed_requests());
4936}
4937
4938// Tests that the network delegate can asynchronously complete OnAuthRequired
4939// by setting credentials.
4940TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554941 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364942
4943 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304944 BlockingNetworkDelegate network_delegate(
4945 BlockingNetworkDelegate::AUTO_CALLBACK);
4946 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364947 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364948 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4949
[email protected]f3cf9802011-10-28 18:44:584950 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364951 network_delegate.set_auth_credentials(auth_credentials);
4952
[email protected]ef2bf422012-05-11 03:27:094953 TestURLRequestContext context(true);
4954 context.set_network_delegate(&network_delegate);
4955 context.Init();
[email protected]c2911d72011-10-03 22:16:364956
4957 {
tommycli59a63432015-11-06 00:10:554958 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164959 std::unique_ptr<URLRequest> r(context.CreateRequest(
4960 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194961 r->Start();
Wez2a31b222018-06-07 22:07:154962 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364963
maksim.sisovb53724b52016-09-16 05:30:504964 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194965 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364966 EXPECT_FALSE(d.auth_required_called());
4967 EXPECT_EQ(1, network_delegate.created_requests());
4968 EXPECT_EQ(0, network_delegate.destroyed_requests());
4969 }
4970 EXPECT_EQ(1, network_delegate.destroyed_requests());
4971}
4972
4973// Tests that the network delegate can asynchronously complete OnAuthRequired
4974// by cancelling authentication.
4975TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554976 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364977
4978 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304979 BlockingNetworkDelegate network_delegate(
4980 BlockingNetworkDelegate::AUTO_CALLBACK);
4981 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364982 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364983 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4984
[email protected]ef2bf422012-05-11 03:27:094985 TestURLRequestContext context(true);
4986 context.set_network_delegate(&network_delegate);
4987 context.Init();
[email protected]c2911d72011-10-03 22:16:364988
4989 {
tommycli59a63432015-11-06 00:10:554990 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164991 std::unique_ptr<URLRequest> r(context.CreateRequest(
4992 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194993 r->Start();
Wez2a31b222018-06-07 22:07:154994 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364995
maksim.sisovb53724b52016-09-16 05:30:504996 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194997 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364998 EXPECT_FALSE(d.auth_required_called());
4999 EXPECT_EQ(1, network_delegate.created_requests());
5000 EXPECT_EQ(0, network_delegate.destroyed_requests());
5001 }
5002 EXPECT_EQ(1, network_delegate.destroyed_requests());
5003}
5004
David Benjamin0bda12f2018-02-07 19:58:455005// Tests that NetworkDelegate header overrides from the 401 response do not
5006// affect the 200 response. This is a regression test for
5007// https://crbug.com/801237.
5008TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
5009 ASSERT_TRUE(http_test_server()->Start());
5010
5011 TestDelegate d;
5012 d.set_credentials(AuthCredentials(kUser, kSecret));
5013 default_network_delegate_.set_add_header_to_first_response(true);
5014
5015 {
5016 GURL url(http_test_server()->GetURL("/auth-basic"));
Ryan Sleevib8449e02018-07-15 04:31:075017 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455018 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5019 r->Start();
5020
Wez2a31b222018-06-07 22:07:155021 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455022
5023 EXPECT_EQ(OK, d.request_status());
5024 EXPECT_EQ(200, r->GetResponseCode());
5025 EXPECT_TRUE(d.auth_required_called());
5026 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
5027 }
5028
5029 {
5030 GURL url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075031 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455032 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5033 r->Start();
5034
Wez2a31b222018-06-07 22:07:155035 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455036
5037 // Check that set_add_header_to_first_response normally adds a header.
5038 EXPECT_EQ(OK, d.request_status());
5039 EXPECT_EQ(200, r->GetResponseCode());
5040 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
5041 }
5042}
5043
[email protected]9045b8822012-01-13 20:35:355044// Tests that we can handle when a network request was canceled while we were
5045// waiting for the network delegate.
5046// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
5047TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:555048 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355049
5050 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305051 BlockingNetworkDelegate network_delegate(
5052 BlockingNetworkDelegate::USER_CALLBACK);
5053 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:355054
[email protected]ef2bf422012-05-11 03:27:095055 TestURLRequestContext context(true);
5056 context.set_network_delegate(&network_delegate);
5057 context.Init();
[email protected]9045b8822012-01-13 20:35:355058
5059 {
rhalavatib7bd7c792017-04-27 05:25:165060 std::unique_ptr<URLRequest> r(
5061 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5062 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355063
[email protected]f7022f32014-08-21 16:32:195064 r->Start();
Wez2a31b222018-06-07 22:07:155065 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305066 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
5067 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355068 EXPECT_EQ(0, network_delegate.completed_requests());
5069 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195070 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355071 // Ensure that network delegate is notified.
5072 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505073 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355074 EXPECT_EQ(1, network_delegate.created_requests());
5075 EXPECT_EQ(0, network_delegate.destroyed_requests());
5076 }
5077 EXPECT_EQ(1, network_delegate.destroyed_requests());
5078}
5079
5080// Tests that we can handle when a network request was canceled while we were
5081// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:005082// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
5083// callback.
[email protected]9045b8822012-01-13 20:35:355084TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:555085 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355086
5087 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305088 BlockingNetworkDelegate network_delegate(
5089 BlockingNetworkDelegate::USER_CALLBACK);
5090 network_delegate.set_block_on(
5091 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:355092
[email protected]ef2bf422012-05-11 03:27:095093 TestURLRequestContext context(true);
5094 context.set_network_delegate(&network_delegate);
5095 context.Init();
[email protected]9045b8822012-01-13 20:35:355096
5097 {
rhalavatib7bd7c792017-04-27 05:25:165098 std::unique_ptr<URLRequest> r(
5099 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5100 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355101
[email protected]f7022f32014-08-21 16:32:195102 r->Start();
Wez2a31b222018-06-07 22:07:155103 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305104 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
5105 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355106 EXPECT_EQ(0, network_delegate.completed_requests());
5107 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195108 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355109 // Ensure that network delegate is notified.
5110 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505111 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355112 EXPECT_EQ(1, network_delegate.created_requests());
5113 EXPECT_EQ(0, network_delegate.destroyed_requests());
5114 }
5115 EXPECT_EQ(1, network_delegate.destroyed_requests());
5116}
5117
5118// Tests that we can handle when a network request was canceled while we were
5119// waiting for the network delegate.
5120// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
5121TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:555122 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355123
5124 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305125 BlockingNetworkDelegate network_delegate(
5126 BlockingNetworkDelegate::USER_CALLBACK);
5127 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:355128
[email protected]ef2bf422012-05-11 03:27:095129 TestURLRequestContext context(true);
5130 context.set_network_delegate(&network_delegate);
5131 context.Init();
[email protected]9045b8822012-01-13 20:35:355132
5133 {
rhalavatib7bd7c792017-04-27 05:25:165134 std::unique_ptr<URLRequest> r(
5135 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5136 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355137
[email protected]f7022f32014-08-21 16:32:195138 r->Start();
Wez2a31b222018-06-07 22:07:155139 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305140 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
5141 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355142 EXPECT_EQ(0, network_delegate.completed_requests());
5143 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195144 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355145 // Ensure that network delegate is notified.
5146 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505147 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355148 EXPECT_EQ(1, network_delegate.created_requests());
5149 EXPECT_EQ(0, network_delegate.destroyed_requests());
5150 }
5151 EXPECT_EQ(1, network_delegate.destroyed_requests());
5152}
5153
5154// Tests that we can handle when a network request was canceled while we were
5155// waiting for the network delegate.
5156// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:025157TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:555158 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355159
5160 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305161 BlockingNetworkDelegate network_delegate(
5162 BlockingNetworkDelegate::USER_CALLBACK);
5163 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:355164
[email protected]ef2bf422012-05-11 03:27:095165 TestURLRequestContext context(true);
5166 context.set_network_delegate(&network_delegate);
5167 context.Init();
[email protected]9045b8822012-01-13 20:35:355168
5169 {
danakj8522a25b2016-04-16 00:17:365170 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165171 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
5172 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355173
[email protected]f7022f32014-08-21 16:32:195174 r->Start();
Wez2a31b222018-06-07 22:07:155175 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305176 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
5177 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355178 EXPECT_EQ(0, network_delegate.completed_requests());
5179 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195180 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355181 // Ensure that network delegate is notified.
5182 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505183 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355184 EXPECT_EQ(1, network_delegate.created_requests());
5185 EXPECT_EQ(0, network_delegate.destroyed_requests());
5186 }
5187 EXPECT_EQ(1, network_delegate.destroyed_requests());
5188}
5189
tommycli59a63432015-11-06 00:10:555190namespace {
5191
danakj8522a25b2016-04-16 00:17:365192std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:555193 const test_server::HttpRequest& request) {
5194 if (request.headers.find("Host") == request.headers.end() ||
5195 request.headers.at("Host") != "www.server-auth.com" ||
5196 request.method != test_server::METHOD_CONNECT) {
5197 return nullptr;
5198 }
5199
danakj8522a25b2016-04-16 00:17:365200 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:555201 new test_server::BasicHttpResponse);
5202 http_response->set_code(HTTP_UNAUTHORIZED);
5203 http_response->AddCustomHeader("WWW-Authenticate",
5204 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:485205 return std::move(http_response);
tommycli59a63432015-11-06 00:10:555206}
5207
5208} // namespace
5209
5210// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:115211// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:555212// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:355213TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:555214 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:125215 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:555216 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115217
[email protected]ceefd7fd2012-11-29 00:36:245218 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:045219 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:555220 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:505221
[email protected]dc651782009-02-14 01:45:085222 TestDelegate d;
5223 {
danakj8522a25b2016-04-16 00:17:365224 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165225 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
5226 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:085227
[email protected]f7022f32014-08-21 16:32:195228 r->Start();
5229 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:085230
Wez2a31b222018-06-07 22:07:155231 d.RunUntilComplete();
[email protected]dc651782009-02-14 01:45:085232
[email protected]d8fc4722014-06-13 13:17:155233 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:475234 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:505235 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:085236 }
5237}
5238
[email protected]b89290212009-08-14 22:37:355239TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:555240 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115241
initial.commit586acc5fe2008-07-26 22:42:525242 TestDelegate d;
5243 {
Ryan Sleevib8449e02018-07-15 04:31:075244 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165245 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5246 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525247
[email protected]f7022f32014-08-21 16:32:195248 r->Start();
5249 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525250
Wez2a31b222018-06-07 22:07:155251 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525252
5253 EXPECT_EQ(1, d.response_started_count());
5254 EXPECT_FALSE(d.received_data_before_response());
5255 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555256 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375257 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555258 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375259 r->GetResponseRemoteEndpoint().port());
[email protected]c31a54592009-09-04 02:36:165260
[email protected]9e743cd2010-03-16 07:03:535261 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:525262 }
initial.commit586acc5fe2008-07-26 22:42:525263}
5264
[email protected]263163f2012-06-14 22:40:345265// This test has the server send a large number of cookies to the client.
5266// To ensure that no number of cookies causes a crash, a galloping binary
5267// search is used to estimate that maximum number of cookies that are accepted
5268// by the browser. Beyond the maximum number, the request will fail with
5269// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:315270#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:305271// http://crbug.com/177916
5272#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
5273#else
5274#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
5275#endif // defined(OS_WIN)
5276TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:555277 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:345278
5279 int lower_bound = 0;
5280 int upper_bound = 1;
5281
5282 // Double the number of cookies until the response header limits are
5283 // exceeded.
5284 while (DoManyCookiesRequest(upper_bound)) {
5285 lower_bound = upper_bound;
5286 upper_bound *= 2;
5287 ASSERT_LT(upper_bound, 1000000);
5288 }
5289
pkasting6b68a162014-12-01 22:10:295290 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:345291 if (tolerance < 2)
5292 tolerance = 2;
5293
5294 // Perform a binary search to find the highest possible number of cookies,
5295 // within the desired tolerance.
5296 while (upper_bound - lower_bound >= tolerance) {
5297 int num_cookies = (lower_bound + upper_bound) / 2;
5298
5299 if (DoManyCookiesRequest(num_cookies))
5300 lower_bound = num_cookies;
5301 else
5302 upper_bound = num_cookies;
5303 }
5304 // Success: the test did not crash.
5305}
5306
[email protected]b89290212009-08-14 22:37:355307TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:555308 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115309
initial.commit586acc5fe2008-07-26 22:42:525310 TestDelegate d;
5311 {
Ryan Sleevib8449e02018-07-15 04:31:075312 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165313 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5314 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525315
[email protected]f7022f32014-08-21 16:32:195316 r->Start();
5317 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525318
Wez2a31b222018-06-07 22:07:155319 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525320
5321 EXPECT_EQ(1, d.response_started_count());
5322 EXPECT_FALSE(d.received_data_before_response());
5323 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555324 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375325 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555326 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375327 r->GetResponseRemoteEndpoint().port());
initial.commit586acc5fe2008-07-26 22:42:525328 }
[email protected]5d7b373e2009-09-02 07:19:035329}
5330
[email protected]79e1fd62013-06-20 06:50:045331TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555332 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045333
5334 TestDelegate d;
5335 {
tommycli59a63432015-11-06 00:10:555336 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075337 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165338 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045339
5340 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195341 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045342
[email protected]f7022f32014-08-21 16:32:195343 r->Start();
5344 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045345
Wez2a31b222018-06-07 22:07:155346 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:045347
5348 EXPECT_EQ(1, d.response_started_count());
5349 EXPECT_FALSE(d.received_data_before_response());
5350 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555351 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375352 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555353 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375354 r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:045355
5356 EXPECT_TRUE(d.have_full_request_headers());
5357 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5358 }
5359}
5360
[email protected]58e32bb2013-01-21 18:23:255361TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555362 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255363
5364 TestDelegate d;
5365 {
Ryan Sleevib8449e02018-07-15 04:31:075366 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165367 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5368 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255369
[email protected]f7022f32014-08-21 16:32:195370 r->Start();
5371 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255372
Wez2a31b222018-06-07 22:07:155373 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255374
5375 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195376 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255377 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5378
5379 EXPECT_EQ(1, d.response_started_count());
5380 EXPECT_FALSE(d.received_data_before_response());
5381 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555382 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375383 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555384 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375385 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:255386 }
5387}
5388
tommycli59a63432015-11-06 00:10:555389// TODO(svaldez): Update tests to use EmbeddedTestServer.
5390#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395391TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555392 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555393 base::FilePath(kTestFilePath));
5394
5395 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395396
5397 // Parameter that specifies the Content-Length field in the response:
5398 // C - Compressed length.
5399 // U - Uncompressed length.
5400 // L - Large length (larger than both C & U).
5401 // M - Medium length (between C & U).
5402 // S - Small length (smaller than both C & U).
5403 const char test_parameters[] = "CULMS";
Avi Drissman4365a4782018-12-28 19:26:245404 const int num_tests = base::size(test_parameters) - 1; // Skip NULL.
[email protected]aad63572011-05-24 20:14:395405 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445406 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395407 // S has too little data, but we seem to accept it.
5408 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375409 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395410
xunjielifb4da222016-07-14 18:38:595411 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:195412 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
xunjielifb4da222016-07-14 18:38:595413 file_path = file_path.Append(kTestFilePath);
5414 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5415 std::string expected_content;
5416 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5417
5418 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395419 TestDelegate d;
5420 {
tommycli59a63432015-11-06 00:10:555421 std::string test_file = base::StringPrintf(
5422 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395423
[email protected]ceefd7fd2012-11-29 00:36:245424 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095425 TestURLRequestContext context(true);
5426 context.set_network_delegate(&network_delegate);
5427 context.Init();
[email protected]87a09a92011-07-14 15:50:505428
rhalavatib7bd7c792017-04-27 05:25:165429 std::unique_ptr<URLRequest> r(
5430 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5431 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195432 r->Start();
5433 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395434
Wez2a31b222018-06-07 22:07:155435 d.RunUntilComplete();
[email protected]aad63572011-05-24 20:14:395436
5437 EXPECT_EQ(1, d.response_started_count());
5438 EXPECT_FALSE(d.received_data_before_response());
5439 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505440 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395441 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505442 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5443 << "\"";
xunjielifb4da222016-07-14 18:38:595444 if (test_parameters[i] == 'S') {
5445 // When content length is smaller than both compressed length and
5446 // uncompressed length, HttpStreamParser might not read the full
5447 // response body.
5448 continue;
5449 }
5450 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395451 } else {
maksim.sisovb53724b52016-09-16 05:30:505452 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395453 << " Parameter = \"" << test_file << "\"";
5454 }
5455 }
5456 }
5457}
tommycli59a63432015-11-06 00:10:555458#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395459
[email protected]58e32bb2013-01-21 18:23:255460TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555461 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255462
tommycli59a63432015-11-06 00:10:555463 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455464 GURL original_url =
tommycli59a63432015-11-06 00:10:555465 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255466 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075467 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165468 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195469 req->Start();
Wez2a31b222018-06-07 22:07:155470 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255471
5472 EXPECT_EQ(1, d.response_started_count());
5473 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195474 EXPECT_EQ(destination_url, req->url());
5475 EXPECT_EQ(original_url, req->original_url());
5476 ASSERT_EQ(2U, req->url_chain().size());
5477 EXPECT_EQ(original_url, req->url_chain()[0]);
5478 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255479
5480 LoadTimingInfo load_timing_info_before_redirect;
5481 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5482 &load_timing_info_before_redirect));
5483 TestLoadTimingNotReused(load_timing_info_before_redirect,
5484 CONNECT_TIMING_HAS_DNS_TIMES);
5485
5486 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195487 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255488 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5489
5490 // Check that a new socket was used on redirect, since the server does not
5491 // supposed keep-alive sockets, and that the times before the redirect are
5492 // before the ones recorded for the second request.
5493 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5494 load_timing_info.socket_log_id);
5495 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5496 load_timing_info.connect_timing.connect_start);
5497}
5498
[email protected]8f1ac082011-04-19 21:14:135499TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555500 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135501
tommycli59a63432015-11-06 00:10:555502 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455503 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555504 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5505 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5506 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135507 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075508 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165509 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195510 req->Start();
Wez2a31b222018-06-07 22:07:155511 d.RunUntilComplete();
[email protected]8f1ac082011-04-19 21:14:135512
5513 EXPECT_EQ(1, d.response_started_count());
5514 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195515 EXPECT_EQ(destination_url, req->url());
5516 EXPECT_EQ(original_url, req->original_url());
5517 ASSERT_EQ(3U, req->url_chain().size());
5518 EXPECT_EQ(original_url, req->url_chain()[0]);
5519 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5520 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135521}
5522
David Benjamina7fde612019-03-15 14:20:585523// This is a regression test for https://crbug.com/942073.
5524TEST_F(URLRequestTestHTTP, RedirectEscaping) {
5525 ASSERT_TRUE(http_test_server()->Start());
5526
5527 // Assemble the destination URL as a string so it is not escaped by GURL.
5528 GURL destination_base = http_test_server()->GetURL("/defaultresponse");
5529 // Add a URL fragment of U+2603 unescaped, U+2603 escaped, and then a UTF-8
5530 // encoding error.
5531 std::string destination_url =
5532 destination_base.spec() + "#\xE2\x98\x83_%E2%98%83_\xE0\xE0";
5533 // Redirect resolution should percent-escape bytes and preserve the UTF-8
5534 // error at the end.
5535 std::string destination_escaped =
5536 destination_base.spec() + "#%E2%98%83_%E2%98%83_%E0%E0";
5537 GURL original_url = http_test_server()->GetURL(
5538 "/server-redirect?" + EscapeQueryParamValue(destination_url, false));
5539 TestDelegate d;
5540 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
5541 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5542 req->Start();
5543 d.RunUntilComplete();
5544
5545 EXPECT_EQ(1, d.response_started_count());
5546 EXPECT_EQ(1, d.received_redirect_count());
5547 EXPECT_EQ(destination_escaped, req->url().spec());
5548 EXPECT_EQ(original_url, req->original_url());
5549 ASSERT_EQ(2U, req->url_chain().size());
5550 EXPECT_EQ(original_url, req->url_chain()[0]);
5551 EXPECT_EQ(destination_escaped, req->url_chain()[1].spec());
5552}
5553
[email protected]abe1c4a2013-10-25 19:28:515554// First and second pieces of information logged by delegates to URLRequests.
5555const char kFirstDelegateInfo[] = "Wonderful delegate";
5556const char kSecondDelegateInfo[] = "Exciting delegate";
5557
5558// Logs delegate information to a URLRequest. The first string is logged
5559// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5560// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5561// another asynchronous call is used to clear the delegate information
5562// before calling a callback. The object then deletes itself.
5563class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5564 public:
David Benjamind1f287bf2018-06-12 01:57:205565 using Callback = base::OnceCallback<void()>;
[email protected]abe1c4a2013-10-25 19:28:515566
5567 // Each time delegate information is added to the URLRequest, the resulting
5568 // load state is checked. The expected load state after each request is
5569 // passed in as an argument.
5570 static void Run(URLRequest* url_request,
5571 LoadState expected_first_load_state,
5572 LoadState expected_second_load_state,
5573 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205574 Callback callback) {
tzik38f920a2018-08-01 04:41:205575 // base::MakeRefCounted<AsyncDelegateLogger> is unavailable here, since the
5576 // constructor of AsyncDelegateLogger is private.
5577 auto logger = base::WrapRefCounted(new AsyncDelegateLogger(
David Benjamind1f287bf2018-06-12 01:57:205578 url_request, expected_first_load_state, expected_second_load_state,
tzik38f920a2018-08-01 04:41:205579 expected_third_load_state, std::move(callback)));
[email protected]abe1c4a2013-10-25 19:28:515580 logger->Start();
5581 }
5582
5583 // Checks that the log entries, starting with log_position, contain the
5584 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5585 // recorded. Returns the index of entry after the expected number of
5586 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465587 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515588 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515589 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5590 if (log_position + 3 >= entries.size()) {
5591 ADD_FAILURE() << "Not enough log entries";
5592 return entries.size();
5593 }
5594 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005595 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5596 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075597 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515598 &delegate_info));
5599 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5600
5601 ++log_position;
mikecirone8b85c432016-09-08 19:11:005602 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5603 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515604
5605 ++log_position;
mikecirone8b85c432016-09-08 19:11:005606 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5607 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075608 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515609 &delegate_info));
5610 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5611
5612 ++log_position;
mikecirone8b85c432016-09-08 19:11:005613 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5614 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515615
5616 return log_position + 1;
5617 }
5618
5619 private:
5620 friend class base::RefCounted<AsyncDelegateLogger>;
5621
5622 AsyncDelegateLogger(URLRequest* url_request,
5623 LoadState expected_first_load_state,
5624 LoadState expected_second_load_state,
5625 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205626 Callback callback)
[email protected]abe1c4a2013-10-25 19:28:515627 : url_request_(url_request),
5628 expected_first_load_state_(expected_first_load_state),
5629 expected_second_load_state_(expected_second_load_state),
5630 expected_third_load_state_(expected_third_load_state),
David Benjamind1f287bf2018-06-12 01:57:205631 callback_(std::move(callback)) {}
[email protected]abe1c4a2013-10-25 19:28:515632
Chris Watkins7a41d3552017-12-01 02:13:275633 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515634
5635 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535636 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515637 LoadStateWithParam load_state = url_request_->GetLoadState();
5638 EXPECT_EQ(expected_first_load_state_, load_state.state);
5639 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455640 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155641 FROM_HERE,
5642 base::BindOnce(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515643 }
5644
5645 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535646 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515647 LoadStateWithParam load_state = url_request_->GetLoadState();
5648 EXPECT_EQ(expected_second_load_state_, load_state.state);
5649 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5650 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5651 } else {
5652 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5653 }
skyostil4891b25b2015-06-11 11:43:455654 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155655 FROM_HERE, base::BindOnce(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515656 }
5657
5658 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535659 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515660 LoadStateWithParam load_state = url_request_->GetLoadState();
5661 EXPECT_EQ(expected_third_load_state_, load_state.state);
5662 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085663 EXPECT_EQ(base::string16(), load_state.param);
David Benjamind1f287bf2018-06-12 01:57:205664 std::move(callback_).Run();
[email protected]abe1c4a2013-10-25 19:28:515665 }
5666
5667 URLRequest* url_request_;
5668 const int expected_first_load_state_;
5669 const int expected_second_load_state_;
5670 const int expected_third_load_state_;
David Benjamind1f287bf2018-06-12 01:57:205671 Callback callback_;
[email protected]abe1c4a2013-10-25 19:28:515672
5673 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5674};
5675
5676// NetworkDelegate that logs delegate information before a request is started,
5677// before headers are sent, when headers are read, and when auth information
5678// is requested. Uses AsyncDelegateLogger.
5679class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5680 public:
Chris Watkins7a41d3552017-12-01 02:13:275681 AsyncLoggingNetworkDelegate() = default;
5682 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515683
5684 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205685 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205686 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:205687 GURL* new_url) override {
David Benjamind1f287bf2018-06-12 01:57:205688 // TestNetworkDelegate always completes synchronously.
5689 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
5690 request, base::NullCallback(), new_url));
5691 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515692 }
5693
ryansturm2343cb62016-06-15 01:09:005694 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205695 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:005696 HttpRequestHeaders* headers) override {
David Benjamind1f287bf2018-06-12 01:57:205697 // TestNetworkDelegate always completes synchronously.
5698 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
5699 request, base::NullCallback(), headers));
5700 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515701 }
5702
dchengb03027d2014-10-21 12:00:205703 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515704 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205705 CompletionOnceCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515706 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165707 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135708 GURL* allowed_unsafe_redirect_url) override {
David Benjamind1f287bf2018-06-12 01:57:205709 // TestNetworkDelegate always completes synchronously.
5710 CHECK_NE(ERR_IO_PENDING,
5711 TestNetworkDelegate::OnHeadersReceived(
5712 request, base::NullCallback(), original_response_headers,
5713 override_response_headers, allowed_unsafe_redirect_url));
5714 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515715 }
5716
dchengb03027d2014-10-21 12:00:205717 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515718 URLRequest* request,
5719 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:205720 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:135721 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515722 AsyncDelegateLogger::Run(
David Benjamind1f287bf2018-06-12 01:57:205723 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5724 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5725 base::BindOnce(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5726 std::move(callback), credentials));
[email protected]abe1c4a2013-10-25 19:28:515727 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5728 }
5729
5730 private:
David Benjamind1f287bf2018-06-12 01:57:205731 static int RunCallbackAsynchronously(URLRequest* request,
5732 CompletionOnceCallback callback) {
5733 AsyncDelegateLogger::Run(request, LOAD_STATE_WAITING_FOR_DELEGATE,
5734 LOAD_STATE_WAITING_FOR_DELEGATE,
5735 LOAD_STATE_WAITING_FOR_DELEGATE,
5736 base::BindOnce(std::move(callback), OK));
[email protected]abe1c4a2013-10-25 19:28:515737 return ERR_IO_PENDING;
5738 }
5739
David Benjamind1f287bf2018-06-12 01:57:205740 static void SetAuthAndResume(AuthCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515741 AuthCredentials* credentials) {
5742 *credentials = AuthCredentials(kUser, kSecret);
David Benjamind1f287bf2018-06-12 01:57:205743 std::move(callback).Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
[email protected]abe1c4a2013-10-25 19:28:515744 }
5745
5746 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5747};
5748
5749// URLRequest::Delegate that logs delegate information when the headers
5750// are received, when each read completes, and during redirects. Uses
5751// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5752//
5753// Inherits from TestDelegate to reuse the TestDelegate code to handle
5754// advancing to the next step in most cases, as well as cancellation.
5755class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5756 public:
5757 enum CancelStage {
5758 NO_CANCEL = 0,
5759 CANCEL_ON_RECEIVED_REDIRECT,
5760 CANCEL_ON_RESPONSE_STARTED,
5761 CANCEL_ON_READ_COMPLETED
5762 };
5763
5764 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5765 : cancel_stage_(cancel_stage) {
5766 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5767 set_cancel_in_received_redirect(true);
5768 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5769 set_cancel_in_response_started(true);
5770 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5771 set_cancel_in_received_data(true);
5772 }
Chris Watkins7a41d3552017-12-01 02:13:275773 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515774
5775 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205776 void OnReceivedRedirect(URLRequest* request,
5777 const RedirectInfo& redirect_info,
5778 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515779 *defer_redirect = true;
5780 AsyncDelegateLogger::Run(
5781 request,
5782 LOAD_STATE_WAITING_FOR_DELEGATE,
5783 LOAD_STATE_WAITING_FOR_DELEGATE,
5784 LOAD_STATE_WAITING_FOR_DELEGATE,
5785 base::Bind(
5786 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595787 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515788 }
5789
maksim.sisov0f4aa142016-09-05 05:55:285790 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515791 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285792 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5793 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5794 base::Bind(
5795 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5796 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515797 }
5798
dchengb03027d2014-10-21 12:00:205799 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515800 AsyncDelegateLogger::Run(
5801 request,
5802 LOAD_STATE_IDLE,
5803 LOAD_STATE_IDLE,
5804 LOAD_STATE_IDLE,
5805 base::Bind(
5806 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5807 base::Unretained(this), request, bytes_read));
5808 }
5809
5810 private:
5811 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595812 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515813 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595814 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515815 // FollowDeferredRedirect should not be called after cancellation.
5816 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5817 return;
Arthur Sonzognib8465ff72019-01-04 18:44:355818 if (!defer_redirect) {
5819 request->FollowDeferredRedirect(base::nullopt /* removed_headers */,
5820 base::nullopt /* modified_headers */);
5821 }
[email protected]abe1c4a2013-10-25 19:28:515822 }
5823
maksim.sisov0f4aa142016-09-05 05:55:285824 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515825 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285826 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515827 }
5828
5829 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5830 // The parent class continues the request.
5831 TestDelegate::OnReadCompleted(request, bytes_read);
5832 }
5833
5834 const CancelStage cancel_stage_;
5835
5836 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5837};
5838
5839// Tests handling of delegate info before a request starts.
5840TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555841 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515842
5843 TestDelegate request_delegate;
5844 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:355845 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:515846 context.set_net_log(&net_log_);
5847 context.Init();
5848
5849 {
rhalavatib7bd7c792017-04-27 05:25:165850 std::unique_ptr<URLRequest> r(context.CreateRequest(
5851 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5852 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195853 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515854 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085855 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515856
5857 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195858 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515859 LOAD_STATE_WAITING_FOR_DELEGATE,
5860 LOAD_STATE_WAITING_FOR_DELEGATE,
5861 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195862 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515863
Wez2a31b222018-06-07 22:07:155864 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515865
[email protected]f7022f32014-08-21 16:32:195866 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505867 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515868 }
5869
mmenke43758e62015-05-04 21:09:465870 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515871 net_log_.GetEntries(&entries);
5872 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005873 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515874
5875 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5876
5877 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005878 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5879 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515880}
5881
5882// Tests handling of delegate info from a network delegate.
5883TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555884 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515885
5886 TestDelegate request_delegate;
5887 AsyncLoggingNetworkDelegate network_delegate;
5888 TestURLRequestContext context(true);
5889 context.set_network_delegate(&network_delegate);
5890 context.set_net_log(&net_log_);
5891 context.Init();
5892
5893 {
rhalavatib7bd7c792017-04-27 05:25:165894 std::unique_ptr<URLRequest> r(context.CreateRequest(
5895 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
5896 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195897 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515898 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085899 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515900
[email protected]f7022f32014-08-21 16:32:195901 r->Start();
Wez2a31b222018-06-07 22:07:155902 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515903
[email protected]f7022f32014-08-21 16:32:195904 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505905 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515906 EXPECT_EQ(1, network_delegate.created_requests());
5907 EXPECT_EQ(0, network_delegate.destroyed_requests());
5908 }
5909 EXPECT_EQ(1, network_delegate.destroyed_requests());
5910
5911 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465912 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515913 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155914 static const NetLogEventType kExpectedEvents[] = {
5915 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5916 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5917 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5918 };
5919 for (NetLogEventType event : kExpectedEvents) {
5920 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515921 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155922 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515923
5924 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5925 log_position + 1);
5926
5927 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155928 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005929 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515930 }
5931
mikecirone8b85c432016-09-08 19:11:005932 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5933 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515934}
5935
5936// Tests handling of delegate info from a network delegate in the case of an
5937// HTTP redirect.
5938TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555939 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515940
5941 TestDelegate request_delegate;
5942 AsyncLoggingNetworkDelegate network_delegate;
5943 TestURLRequestContext context(true);
5944 context.set_network_delegate(&network_delegate);
5945 context.set_net_log(&net_log_);
5946 context.Init();
5947
5948 {
danakj8522a25b2016-04-16 00:17:365949 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555950 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165951 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195952 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515953 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085954 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515955
[email protected]f7022f32014-08-21 16:32:195956 r->Start();
Wez2a31b222018-06-07 22:07:155957 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515958
[email protected]f7022f32014-08-21 16:32:195959 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505960 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515961 EXPECT_EQ(2, network_delegate.created_requests());
5962 EXPECT_EQ(0, network_delegate.destroyed_requests());
5963 }
5964 EXPECT_EQ(1, network_delegate.destroyed_requests());
5965
5966 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465967 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515968 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155969 static const NetLogEventType kExpectedEvents[] = {
5970 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5971 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5972 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5973 };
5974 for (NetLogEventType event : kExpectedEvents) {
5975 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515976 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155977 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515978
David Benjamin9776ca22018-06-13 00:00:155979 log_position =
5980 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:515981
5982 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155983 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005984 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515985 }
5986
5987 // The URLRequest::Delegate then gets informed about the redirect.
5988 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155989 entries, log_position + 1,
5990 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
mikecirone8b85c432016-09-08 19:11:005991 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515992
5993 // The NetworkDelegate logged information in the same three events as before.
David Benjamin9776ca22018-06-13 00:00:155994 for (NetLogEventType event : kExpectedEvents) {
5995 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515996 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155997 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515998
5999 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6000 log_position + 1);
6001
6002 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156003 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006004 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516005 }
6006
mikecirone8b85c432016-09-08 19:11:006007 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6008 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516009}
6010
6011// Tests handling of delegate info from a network delegate in the case of HTTP
6012// AUTH.
6013TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:556014 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516015
6016 TestDelegate request_delegate;
6017 AsyncLoggingNetworkDelegate network_delegate;
6018 TestURLRequestContext context(true);
6019 context.set_network_delegate(&network_delegate);
6020 context.set_net_log(&net_log_);
6021 context.Init();
6022
6023 {
rhalavatib7bd7c792017-04-27 05:25:166024 std::unique_ptr<URLRequest> r(context.CreateRequest(
6025 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
6026 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196027 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516028 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086029 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516030
[email protected]f7022f32014-08-21 16:32:196031 r->Start();
Wez2a31b222018-06-07 22:07:156032 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516033
[email protected]f7022f32014-08-21 16:32:196034 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506035 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516036 EXPECT_EQ(1, network_delegate.created_requests());
6037 EXPECT_EQ(0, network_delegate.destroyed_requests());
6038 }
6039 EXPECT_EQ(1, network_delegate.destroyed_requests());
6040
6041 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466042 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516043 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:156044 static const NetLogEventType kExpectedEvents[] = {
6045 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6046 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6047 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6048 NetLogEventType::NETWORK_DELEGATE_AUTH_REQUIRED,
6049 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6050 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6051 };
6052 for (NetLogEventType event : kExpectedEvents) {
6053 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516054 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156055 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516056
David Benjamin9776ca22018-06-13 00:00:156057 log_position =
6058 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516059
6060 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156061 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006062 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516063 }
6064
mikecirone8b85c432016-09-08 19:11:006065 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6066 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516067}
6068
tommycli59a63432015-11-06 00:10:556069// TODO(svaldez): Update tests to use EmbeddedTestServer.
6070#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516071// Tests handling of delegate info from a URLRequest::Delegate.
6072TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:556073 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:556074 base::FilePath(kTestFilePath));
6075
6076 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:516077
6078 AsyncLoggingUrlRequestDelegate request_delegate(
6079 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6080 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356081 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516082 context.set_net_log(&net_log_);
6083 context.Init();
6084
6085 {
6086 // A chunked response with delays between chunks is used to make sure that
6087 // attempts by the URLRequest delegate to log information while reading the
6088 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:486089 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:516090 // that it occurs.
danakj8522a25b2016-04-16 00:17:366091 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556092 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166093 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196094 LoadStateWithParam load_state = r->GetLoadState();
6095 r->Start();
Wez2a31b222018-06-07 22:07:156096 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516097
[email protected]f7022f32014-08-21 16:32:196098 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506099 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516100 }
6101
mmenke43758e62015-05-04 21:09:466102 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516103 net_log_.GetEntries(&entries);
6104
[email protected]1826a402014-01-08 15:40:486105 size_t log_position = 0;
6106
[email protected]abe1c4a2013-10-25 19:28:516107 // The delegate info should only have been logged on header complete. Other
6108 // times it should silently be ignored.
David Benjamin9776ca22018-06-13 00:00:156109 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
6110 entries, 0, NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST));
mikecirone8b85c432016-09-08 19:11:006111 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156112 entries, log_position + 1,
6113 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
mikecirone8b85c432016-09-08 19:11:006114 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516115
David Benjamin9776ca22018-06-13 00:00:156116 log_position =
6117 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516118
6119 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156120 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6121 entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006122 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516123
mikecirone8b85c432016-09-08 19:11:006124 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6125 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516126 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
David Benjamin9776ca22018-06-13 00:00:156127 entries, log_position + 1,
6128 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED));
[email protected]abe1c4a2013-10-25 19:28:516129}
tommycli59a63432015-11-06 00:10:556130#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516131
6132// Tests handling of delegate info from a URLRequest::Delegate in the case of
6133// an HTTP redirect.
6134TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:556135 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516136
6137 AsyncLoggingUrlRequestDelegate request_delegate(
6138 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6139 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356140 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516141 context.set_net_log(&net_log_);
6142 context.Init();
6143
6144 {
danakj8522a25b2016-04-16 00:17:366145 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556146 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166147 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196148 LoadStateWithParam load_state = r->GetLoadState();
6149 r->Start();
Wez2a31b222018-06-07 22:07:156150 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516151
[email protected]f7022f32014-08-21 16:32:196152 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506153 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516154 }
6155
mmenke43758e62015-05-04 21:09:466156 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516157 net_log_.GetEntries(&entries);
6158
6159 // Delegate info should only have been logged in OnReceivedRedirect and
6160 // OnResponseStarted.
6161 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156162 static const NetLogEventType kExpectedEvents[] = {
6163 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6164 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6165 };
6166 for (NetLogEventType event : kExpectedEvents) {
6167 SCOPED_TRACE(NetLog::EventTypeToString(event));
6168 log_position = ExpectLogContainsSomewhereAfter(entries, log_position, event,
6169 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516170
David Benjamin9776ca22018-06-13 00:00:156171 log_position =
6172 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516173
6174 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156175 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006176 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516177 }
6178
mikecirone8b85c432016-09-08 19:11:006179 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6180 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516181}
6182
6183// Tests handling of delegate info from a URLRequest::Delegate in the case of
6184// an HTTP redirect, with cancellation at various points.
6185TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:556186 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516187
6188 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
6189 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
6190 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
6191 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
6192 };
6193
David Benjamin9776ca22018-06-13 00:00:156194 for (auto cancel_stage : kCancelStages) {
6195 AsyncLoggingUrlRequestDelegate request_delegate(cancel_stage);
vishal.b62985ca92015-04-17 08:45:516196 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046197 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356198 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516199 context.set_net_log(&net_log);
6200 context.Init();
6201
6202 {
danakj8522a25b2016-04-16 00:17:366203 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556204 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166205 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196206 LoadStateWithParam load_state = r->GetLoadState();
6207 r->Start();
Wez2a31b222018-06-07 22:07:156208 request_delegate.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506209 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
Wez2a31b222018-06-07 22:07:156210
6211 // Spin the message loop to run AsyncDelegateLogger task(s) posted after
6212 // the |request_delegate| completion task.
6213 base::RunLoop().RunUntilIdle();
[email protected]abe1c4a2013-10-25 19:28:516214 }
6215
mmenke43758e62015-05-04 21:09:466216 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516217 net_log.GetEntries(&entries);
6218
6219 // Delegate info is always logged in both OnReceivedRedirect and
6220 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6221 // OnResponseStarted delegate call is after cancellation, but logging is
6222 // still currently supported in that call.
6223 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156224 static const NetLogEventType kExpectedEvents[] = {
6225 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6226 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6227 };
6228 for (NetLogEventType event : kExpectedEvents) {
6229 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516230 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156231 entries, log_position, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516232
David Benjamin9776ca22018-06-13 00:00:156233 log_position =
6234 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516235
6236 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156237 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006238 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516239 }
6240
mikecirone8b85c432016-09-08 19:11:006241 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6242 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516243 }
6244}
6245
[email protected]847c0fa92012-11-06 16:37:426246namespace {
6247
6248const char kExtraHeader[] = "Allow-Snafu";
6249const char kExtraValue[] = "fubar";
6250
6251class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206252 void OnReceivedRedirect(URLRequest* request,
6253 const RedirectInfo& redirect_info,
6254 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596255 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426256 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6257 }
6258};
6259
6260} // namespace
6261
6262TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556263 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426264
tommycli59a63432015-11-06 00:10:556265 GURL destination_url =
6266 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6267 GURL original_url =
6268 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426269 RedirectWithAdditionalHeadersDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076270 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166271 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196272 req->Start();
Wez2a31b222018-06-07 22:07:156273 d.RunUntilComplete();
[email protected]847c0fa92012-11-06 16:37:426274
6275 std::string value;
[email protected]f7022f32014-08-21 16:32:196276 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426277 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6278 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196279 EXPECT_FALSE(req->is_pending());
6280 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426281 EXPECT_EQ(kExtraValue, d.data_received());
6282}
6283
[email protected]251a1b92012-11-13 11:01:096284namespace {
6285
6286const char kExtraHeaderToRemove[] = "To-Be-Removed";
6287
6288class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206289 void OnReceivedRedirect(URLRequest* request,
6290 const RedirectInfo& redirect_info,
6291 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596292 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096293 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6294 }
6295};
6296
6297} // namespace
6298
6299TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556300 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096301
tommycli59a63432015-11-06 00:10:556302 GURL destination_url = http_test_server()->GetURL(
6303 "/echoheader?" + std::string(kExtraHeaderToRemove));
6304 GURL original_url =
6305 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096306 RedirectWithHeaderRemovalDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076307 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166308 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196309 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6310 req->Start();
Wez2a31b222018-06-07 22:07:156311 d.RunUntilComplete();
[email protected]251a1b92012-11-13 11:01:096312
6313 std::string value;
[email protected]f7022f32014-08-21 16:32:196314 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096315 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196316 EXPECT_FALSE(req->is_pending());
6317 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096318 EXPECT_EQ("None", d.data_received());
6319}
6320
mmenke94f1bd92016-12-07 21:13:056321TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446322 TestDelegate d;
6323 {
Ryan Sleevib8449e02018-07-15 04:31:076324 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166325 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6326 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446327
[email protected]f7022f32014-08-21 16:32:196328 r->Start();
6329 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446330
[email protected]f7022f32014-08-21 16:32:196331 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446332
Wez2a31b222018-06-07 22:07:156333 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446334
6335 // We expect to receive OnResponseStarted even though the request has been
6336 // cancelled.
6337 EXPECT_EQ(1, d.response_started_count());
6338 EXPECT_EQ(0, d.bytes_received());
6339 EXPECT_FALSE(d.received_data_before_response());
6340 }
6341}
6342
mmenke94f1bd92016-12-07 21:13:056343TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556344 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446345
6346 TestDelegate d;
6347 {
Ryan Sleevib8449e02018-07-15 04:31:076348 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166349 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6350 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446351
6352 d.set_cancel_in_response_started(true);
6353
[email protected]f7022f32014-08-21 16:32:196354 r->Start();
6355 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446356
Wez2a31b222018-06-07 22:07:156357 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446358
6359 EXPECT_EQ(1, d.response_started_count());
6360 EXPECT_EQ(0, d.bytes_received());
6361 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506362 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446363 }
6364}
6365
mmenke94f1bd92016-12-07 21:13:056366TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556367 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446368
6369 TestDelegate d;
6370 {
Ryan Sleevib8449e02018-07-15 04:31:076371 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166372 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6373 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056374
6375 d.set_cancel_in_received_data(true);
6376
6377 r->Start();
6378 EXPECT_TRUE(r->is_pending());
6379
Wez2a31b222018-06-07 22:07:156380 d.RunUntilComplete();
mmenke94f1bd92016-12-07 21:13:056381
6382 EXPECT_EQ(1, d.response_started_count());
6383 EXPECT_NE(0, d.received_bytes_count());
6384 EXPECT_FALSE(d.received_data_before_response());
6385 EXPECT_EQ(ERR_ABORTED, d.request_status());
6386 }
6387}
6388
6389TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6390 ASSERT_TRUE(http_test_server()->Start());
6391
6392 TestDelegate d;
6393 {
6394 // This returns an empty response (With headers).
Ryan Sleevib8449e02018-07-15 04:31:076395 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166396 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6397 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446398
6399 d.set_cancel_in_received_data(true);
6400
[email protected]f7022f32014-08-21 16:32:196401 r->Start();
6402 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446403
Wez2a31b222018-06-07 22:07:156404 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446405
6406 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056407 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446408 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506409 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446410 }
6411}
6412
mmenke94f1bd92016-12-07 21:13:056413TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556414 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446415
6416 TestDelegate d;
6417 {
Ryan Sleevib8449e02018-07-15 04:31:076418 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166419 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6420 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446421
[email protected]f7022f32014-08-21 16:32:196422 r->Start();
6423 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446424
6425 // The request will be implicitly canceled when it is destroyed. The
6426 // test delegate must not post a quit message when this happens because
6427 // this test doesn't actually have a message loop. The quit message would
6428 // get put on this thread's message queue and the next test would exit
6429 // early, causing problems.
Wez0e717112018-06-18 23:09:226430 d.set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:446431 }
6432 // expect things to just cleanup properly.
6433
kimwjdalsl2bb4ff02015-12-16 22:06:026434 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446435 // message loop
6436 EXPECT_FALSE(d.received_data_before_response());
6437 EXPECT_EQ(0, d.bytes_received());
6438}
6439
mmenke94f1bd92016-12-07 21:13:056440TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556441 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446442
6443 // populate cache
6444 {
6445 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076446 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166447 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6448 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196449 r->Start();
Wez2a31b222018-06-07 22:07:156450 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506451 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446452 }
6453
6454 // cancel read from cache (see bug 990242)
6455 {
6456 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076457 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166458 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6459 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196460 r->Start();
6461 r->Cancel();
Wez2a31b222018-06-07 22:07:156462 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446463
maksim.sisovb53724b52016-09-16 05:30:506464 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446465 EXPECT_EQ(1, d.response_started_count());
6466 EXPECT_EQ(0, d.bytes_received());
6467 EXPECT_FALSE(d.received_data_before_response());
6468 }
6469}
6470
6471TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556472 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446473 HTTPUploadDataOperationTest("POST");
6474}
6475
6476TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556477 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446478 HTTPUploadDataOperationTest("PUT");
6479}
6480
6481TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556482 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446483
6484 TestDelegate d;
6485 {
Ryan Sleevib8449e02018-07-15 04:31:076486 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166487 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6488 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196489 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446490
[email protected]f7022f32014-08-21 16:32:196491 r->Start();
6492 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446493
Wez2a31b222018-06-07 22:07:156494 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446495
maksim.sisovb53724b52016-09-16 05:30:506496 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6497 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446498
6499 EXPECT_FALSE(d.received_data_before_response());
6500 EXPECT_TRUE(d.data_received().empty());
6501 }
6502}
6503
6504TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556505 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446506
6507 TestDelegate d;
6508 {
Ryan Sleevib8449e02018-07-15 04:31:076509 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166510 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6511 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196512 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446513
[email protected]6cdfd7f2013-02-08 20:40:156514 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196515 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026516 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446517
danakj8522a25b2016-04-16 00:17:366518 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446519
[email protected]6cdfd7f2013-02-08 20:40:156520 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196521 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476522 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446523 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196524 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146525 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076526 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046527 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6528 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446529
[email protected]f7022f32014-08-21 16:32:196530 r->Start();
6531 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446532
Wez2a31b222018-06-07 22:07:156533 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446534
avibf0746c2015-12-09 19:53:146535 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296536 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6537 ASSERT_LE(size64, std::numeric_limits<int>::max());
6538 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366539 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446540
[email protected]7600d0b2013-12-08 21:43:306541 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446542
maksim.sisovb53724b52016-09-16 05:30:506543 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6544 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446545
6546 EXPECT_FALSE(d.received_data_before_response());
6547
[email protected]329b68b2012-11-14 17:54:276548 EXPECT_EQ(size, d.bytes_received());
6549 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446550 }
6551}
6552
[email protected]999dd8c2013-11-12 06:45:546553TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556554 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546555
6556 TestDelegate d;
6557 {
Ryan Sleevib8449e02018-07-15 04:31:076558 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166559 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6560 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196561 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546562
danakj8522a25b2016-04-16 00:17:366563 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546564
Jeremy Roman0579ed62017-08-29 15:56:196565 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456566 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546567 base::FilePath(FILE_PATH_LITERAL(
6568 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076569 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046570 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6571 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546572
[email protected]f7022f32014-08-21 16:32:196573 r->Start();
6574 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546575
Wez2a31b222018-06-07 22:07:156576 d.RunUntilComplete();
[email protected]999dd8c2013-11-12 06:45:546577
[email protected]999dd8c2013-11-12 06:45:546578 EXPECT_TRUE(d.request_failed());
6579 EXPECT_FALSE(d.received_data_before_response());
6580 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506581 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546582 }
6583}
6584
mmenke56b0cbb912016-03-28 21:34:536585namespace {
6586
6587// Adds a standard set of data to an upload for chunked upload integration
6588// tests.
6589void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6590 writer->AppendData("a", 1, false);
6591 writer->AppendData("bcd", 3, false);
6592 writer->AppendData("this is a longer chunk than before.", 35, false);
6593 writer->AppendData("\r\n\r\n", 4, false);
6594 writer->AppendData("0", 1, false);
6595 writer->AppendData("2323", 4, true);
6596}
6597
6598// Checks that the upload data added in AddChunksToUpload() was echoed back from
6599// the server.
6600void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6601 // This should match the chunks sent by AddChunksToUpload().
6602 const std::string expected_data =
6603 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6604
maksim.sisovb53724b52016-09-16 05:30:506605 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6606 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536607
6608 EXPECT_FALSE(d->received_data_before_response());
6609
6610 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6611 EXPECT_EQ(expected_data, d->data_received());
6612}
6613
6614} // namespace
6615
[email protected]316c1e5e2012-09-12 15:17:446616TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556617 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446618
6619 TestDelegate d;
6620 {
Ryan Sleevib8449e02018-07-15 04:31:076621 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166622 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6623 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366624 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536625 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366626 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536627 upload_data_stream->CreateWriter();
6628 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196629 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536630 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196631 r->Start();
6632 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446633
Wez2a31b222018-06-07 22:07:156634 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446635
[email protected]f7022f32014-08-21 16:32:196636 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446637 }
6638}
6639
[email protected]329b68b2012-11-14 17:54:276640TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556641 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276642
6643 TestDelegate d;
6644 {
Ryan Sleevib8449e02018-07-15 04:31:076645 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166646 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6647 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366648 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536649 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366650 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536651 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046652 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196653 r->set_method("POST");
6654 r->Start();
6655 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536656 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156657 d.RunUntilComplete();
[email protected]329b68b2012-11-14 17:54:276658
[email protected]f7022f32014-08-21 16:32:196659 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276660 }
6661}
6662
Asanka Herathf05753e2018-08-16 17:38:206663TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556664 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446665
6666 TestDelegate d;
6667 {
Ryan Sleevib8449e02018-07-15 04:31:076668 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166669 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6670 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366671 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536672 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366673 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536674 upload_data_stream->CreateWriter();
6675 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196676 r->set_method("POST");
6677 r->Start();
6678 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446679
Asanka Herathf05753e2018-08-16 17:38:206680 // Pump messages until we start sending headers..
[email protected]255620da2013-08-19 13:14:296681 base::RunLoop().RunUntilIdle();
Asanka Herathf05753e2018-08-16 17:38:206682
6683 // And now wait for completion.
6684 base::RunLoop run_loop;
6685 d.set_on_complete(run_loop.QuitClosure());
mmenke56b0cbb912016-03-28 21:34:536686 AddDataToUpload(writer.get());
Asanka Herathf05753e2018-08-16 17:38:206687 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:446688
[email protected]f7022f32014-08-21 16:32:196689 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446690 }
6691}
6692
6693TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556694 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446695
6696 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076697 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166698 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6699 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196700 req->Start();
Wez2a31b222018-06-07 22:07:156701 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446702
[email protected]f7022f32014-08-21 16:32:196703 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446704
6705 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196706 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446707
6708 std::string header;
6709 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6710 EXPECT_EQ("private", header);
6711
6712 header.clear();
6713 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6714 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6715
6716 // The response has two "X-Multiple-Entries" headers.
6717 // This verfies our output has them concatenated together.
6718 header.clear();
6719 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6720 EXPECT_EQ("a, b", header);
6721}
6722
tommycli59a63432015-11-06 00:10:556723// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6724// security state. (see http://crbug.com/550977).
6725#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466726TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556727 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6728 https_test_server.SetSSLConfig(
6729 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6730 https_test_server.ServeFilesFromSourceDirectory(
6731 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466732 ASSERT_TRUE(https_test_server.Start());
6733
tommycli59a63432015-11-06 00:10:556734 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466735 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076736 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166737 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6738 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196739 request->Start();
Wez2a31b222018-06-07 22:07:156740 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466741
6742 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076743 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406744 TransportSecurityState::STSState sts_state;
6745 TransportSecurityState::PKPState pkp_state;
6746 EXPECT_TRUE(
6747 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6748 EXPECT_FALSE(
6749 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6750 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6751 sts_state.upgrade_mode);
6752 EXPECT_TRUE(sts_state.include_subdomains);
6753 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036754#if defined(OS_ANDROID)
6755 // Android's CertVerifyProc does not (yet) handle pins.
6756#else
martijnc0d6b622015-06-30 19:14:406757 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036758#endif
[email protected]37fd55fb2013-06-29 13:13:276759}
6760
estarka5da76702015-04-09 04:00:166761TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556762 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6763 https_test_server.ServeFilesFromSourceDirectory(
6764 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166765 ASSERT_TRUE(https_test_server.Start());
6766 // Make sure this test fails if the test server is changed to not
6767 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556768 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6769 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166770
6771 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076772 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166773 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6774 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166775 request->Start();
Wez2a31b222018-06-07 22:07:156776 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:166777 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076778 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406779 TransportSecurityState::STSState sts_state;
6780 EXPECT_FALSE(
6781 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166782}
6783
estark06e0dac2015-08-07 21:56:016784namespace {
Martijn Croonenb1383da2017-10-11 11:56:356785const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
Matt Mueller230996f12018-10-22 19:39:446786const char kPKPReportUri[] = "http://report-uri.preloaded.test/pkp";
6787const char kPKPHost[] = "with-report-uri-pkp.preloaded.test";
estark06e0dac2015-08-07 21:56:016788} // namespace
6789
Matt Mueller230996f12018-10-22 19:39:446790// Tests that reports get sent on PKP violations when a report-uri is set.
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516791TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
Matt Mueller230996f12018-10-22 19:39:446792 GURL report_uri(kPKPReportUri);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516793 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6794 https_test_server.SetSSLConfig(
6795 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6796 https_test_server.ServeFilesFromSourceDirectory(
6797 base::FilePath(kTestFilePath));
6798 ASSERT_TRUE(https_test_server.Start());
6799
Matt Mueller230996f12018-10-22 19:39:446800 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016801
6802 // Set up a pin for |test_server_hostname|.
6803 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446804 security_state.EnableStaticPinsForTesting();
6805 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016806
6807 MockCertificateReportSender mock_report_sender;
6808 security_state.SetReportSender(&mock_report_sender);
6809
6810 // Set up a MockCertVerifier to trigger a violation of the previously
6811 // set pin.
6812 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6813 ASSERT_TRUE(cert);
6814
6815 MockCertVerifier cert_verifier;
6816 CertVerifyResult verify_result;
6817 verify_result.verified_cert = cert;
6818 verify_result.is_issued_by_known_root = true;
6819 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446820 ASSERT_TRUE(
6821 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016822 verify_result.public_key_hashes.push_back(hash3);
6823 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6824
6825 TestNetworkDelegate network_delegate;
6826 TestURLRequestContext context(true);
6827 context.set_transport_security_state(&security_state);
6828 context.set_network_delegate(&network_delegate);
6829 context.set_cert_verifier(&cert_verifier);
6830 context.Init();
6831
6832 // Now send a request to trigger the violation.
6833 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366834 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446835 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166836 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016837 violating_request->Start();
Wez2a31b222018-06-07 22:07:156838 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016839
6840 // Check that a report was sent.
6841 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6842 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446843 EXPECT_EQ("application/json; charset=utf-8",
6844 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366845 std::unique_ptr<base::Value> value(
Lei Zhanga8b4c5fb2019-02-16 03:02:036846 base::JSONReader::ReadDeprecated(mock_report_sender.latest_report()));
estark06e0dac2015-08-07 21:56:016847 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086848 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016849 base::DictionaryValue* report_dict;
6850 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6851 std::string report_hostname;
6852 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6853 EXPECT_EQ(test_server_hostname, report_hostname);
6854}
6855
Matt Mueller230996f12018-10-22 19:39:446856// Tests that reports do not get sent on requests to static pkp hosts that
6857// don't have pin violations.
6858TEST_F(URLRequestTestHTTP, ProcessPKPWithNoViolation) {
tommycli59a63432015-11-06 00:10:556859 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6860 https_test_server.SetSSLConfig(
6861 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6862 https_test_server.ServeFilesFromSourceDirectory(
6863 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016864 ASSERT_TRUE(https_test_server.Start());
6865
Matt Mueller230996f12018-10-22 19:39:446866 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016867
6868 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446869 security_state.EnableStaticPinsForTesting();
6870 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016871 MockCertificateReportSender mock_report_sender;
6872 security_state.SetReportSender(&mock_report_sender);
6873
Matt Mueller230996f12018-10-22 19:39:446874 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6875 ASSERT_TRUE(cert);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516876 MockCertVerifier mock_cert_verifier;
Matt Mueller230996f12018-10-22 19:39:446877 CertVerifyResult verify_result;
6878 verify_result.verified_cert = cert;
6879 verify_result.is_issued_by_known_root = true;
6880 HashValue hash;
6881 // The expected value of GoodPin1 used by |test_default::kHSTSSource|.
6882 ASSERT_TRUE(
6883 hash.FromString("sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY="));
6884 verify_result.public_key_hashes.push_back(hash);
6885 mock_cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6886
6887 TestNetworkDelegate network_delegate;
estark06e0dac2015-08-07 21:56:016888 TestURLRequestContext context(true);
6889 context.set_transport_security_state(&security_state);
6890 context.set_network_delegate(&network_delegate);
6891 context.set_cert_verifier(&mock_cert_verifier);
estark06e0dac2015-08-07 21:56:016892 context.Init();
6893
6894 // Now send a request that does not trigger the violation.
6895 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366896 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446897 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166898 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016899 request->Start();
Wez2a31b222018-06-07 22:07:156900 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016901
Matt Mueller230996f12018-10-22 19:39:446902 // Check that the request succeeded, a report was not sent and the pkp was
6903 // not bypassed.
6904 EXPECT_EQ(OK, d.request_status());
estark06e0dac2015-08-07 21:56:016905 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6906 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
Matt Mueller230996f12018-10-22 19:39:446907 TransportSecurityState::STSState sts_state;
martijnc0d6b622015-06-30 19:14:406908 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:446909 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
6910 &sts_state, &pkp_state));
6911 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
6912 EXPECT_FALSE(request->ssl_info().pkp_bypassed);
estarka5da76702015-04-09 04:00:166913}
6914
dadriandf302c42016-06-10 18:48:596915TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6916 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6917 https_test_server.SetSSLConfig(
6918 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6919 https_test_server.ServeFilesFromSourceDirectory(
6920 base::FilePath(kTestFilePath));
6921 ASSERT_TRUE(https_test_server.Start());
6922
6923 // Set up a MockCertVerifier to be a local root that violates the pin
6924 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6925 ASSERT_TRUE(cert);
6926
6927 MockCertVerifier cert_verifier;
6928 CertVerifyResult verify_result;
6929 verify_result.verified_cert = cert;
6930 verify_result.is_issued_by_known_root = false;
6931 HashValue hash;
6932 ASSERT_TRUE(
6933 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6934 verify_result.public_key_hashes.push_back(hash);
6935 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
dadriandf302c42016-06-10 18:48:596936
Matt Mueller230996f12018-10-22 19:39:446937 std::string test_server_hostname = kPKPHost;
dadriandf302c42016-06-10 18:48:596938
Matt Mueller230996f12018-10-22 19:39:446939 // Set up PKP
dadriandf302c42016-06-10 18:48:596940 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446941 security_state.EnableStaticPinsForTesting();
6942 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
6943 MockCertificateReportSender mock_report_sender;
6944 security_state.SetReportSender(&mock_report_sender);
dadriandf302c42016-06-10 18:48:596945
6946 TestNetworkDelegate network_delegate;
6947 TestURLRequestContext context(true);
6948 context.set_transport_security_state(&security_state);
6949 context.set_network_delegate(&network_delegate);
6950 context.set_cert_verifier(&cert_verifier);
6951 context.Init();
6952
6953 TestDelegate d;
6954 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446955 https_test_server.GetURL(test_server_hostname, "/simple.html"),
6956 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:596957 request->Start();
Wez2a31b222018-06-07 22:07:156958 d.RunUntilComplete();
dadriandf302c42016-06-10 18:48:596959
Matt Mueller230996f12018-10-22 19:39:446960 // Check that the request succeeded, a report was not sent and the PKP was
6961 // bypassed.
6962 EXPECT_EQ(OK, d.request_status());
6963 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6964 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6965 TransportSecurityState::STSState sts_state;
dadriandf302c42016-06-10 18:48:596966 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:446967 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
6968 &sts_state, &pkp_state));
6969 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
dadriandf302c42016-06-10 18:48:596970 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6971}
6972
[email protected]242d8562012-10-30 21:20:466973TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556974 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6975 https_test_server.SetSSLConfig(
6976 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6977 https_test_server.ServeFilesFromSourceDirectory(
6978 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466979 ASSERT_TRUE(https_test_server.Start());
6980
tommycli59a63432015-11-06 00:10:556981 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166982
[email protected]242d8562012-10-30 21:20:466983 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076984 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:556985 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166986 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196987 request->Start();
Wez2a31b222018-06-07 22:07:156988 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466989
6990 // We should have set parameters from the first header, not the second.
6991 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076992 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406993 TransportSecurityState::STSState sts_state;
6994 EXPECT_TRUE(
6995 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6996 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6997 sts_state.upgrade_mode);
6998 EXPECT_FALSE(sts_state.include_subdomains);
6999 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:467000}
7001
estark1614475f2016-03-10 03:46:477002// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
7003// called.
7004class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
7005 public:
7006 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:277007 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:477008
7009 void OnExpectCTFailed(const HostPortPair& host_port_pair,
7010 const GURL& report_uri,
estarkae028b462017-06-20 23:25:017011 base::Time expiration,
estarkbf1b52962017-05-05 17:05:257012 const X509Certificate* validated_certificate_chain,
7013 const X509Certificate* served_certificate_chain,
7014 const SignedCertificateTimestampAndStatusList&
7015 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:477016 num_failures_++;
7017 }
7018
7019 uint32_t num_failures() { return num_failures_; }
7020
7021 private:
7022 uint32_t num_failures_;
7023};
7024
Emily Stark627238f2017-11-29 03:29:547025// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:477026// for every certificate.
7027class MockCTPolicyEnforcer : public CTPolicyEnforcer {
7028 public:
7029 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:547030 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:277031 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:477032
Emily Stark627238f2017-11-29 03:29:547033 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:477034 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:237035 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:207036 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:477037 return default_result_;
7038 }
7039
Emily Stark627238f2017-11-29 03:29:547040 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:477041 default_result_ = default_result;
7042 }
7043
7044 private:
Emily Stark627238f2017-11-29 03:29:547045 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:477046};
7047
Emily Stark4cfecf072017-08-08 01:05:517048// Tests that Expect CT headers for the preload list are processed correctly.
7049TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:357050 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7051
estark1614475f2016-03-10 03:46:477052 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7053 https_test_server.SetSSLConfig(
7054 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7055 https_test_server.ServeFilesFromSourceDirectory(
7056 base::FilePath(kTestFilePath));
7057 ASSERT_TRUE(https_test_server.Start());
7058
7059 MockExpectCTReporter reporter;
7060 TransportSecurityState transport_security_state;
7061 transport_security_state.enable_static_expect_ct_ = true;
7062 transport_security_state.SetExpectCTReporter(&reporter);
7063
7064 // Set up a MockCertVerifier to accept the certificate that the server sends.
7065 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7066 ASSERT_TRUE(cert);
7067 MockCertVerifier cert_verifier;
7068 CertVerifyResult verify_result;
7069 verify_result.verified_cert = cert;
7070 verify_result.is_issued_by_known_root = true;
7071 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7072
rsleevi22cae1672016-12-28 01:53:367073 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
7074 // CT violation.
7075 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:477076 MockCTPolicyEnforcer ct_policy_enforcer;
7077 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547078 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:477079
7080 TestNetworkDelegate network_delegate;
7081 // Use a MockHostResolver (which by default maps all hosts to
7082 // 127.0.0.1) so that the request can be sent to a site on the Expect
7083 // CT preload list.
7084 MockHostResolver host_resolver;
7085 TestURLRequestContext context(true);
7086 context.set_host_resolver(&host_resolver);
7087 context.set_transport_security_state(&transport_security_state);
7088 context.set_network_delegate(&network_delegate);
7089 context.set_cert_verifier(&cert_verifier);
7090 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:467091 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:477092 context.Init();
7093
7094 // Now send a request to trigger the violation.
7095 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:517096 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:477097 GURL::Replacements replace_host;
7098 replace_host.SetHostStr(kExpectCTStaticHostname);
7099 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:167100 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
7101 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:477102 violating_request->Start();
Wez2a31b222018-06-07 22:07:157103 d.RunUntilComplete();
estark1614475f2016-03-10 03:46:477104
7105 EXPECT_EQ(1u, reporter.num_failures());
7106}
Emily Stark4cfecf072017-08-08 01:05:517107
7108// Tests that Expect CT HTTP headers are processed correctly.
7109TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
7110 base::test::ScopedFeatureList feature_list;
7111 feature_list.InitAndEnableFeature(
7112 TransportSecurityState::kDynamicExpectCTFeature);
7113
7114 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7115 https_test_server.SetSSLConfig(
7116 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7117 https_test_server.ServeFilesFromSourceDirectory(
7118 base::FilePath(kTestFilePath));
7119 ASSERT_TRUE(https_test_server.Start());
7120
7121 MockExpectCTReporter reporter;
7122 TransportSecurityState transport_security_state;
7123 transport_security_state.SetExpectCTReporter(&reporter);
7124
7125 // Set up a MockCertVerifier to accept the certificate that the server sends.
7126 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7127 ASSERT_TRUE(cert);
7128 MockCertVerifier cert_verifier;
7129 CertVerifyResult verify_result;
7130 verify_result.verified_cert = cert;
7131 verify_result.is_issued_by_known_root = true;
7132 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7133
7134 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7135 // compliance.
7136 DoNothingCTVerifier ct_verifier;
7137 MockCTPolicyEnforcer ct_policy_enforcer;
7138 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547139 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517140
7141 TestNetworkDelegate network_delegate;
7142 // Use a MockHostResolver (which by default maps all hosts to
7143 // 127.0.0.1).
7144 MockHostResolver host_resolver;
7145 TestURLRequestContext context(true);
7146 context.set_host_resolver(&host_resolver);
7147 context.set_transport_security_state(&transport_security_state);
7148 context.set_network_delegate(&network_delegate);
7149 context.set_cert_verifier(&cert_verifier);
7150 context.set_cert_transparency_verifier(&ct_verifier);
7151 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7152 context.Init();
7153
7154 // Now send a request to trigger the header processing.
7155 TestDelegate d;
7156 GURL url = https_test_server.GetURL("/expect-ct-header.html");
7157 std::unique_ptr<URLRequest> request(context.CreateRequest(
7158 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7159 request->Start();
Wez2a31b222018-06-07 22:07:157160 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517161
7162 TransportSecurityState::ExpectCTState state;
7163 ASSERT_TRUE(
7164 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7165 EXPECT_TRUE(state.enforce);
7166 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7167}
7168
7169// Tests that if multiple Expect CT HTTP headers are sent, they are all
7170// processed.
7171TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
7172 base::test::ScopedFeatureList feature_list;
7173 feature_list.InitAndEnableFeature(
7174 TransportSecurityState::kDynamicExpectCTFeature);
7175
7176 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7177 https_test_server.SetSSLConfig(
7178 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7179 https_test_server.ServeFilesFromSourceDirectory(
7180 base::FilePath(kTestFilePath));
7181 ASSERT_TRUE(https_test_server.Start());
7182
7183 MockExpectCTReporter reporter;
7184 TransportSecurityState transport_security_state;
7185 transport_security_state.SetExpectCTReporter(&reporter);
7186
7187 // Set up a MockCertVerifier to accept the certificate that the server sends.
7188 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7189 ASSERT_TRUE(cert);
7190 MockCertVerifier cert_verifier;
7191 CertVerifyResult verify_result;
7192 verify_result.verified_cert = cert;
7193 verify_result.is_issued_by_known_root = true;
7194 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7195
7196 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7197 // compliance.
7198 DoNothingCTVerifier ct_verifier;
7199 MockCTPolicyEnforcer ct_policy_enforcer;
7200 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547201 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517202
7203 TestNetworkDelegate network_delegate;
7204 // Use a MockHostResolver (which by default maps all hosts to
7205 // 127.0.0.1).
7206 MockHostResolver host_resolver;
7207 TestURLRequestContext context(true);
7208 context.set_host_resolver(&host_resolver);
7209 context.set_transport_security_state(&transport_security_state);
7210 context.set_network_delegate(&network_delegate);
7211 context.set_cert_verifier(&cert_verifier);
7212 context.set_cert_transparency_verifier(&ct_verifier);
7213 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7214 context.Init();
7215
7216 // Now send a request to trigger the header processing.
7217 TestDelegate d;
7218 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7219 std::unique_ptr<URLRequest> request(context.CreateRequest(
7220 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7221 request->Start();
Wez2a31b222018-06-07 22:07:157222 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517223
7224 TransportSecurityState::ExpectCTState state;
7225 ASSERT_TRUE(
7226 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7227 EXPECT_TRUE(state.enforce);
7228 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7229}
7230
mmenkefd9d15c2017-06-29 13:45:547231#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477232
Lily Chenfec60d92019-01-24 01:16:427233#if BUILDFLAG(ENABLE_REPORTING)
7234
Lily Chend3930e72019-03-01 19:31:117235TEST_F(URLRequestTestHTTP, NetworkErrorLogging_DontReportIfNetworkNotAccessed) {
7236 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7237 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7238 ASSERT_TRUE(https_test_server.Start());
7239 GURL request_url = https_test_server.GetURL("/cachetime");
7240
7241 TestNetworkErrorLoggingService nel_service;
7242 TestURLRequestContext context(true);
7243 context.set_network_error_logging_service(&nel_service);
7244 context.Init();
7245
7246 // Populate the cache.
7247 TestDelegate d;
7248 std::unique_ptr<URLRequest> request(context.CreateRequest(
7249 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7250 request->Start();
7251 d.RunUntilComplete();
7252
7253 ASSERT_EQ(1u, nel_service.errors().size());
7254 const TestNetworkErrorLoggingService::RequestDetails& error =
7255 nel_service.errors()[0];
7256 EXPECT_EQ(request_url, error.uri);
7257 EXPECT_EQ(200, error.status_code);
7258 EXPECT_EQ(OK, error.type);
7259
7260 request = context.CreateRequest(request_url, DEFAULT_PRIORITY, &d,
7261 TRAFFIC_ANNOTATION_FOR_TESTS);
7262 request->Start();
7263 d.RunUntilComplete();
7264
7265 EXPECT_FALSE(request->response_info().network_accessed);
7266 EXPECT_TRUE(request->response_info().was_cached);
7267 // No additional NEL report was generated.
7268 EXPECT_EQ(1u, nel_service.errors().size());
7269}
7270
Lily Chenfec60d92019-01-24 01:16:427271TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicSuccess) {
7272 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7273 https_test_server.ServeFilesFromSourceDirectory(
7274 base::FilePath(kTestFilePath));
7275 ASSERT_TRUE(https_test_server.Start());
7276 GURL request_url = https_test_server.GetURL("/simple.html");
7277
7278 TestNetworkErrorLoggingService nel_service;
7279 TestURLRequestContext context(true);
7280 context.set_network_error_logging_service(&nel_service);
7281 context.Init();
7282
7283 TestDelegate d;
7284 std::unique_ptr<URLRequest> request(context.CreateRequest(
7285 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7286 request->Start();
7287 d.RunUntilComplete();
7288
7289 ASSERT_EQ(1u, nel_service.errors().size());
7290 const TestNetworkErrorLoggingService::RequestDetails& error =
7291 nel_service.errors()[0];
7292 EXPECT_EQ(request_url, error.uri);
7293 EXPECT_EQ(200, error.status_code);
7294 EXPECT_EQ(OK, error.type);
7295}
7296
7297TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicError) {
7298 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7299 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7300 ASSERT_TRUE(https_test_server.Start());
7301 GURL request_url = https_test_server.GetURL("/close-socket");
7302
7303 TestNetworkErrorLoggingService nel_service;
7304 TestURLRequestContext context(true);
7305 context.set_network_error_logging_service(&nel_service);
7306 context.Init();
7307
7308 TestDelegate d;
7309 std::unique_ptr<URLRequest> request(context.CreateRequest(
7310 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7311 request->Start();
7312 d.RunUntilComplete();
7313
7314 ASSERT_EQ(1u, nel_service.errors().size());
7315 const TestNetworkErrorLoggingService::RequestDetails& error =
7316 nel_service.errors()[0];
7317 EXPECT_EQ(request_url, error.uri);
7318 EXPECT_EQ(0, error.status_code);
7319 EXPECT_EQ(ERR_EMPTY_RESPONSE, error.type);
7320}
7321
7322TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Redirect) {
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("/redirect-test.html");
7328 GURL redirect_url = https_test_server.GetURL("/with-headers.html");
7329
7330 TestNetworkErrorLoggingService nel_service;
7331 TestURLRequestContext context(true);
7332 context.set_network_error_logging_service(&nel_service);
7333 context.Init();
7334
7335 TestDelegate d;
7336 std::unique_ptr<URLRequest> request(context.CreateRequest(
7337 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7338 request->Start();
7339 d.RunUntilComplete();
7340
7341 ASSERT_EQ(2u, nel_service.errors().size());
7342 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7343 nel_service.errors()[0];
7344 EXPECT_EQ(request_url, error1.uri);
7345 EXPECT_EQ(302, error1.status_code);
7346 EXPECT_EQ(OK, error1.type);
7347 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7348 nel_service.errors()[1];
7349 EXPECT_EQ(redirect_url, error2.uri);
7350 EXPECT_EQ(200, error2.status_code);
7351 EXPECT_EQ(OK, error2.type);
7352}
7353
Lily Chend3930e72019-03-01 19:31:117354TEST_F(URLRequestTestHTTP, NetworkErrorLogging_RedirectWithoutLocationHeader) {
7355 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7356 https_test_server.ServeFilesFromSourceDirectory(
7357 base::FilePath(kTestFilePath));
7358 ASSERT_TRUE(https_test_server.Start());
7359 GURL request_url = https_test_server.GetURL("/308-without-location-header");
7360
7361 TestNetworkErrorLoggingService nel_service;
7362 TestURLRequestContext context(true);
7363 context.set_network_error_logging_service(&nel_service);
7364 context.Init();
7365
7366 TestDelegate d;
7367 std::unique_ptr<URLRequest> request(context.CreateRequest(
7368 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7369 request->Start();
7370 d.RunUntilComplete();
7371
7372 ASSERT_EQ(1u, nel_service.errors().size());
7373 const TestNetworkErrorLoggingService::RequestDetails& error =
7374 nel_service.errors()[0];
7375 EXPECT_EQ(request_url, error.uri);
7376 EXPECT_EQ(308, error.status_code);
7377 // The body of the response was successfully read.
7378 EXPECT_EQ(OK, error.type);
7379}
7380
Lily Chenfec60d92019-01-24 01:16:427381TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Auth) {
7382 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7383 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7384 ASSERT_TRUE(https_test_server.Start());
7385 GURL request_url = https_test_server.GetURL("/auth-basic");
7386
7387 TestNetworkErrorLoggingService nel_service;
7388 TestURLRequestContext context(true);
7389 context.set_network_error_logging_service(&nel_service);
7390 context.Init();
7391
7392 TestDelegate d;
7393 d.set_credentials(AuthCredentials(kUser, kSecret));
7394 std::unique_ptr<URLRequest> request(context.CreateRequest(
7395 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7396 request->Start();
7397 d.RunUntilComplete();
7398
7399 ASSERT_EQ(2u, nel_service.errors().size());
7400 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7401 nel_service.errors()[0];
7402 EXPECT_EQ(request_url, error1.uri);
7403 EXPECT_EQ(401, error1.status_code);
7404 EXPECT_EQ(OK, error1.type);
7405 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7406 nel_service.errors()[1];
7407 EXPECT_EQ(request_url, error2.uri);
7408 EXPECT_EQ(200, error2.status_code);
7409 EXPECT_EQ(OK, error2.type);
7410}
7411
Lily Chend3930e72019-03-01 19:31:117412TEST_F(URLRequestTestHTTP, NetworkErrorLogging_304Response) {
7413 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7414 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7415 ASSERT_TRUE(https_test_server.Start());
7416 GURL request_url = https_test_server.GetURL("/auth-basic");
7417
7418 TestNetworkErrorLoggingService nel_service;
7419 TestURLRequestContext context(true);
7420 context.set_network_error_logging_service(&nel_service);
7421 context.Init();
7422
7423 // populate the cache
7424 {
7425 TestDelegate d;
7426 d.set_credentials(AuthCredentials(kUser, kSecret));
7427 std::unique_ptr<URLRequest> r(context.CreateRequest(
7428 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7429 r->Start();
7430 d.RunUntilComplete();
7431 }
7432 ASSERT_EQ(2u, nel_service.errors().size());
7433 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7434 nel_service.errors()[0];
7435 EXPECT_EQ(request_url, error1.uri);
7436 EXPECT_EQ(401, error1.status_code);
7437 EXPECT_EQ(OK, error1.type);
7438 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7439 nel_service.errors()[1];
7440 EXPECT_EQ(request_url, error2.uri);
7441 EXPECT_EQ(200, error2.status_code);
7442 EXPECT_EQ(OK, error2.type);
7443
7444 // repeat request with end-to-end validation. since auth-basic results in a
7445 // cachable page, we expect this test to result in a 304. in which case, the
7446 // response should be fetched from the cache.
7447 {
7448 TestDelegate d;
7449 d.set_credentials(AuthCredentials(kUser, kSecret));
7450 std::unique_ptr<URLRequest> r(context.CreateRequest(
7451 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7452 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7453 r->Start();
7454 d.RunUntilComplete();
7455
7456 // Should be the same cached document.
7457 EXPECT_TRUE(r->was_cached());
7458 }
7459 ASSERT_EQ(3u, nel_service.errors().size());
7460 const TestNetworkErrorLoggingService::RequestDetails& error3 =
7461 nel_service.errors()[2];
7462 EXPECT_EQ(request_url, error3.uri);
7463 EXPECT_EQ(304, error3.status_code);
7464 EXPECT_EQ(OK, error3.type);
7465}
7466
7467TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelInResponseStarted) {
Lily Chenfec60d92019-01-24 01:16:427468 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7469 https_test_server.ServeFilesFromSourceDirectory(
7470 base::FilePath(kTestFilePath));
7471 ASSERT_TRUE(https_test_server.Start());
7472 GURL request_url = https_test_server.GetURL("/simple.html");
7473
7474 TestNetworkErrorLoggingService nel_service;
7475 TestURLRequestContext context(true);
7476 context.set_network_error_logging_service(&nel_service);
7477 context.Init();
7478
7479 TestDelegate d;
7480 d.set_cancel_in_response_started(true);
7481 std::unique_ptr<URLRequest> request(context.CreateRequest(
7482 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7483 request->Start();
7484 d.RunUntilComplete();
7485
7486 ASSERT_EQ(1u, nel_service.errors().size());
7487 const TestNetworkErrorLoggingService::RequestDetails& error =
7488 nel_service.errors()[0];
7489 EXPECT_EQ(request_url, error.uri);
7490 EXPECT_EQ(200, error.status_code);
Lily Chend3930e72019-03-01 19:31:117491 // Headers were received and the body should have been read but was not.
7492 EXPECT_EQ(ERR_ABORTED, error.type);
7493}
7494
7495TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelOnDataReceived) {
7496 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7497 https_test_server.ServeFilesFromSourceDirectory(
7498 base::FilePath(kTestFilePath));
7499 ASSERT_TRUE(https_test_server.Start());
7500 GURL request_url = https_test_server.GetURL("/simple.html");
7501
7502 TestNetworkErrorLoggingService nel_service;
7503 TestURLRequestContext context(true);
7504 context.set_network_error_logging_service(&nel_service);
7505 context.Init();
7506
7507 TestDelegate d;
7508 d.set_cancel_in_received_data(true);
7509 std::unique_ptr<URLRequest> request(context.CreateRequest(
7510 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7511 request->Start();
7512 d.RunUntilComplete();
7513
7514 ASSERT_EQ(1u, nel_service.errors().size());
7515 const TestNetworkErrorLoggingService::RequestDetails& error =
7516 nel_service.errors()[0];
7517 EXPECT_EQ(request_url, error.uri);
7518 EXPECT_EQ(200, error.status_code);
7519 // Data was received but the body was not completely read.
7520 EXPECT_EQ(ERR_ABORTED, error.type);
7521}
7522
7523TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelRedirect) {
7524 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7525 https_test_server.ServeFilesFromSourceDirectory(
7526 base::FilePath(kTestFilePath));
7527 ASSERT_TRUE(https_test_server.Start());
7528 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7529
7530 TestNetworkErrorLoggingService nel_service;
7531 TestURLRequestContext context(true);
7532 context.set_network_error_logging_service(&nel_service);
7533 context.Init();
7534
7535 TestDelegate d;
7536 d.set_cancel_in_received_redirect(true);
7537 std::unique_ptr<URLRequest> request(context.CreateRequest(
7538 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7539 request->Start();
7540 d.RunUntilComplete();
7541
7542 ASSERT_EQ(1u, nel_service.errors().size());
7543 const TestNetworkErrorLoggingService::RequestDetails& error =
7544 nel_service.errors()[0];
7545 EXPECT_EQ(request_url, error.uri);
7546 EXPECT_EQ(302, error.status_code);
7547 // A valid HTTP response was received, even though the request was cancelled.
Lily Chenfec60d92019-01-24 01:16:427548 EXPECT_EQ(OK, error.type);
7549}
7550
7551#endif // BUILDFLAG(ENABLE_REPORTING)
7552
[email protected]316c1e5e2012-09-12 15:17:447553TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557554 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447555
7556 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077557 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557558 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167559 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197560 req->Start();
Wez2a31b222018-06-07 22:07:157561 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447562
7563 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197564 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447565 EXPECT_EQ("text/html", mime_type);
7566
7567 std::string charset;
[email protected]f7022f32014-08-21 16:32:197568 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447569 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197570 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447571}
7572
[email protected]02494ec2014-05-07 15:05:297573TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347574 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347575 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347576 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027577 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347578
7579 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507580 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347581}
7582
brettwa1228ebb2016-10-28 03:51:347583#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297584TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7585 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7586 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457587 FileProtocolHandler file_protocol_handler(
7588 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297589 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7590
7591 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507592 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297593}
7594
[email protected]588614c22013-08-16 00:09:027595TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557596 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447597
7598 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077599 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557600 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167601 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197602 req->Start();
Wez2a31b222018-06-07 22:07:157603 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447604
maksim.sisovb53724b52016-09-16 05:30:507605 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307606
7607 // The redirect should have been rejected before reporting it to the caller.
7608 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447609}
brettwa1228ebb2016-10-28 03:51:347610#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447611
[email protected]588614c22013-08-16 00:09:027612TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557613 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027614
7615 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077616 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557617 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167618 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197619 req->Start();
Wez2a31b222018-06-07 22:07:157620 d.RunUntilComplete();
[email protected]588614c22013-08-16 00:09:027621
maksim.sisovb53724b52016-09-16 05:30:507622 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307623
7624 // The redirect should have been rejected before reporting it to the
7625 // caller. See https://crbug.com/723796
7626 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027627}
7628
davidbend894710b2017-06-06 19:28:307629// Test that redirects to invalid URLs are rejected. See
7630// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447631TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557632 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447633
7634 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077635 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557636 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167637 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197638 req->Start();
Wez2a31b222018-06-07 22:07:157639 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447640
davidbend894710b2017-06-06 19:28:307641 EXPECT_EQ(1, d.response_started_count());
7642 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7643
7644 // The redirect should have been rejected before reporting it to the caller.
7645 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447646}
7647
[email protected]e50efea2014-03-24 18:41:007648// Make sure redirects are cached, despite not reading their bodies.
7649TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557650 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007651 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557652 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007653
7654 {
7655 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077656 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167657 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197658 req->Start();
Wez2a31b222018-06-07 22:07:157659 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507660 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007661 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557662 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007663 }
7664
7665 {
7666 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077667 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167668 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197669 req->Start();
Wez0e717112018-06-18 23:09:227670 d.RunUntilRedirect();
[email protected]e50efea2014-03-24 18:41:007671
7672 EXPECT_EQ(1, d.received_redirect_count());
7673 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197674 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007675
Arthur Sonzognib8465ff72019-01-04 18:44:357676 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7677 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157678 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007679 EXPECT_EQ(1, d.received_redirect_count());
7680 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507681 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557682 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007683 }
7684}
7685
7686// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7687// when the headers are read, since the body won't have been read.
7688TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557689 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007690 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557691 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007692
7693 {
7694 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557695 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007696 default_network_delegate_.set_redirect_on_headers_received_url(
7697 redirect_to_url);
7698
7699 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077700 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167701 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197702 req->Start();
Wez2a31b222018-06-07 22:07:157703 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507704 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007705 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197706 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007707 }
7708
7709 {
7710 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077711 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167712 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197713 req->Start();
Wez2a31b222018-06-07 22:07:157714 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007715
maksim.sisovb53724b52016-09-16 05:30:507716 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197717 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007718 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197719 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007720 }
7721}
7722
[email protected]5f714132014-03-26 10:41:167723// Tests that redirection to an unsafe URL is allowed when it has been marked as
7724// safe.
7725TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557726 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167727
7728 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7729 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7730 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7731
7732 TestDelegate d;
7733 {
Ryan Sleevib8449e02018-07-15 04:31:077734 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167735 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7736 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167737
[email protected]f7022f32014-08-21 16:32:197738 r->Start();
Wez2a31b222018-06-07 22:07:157739 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167740
maksim.sisovb53724b52016-09-16 05:30:507741 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197742 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197743 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167744 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7745 }
7746}
7747
7748// Tests that a redirect to a different unsafe URL is blocked, even after adding
7749// some other URL to the whitelist.
7750TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557751 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167752
7753 GURL unsafe_url("data:text/html,something");
7754 GURL different_unsafe_url("data:text/html,something-else");
7755 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7756 default_network_delegate_.set_allowed_unsafe_redirect_url(
7757 different_unsafe_url);
7758
7759 TestDelegate d;
7760 {
Ryan Sleevib8449e02018-07-15 04:31:077761 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167762 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7763 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167764
[email protected]f7022f32014-08-21 16:32:197765 r->Start();
Wez2a31b222018-06-07 22:07:157766 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167767
maksim.sisovb53724b52016-09-16 05:30:507768 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307769
7770 // The redirect should have been rejected before reporting it to the caller.
7771 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167772 }
7773}
7774
[email protected]5f714132014-03-26 10:41:167775// Redirects from an URL with fragment to an unsafe URL with fragment should
7776// be allowed, and the reference fragment of the target URL should be preserved.
7777TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557778 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167779
tommycli59a63432015-11-06 00:10:557780 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167781 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7782 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7783
7784 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7785 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7786
7787 TestDelegate d;
7788 {
Ryan Sleevib8449e02018-07-15 04:31:077789 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167790 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167791
[email protected]f7022f32014-08-21 16:32:197792 r->Start();
Wez2a31b222018-06-07 22:07:157793 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167794
[email protected]f7022f32014-08-21 16:32:197795 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507796 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197797 EXPECT_EQ(original_url, r->original_url());
7798 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167799 }
7800}
7801
7802// When a delegate has specified a safe redirect URL, but it does not match the
7803// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147804TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557805 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167806
tommycli59a63432015-11-06 00:10:557807 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167808 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557809 GURL redirect_url(http_test_server()->GetURL("/target"));
7810 GURL expected_redirect_url(
7811 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167812
7813 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7814 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7815
7816 TestDelegate d;
7817 {
Ryan Sleevib8449e02018-07-15 04:31:077818 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167819 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167820
[email protected]f7022f32014-08-21 16:32:197821 r->Start();
Wez2a31b222018-06-07 22:07:157822 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167823
[email protected]f7022f32014-08-21 16:32:197824 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507825 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197826 EXPECT_EQ(original_url, r->original_url());
7827 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167828 }
7829}
7830
[email protected]f878230e2014-04-03 15:36:147831// When a delegate has specified a safe redirect URL, assume that the redirect
7832// URL should not be changed. In particular, the reference fragment should not
7833// be modified.
7834TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557835 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147836
tommycli59a63432015-11-06 00:10:557837 GURL original_url(
7838 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147839 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7840
7841 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7842 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7843
7844 TestDelegate d;
7845 {
Ryan Sleevib8449e02018-07-15 04:31:077846 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167847 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147848
[email protected]f7022f32014-08-21 16:32:197849 r->Start();
Wez2a31b222018-06-07 22:07:157850 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147851
[email protected]f7022f32014-08-21 16:32:197852 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507853 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197854 EXPECT_EQ(original_url, r->original_url());
7855 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147856 }
7857}
7858
7859// When a URLRequestRedirectJob is created, the redirection must be followed and
7860// the reference fragment of the target URL must not be modified.
7861TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557862 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147863
tommycli59a63432015-11-06 00:10:557864 GURL original_url(
7865 http_test_server()->GetURL("/original#should-not-be-appended"));
7866 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147867
7868 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077869 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167870 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147871
danakj8522a25b2016-04-16 00:17:367872 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197873 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427874 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7875 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:147876
[email protected]f7022f32014-08-21 16:32:197877 r->Start();
Wez2a31b222018-06-07 22:07:157878 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147879
maksim.sisovb53724b52016-09-16 05:30:507880 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197881 EXPECT_EQ(original_url, r->original_url());
7882 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147883}
7884
lizeb5120f6dc2016-02-19 09:29:447885TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
7886 ASSERT_TRUE(http_test_server()->Start());
7887
7888 const std::string referrer("foobar://totally.legit.referrer");
7889 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077890 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167891 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7892 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:447893 req->SetReferrer(referrer);
7894 req->Start();
Wez2a31b222018-06-07 22:07:157895 d.RunUntilComplete();
lizeb5120f6dc2016-02-19 09:29:447896
7897 EXPECT_EQ(std::string("None"), d.data_received());
7898}
7899
[email protected]316c1e5e2012-09-12 15:17:447900TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:557901 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447902
7903 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077904 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167905 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7906 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197907 req->SetReferrer("http://user:[email protected]/");
7908 req->Start();
Wez2a31b222018-06-07 22:07:157909 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447910
7911 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
7912}
7913
[email protected]99ecf6e2013-04-10 22:46:137914TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:557915 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137916
7917 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077918 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167919 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7920 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197921 req->SetReferrer("http://foo.com/test#fragment");
7922 req->Start();
Wez2a31b222018-06-07 22:07:157923 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:137924
7925 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
7926}
7927
7928TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:557929 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137930
7931 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077932 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167933 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7934 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197935 req->SetReferrer("http://foo.com/test#fragment");
7936 req->SetReferrer("");
7937 req->Start();
Wez2a31b222018-06-07 22:07:157938 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:137939
7940 EXPECT_EQ(std::string("None"), d.data_received());
7941}
7942
[email protected]316c1e5e2012-09-12 15:17:447943TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:557944 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447945
7946 TestDelegate d;
7947 {
7948 d.set_cancel_in_received_redirect(true);
Ryan Sleevib8449e02018-07-15 04:31:077949 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167950 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7951 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197952 req->Start();
Wez2a31b222018-06-07 22:07:157953 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447954
7955 EXPECT_EQ(1, d.response_started_count());
7956 EXPECT_EQ(0, d.bytes_received());
7957 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507958 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447959 }
7960}
7961
7962TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:557963 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447964
7965 TestDelegate d;
7966 {
tommycli59a63432015-11-06 00:10:557967 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:077968 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167969 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047970
[email protected]f7022f32014-08-21 16:32:197971 req->Start();
Wez0e717112018-06-18 23:09:227972 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:447973
7974 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:237975 EXPECT_TRUE(d.have_full_request_headers());
7976 CheckFullRequestHeaders(d.full_request_headers(), test_url);
7977 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:447978
Arthur Sonzognib8465ff72019-01-04 18:44:357979 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7980 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157981 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447982
7983 EXPECT_EQ(1, d.response_started_count());
7984 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507985 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447986
[email protected]6cdfd7f2013-02-08 20:40:157987 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:197988 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477989 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:447990 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7991
7992 std::string contents;
[email protected]82f84b92013-08-30 18:23:507993 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:447994 EXPECT_EQ(contents, d.data_received());
7995 }
7996}
7997
[email protected]79e1fd62013-06-20 06:50:047998TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:557999 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:048000
8001 TestDelegate d;
8002 {
tommycli59a63432015-11-06 00:10:558003 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078004 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168005 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048006
8007 EXPECT_FALSE(d.have_full_request_headers());
8008
[email protected]f7022f32014-08-21 16:32:198009 req->Start();
Wez0e717112018-06-18 23:09:228010 d.RunUntilRedirect();
[email protected]79e1fd62013-06-20 06:50:048011
8012 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:048013
Arthur Sonzognib8465ff72019-01-04 18:44:358014 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8015 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:158016 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:048017
tommycli59a63432015-11-06 00:10:558018 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:048019 EXPECT_EQ(1, d.response_started_count());
8020 EXPECT_TRUE(d.have_full_request_headers());
8021 CheckFullRequestHeaders(d.full_request_headers(), target_url);
8022 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508023 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:048024
8025 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198026 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478027 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:048028 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8029
8030 std::string contents;
[email protected]82f84b92013-08-30 18:23:508031 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:048032 EXPECT_EQ(contents, d.data_received());
8033 }
8034}
8035
Arthur Sonzognib8465ff72019-01-04 18:44:358036TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedHeaders) {
Chong Zhang7607f1f2018-06-01 20:52:208037 ASSERT_TRUE(http_test_server()->Start());
8038
8039 TestDelegate d;
8040 {
Chong Zhang7607f1f2018-06-01 20:52:208041 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078042 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Chong Zhang7607f1f2018-06-01 20:52:208043 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8044
8045 // Set initial headers for the request.
8046 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8047 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8048
8049 req->Start();
Wez0e717112018-06-18 23:09:228050 d.RunUntilRedirect();
Chong Zhang7607f1f2018-06-01 20:52:208051
8052 // Initial request should only have initial headers.
8053 EXPECT_EQ(1, d.received_redirect_count());
8054 EXPECT_TRUE(d.have_full_request_headers());
8055 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8056 std::string sent_value;
8057 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8058 EXPECT_EQ("Value1", sent_value);
8059 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8060 EXPECT_EQ("Value2", sent_value);
8061 EXPECT_FALSE(sent_headers1.GetHeader("Header3", &sent_value));
8062 d.ClearFullRequestHeaders();
8063
8064 // Overwrite Header2 and add Header3.
Arthur Sonzognib8465ff72019-01-04 18:44:358065 net::HttpRequestHeaders modified_headers;
8066 modified_headers.SetHeader("Header2", "");
8067 modified_headers.SetHeader("Header3", "Value3");
Chong Zhang7607f1f2018-06-01 20:52:208068
Arthur Sonzognib8465ff72019-01-04 18:44:358069 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8070 modified_headers);
Wez2a31b222018-06-07 22:07:158071 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:208072
8073 EXPECT_EQ(1, d.response_started_count());
8074 EXPECT_FALSE(d.received_data_before_response());
8075 EXPECT_EQ(OK, d.request_status());
8076
8077 // Redirected request should also have modified headers.
8078 EXPECT_TRUE(d.have_full_request_headers());
8079 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8080 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8081 EXPECT_EQ("Value1", sent_value);
8082 EXPECT_TRUE(sent_headers2.GetHeader("Header2", &sent_value));
8083 EXPECT_EQ("", sent_value);
8084 EXPECT_TRUE(sent_headers2.GetHeader("Header3", &sent_value));
8085 EXPECT_EQ("Value3", sent_value);
8086 }
8087}
8088
Arthur Sonzognib8465ff72019-01-04 18:44:358089TEST_F(URLRequestTestHTTP, DeferredRedirect_RemovedHeaders) {
8090 ASSERT_TRUE(http_test_server()->Start());
8091
8092 TestDelegate d;
8093 {
8094 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
8095 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8096 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8097
8098 // Set initial headers for the request.
8099 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8100 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8101
8102 req->Start();
8103 d.RunUntilRedirect();
8104
8105 // Initial request should have initial headers.
8106 EXPECT_EQ(1, d.received_redirect_count());
8107 EXPECT_TRUE(d.have_full_request_headers());
8108 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8109 std::string sent_value;
8110 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8111 EXPECT_EQ("Value1", sent_value);
8112 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8113 EXPECT_EQ("Value2", sent_value);
8114 d.ClearFullRequestHeaders();
8115
8116 // Keep Header1 and remove Header2.
8117 std::vector<std::string> removed_headers({"Header2"});
8118 req->FollowDeferredRedirect(removed_headers,
8119 base::nullopt /* modified_headers */);
8120 d.RunUntilComplete();
8121
8122 EXPECT_EQ(1, d.response_started_count());
8123 EXPECT_FALSE(d.received_data_before_response());
8124 EXPECT_EQ(OK, d.request_status());
8125
8126 // Redirected request should also have
8127 EXPECT_TRUE(d.have_full_request_headers());
8128 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8129 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8130 EXPECT_EQ("Value1", sent_value);
8131 EXPECT_FALSE(sent_headers2.GetHeader("Header2", &sent_value));
8132 }
8133}
8134
[email protected]316c1e5e2012-09-12 15:17:448135TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:558136 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448137
8138 TestDelegate d;
8139 {
Ryan Sleevib8449e02018-07-15 04:31:078140 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168141 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8142 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198143 req->Start();
Wez0e717112018-06-18 23:09:228144 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:448145
8146 EXPECT_EQ(1, d.received_redirect_count());
8147
[email protected]f7022f32014-08-21 16:32:198148 req->Cancel();
Wez2a31b222018-06-07 22:07:158149 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448150
8151 EXPECT_EQ(1, d.response_started_count());
8152 EXPECT_EQ(0, d.bytes_received());
8153 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508154 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448155 }
8156}
8157
8158TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:558159 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448160
[email protected]3b23a222013-05-15 21:33:258161 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:448162 {
8163 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078164 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558165 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168166 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448167 HttpRequestHeaders headers;
8168 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198169 req->SetExtraRequestHeaders(headers);
8170 req->Start();
Wez2a31b222018-06-07 22:07:158171 d.RunUntilComplete();
[email protected]3b23a222013-05-15 21:33:258172
8173 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198174 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258175 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448176 }
8177
[email protected]3b23a222013-05-15 21:33:258178 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:448179 {
8180 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078181 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558182 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168183 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448184 HttpRequestHeaders headers;
8185 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198186 req->SetExtraRequestHeaders(headers);
8187 req->Start();
Wez2a31b222018-06-07 22:07:158188 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448189
[email protected]f7022f32014-08-21 16:32:198190 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258191
8192 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198193 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258194 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:448195 }
8196
[email protected]3b23a222013-05-15 21:33:258197 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:448198 {
8199 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078200 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558201 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168202 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448203 HttpRequestHeaders headers;
8204 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:198205 req->SetExtraRequestHeaders(headers);
8206 req->Start();
Wez2a31b222018-06-07 22:07:158207 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448208
[email protected]f7022f32014-08-21 16:32:198209 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258210
8211 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198212 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258213 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448214 }
8215}
8216
8217TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:558218 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448219
8220 // populate the cache
8221 {
8222 TestDelegate d;
8223 d.set_credentials(AuthCredentials(kUser, kSecret));
8224
Ryan Sleevib8449e02018-07-15 04:31:078225 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168226 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8227 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198228 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448229
Wez2a31b222018-06-07 22:07:158230 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448231
8232 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8233 }
8234
8235 // repeat request with end-to-end validation. since auth-basic results in a
8236 // cachable page, we expect this test to result in a 304. in which case, the
8237 // response should be fetched from the cache.
8238 {
8239 TestDelegate d;
8240 d.set_credentials(AuthCredentials(kUser, kSecret));
8241
Ryan Sleevib8449e02018-07-15 04:31:078242 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168243 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8244 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198245 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8246 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448247
Wez2a31b222018-06-07 22:07:158248 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448249
8250 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8251
8252 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198253 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:448254 }
8255}
8256
8257// Check that Set-Cookie headers in 401 responses are respected.
8258// http://crbug.com/6450
8259TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:558260 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448261
8262 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:558263 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:448264
8265 // Request a page that will give a 401 containing a Set-Cookie header.
8266 // Verify that when the transaction is restarted, it includes the new cookie.
8267 {
[email protected]ceefd7fd2012-11-29 00:36:248268 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448269 TestURLRequestContext context(true);
8270 context.set_network_delegate(&network_delegate);
8271 context.Init();
8272
8273 TestDelegate d;
8274 d.set_credentials(AuthCredentials(kUser, kSecret));
8275
danakj8522a25b2016-04-16 00:17:368276 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:168277 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
8278 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198279 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448280
Wez2a31b222018-06-07 22:07:158281 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448282
8283 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8284
8285 // Make sure we sent the cookie in the restarted transaction.
8286 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8287 != std::string::npos);
8288 }
8289
8290 // Same test as above, except this time the restart is initiated earlier
8291 // (without user intervention since identity is embedded in the URL).
8292 {
[email protected]ceefd7fd2012-11-29 00:36:248293 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448294 TestURLRequestContext context(true);
8295 context.set_network_delegate(&network_delegate);
8296 context.Init();
8297
8298 TestDelegate d;
8299
8300 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:188301 replacements.SetUsernameStr("user2");
8302 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:448303 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
8304
rhalavatib7bd7c792017-04-27 05:25:168305 std::unique_ptr<URLRequest> r(context.CreateRequest(
8306 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198307 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448308
Wez2a31b222018-06-07 22:07:158309 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448310
8311 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
8312
8313 // Make sure we sent the cookie in the restarted transaction.
8314 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8315 != std::string::npos);
8316 }
8317}
8318
Aaron Tagliaboschi028009e2019-03-07 16:28:068319TEST_F(URLRequestTestHTTP, AuthChallengeWithFilteredCookie) {
8320 ASSERT_TRUE(http_test_server()->Start());
8321
8322 GURL url_requiring_auth = http_test_server()->GetURL(
8323 "/auth-basic?set-cookie-if-not-challenged&set-cookie-if-challenged");
8324
8325 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8326 std::make_unique<TestNetworkDelegate>()); // Must outlive URLRequest.
8327 filtering_network_delegate.SetCookieFilter(
8328 "got_challenged"); // Filter the cookie auth-basic sets
8329 TestURLRequestContext context(true);
8330 context.set_network_delegate(&filtering_network_delegate);
8331 context.Init();
8332
8333 TestDelegate delegate;
8334
8335 delegate.set_credentials(AuthCredentials(kUser, kSecret));
8336
8337 std::unique_ptr<URLRequest> request(
8338 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &delegate,
8339 TRAFFIC_ANNOTATION_FOR_TESTS));
8340 request->Start();
8341
8342 delegate.RunUntilComplete();
8343 EXPECT_THAT(delegate.request_status(), IsOk());
8344
8345 // Make sure the cookie was actually filtered.
8346 EXPECT_EQ(std::string::npos,
8347 delegate.data_received().find("Cookie: got_challenged=true"));
8348 // Make sure it was blocked twice.
8349 EXPECT_EQ(2, filtering_network_delegate.blocked_set_cookie_count());
8350}
8351
[email protected]58e32bb2013-01-21 18:23:258352// Tests that load timing works as expected with auth and the cache.
8353TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:558354 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:258355
8356 // populate the cache
8357 {
8358 TestDelegate d;
8359 d.set_credentials(AuthCredentials(kUser, kSecret));
8360
Ryan Sleevib8449e02018-07-15 04:31:078361 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168362 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8363 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198364 r->Start();
[email protected]58e32bb2013-01-21 18:23:258365
Wez2a31b222018-06-07 22:07:158366 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258367
8368 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8369
8370 LoadTimingInfo load_timing_info_before_auth;
8371 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
8372 &load_timing_info_before_auth));
8373 TestLoadTimingNotReused(load_timing_info_before_auth,
8374 CONNECT_TIMING_HAS_DNS_TIMES);
8375
8376 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198377 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:258378 // The test server does not support keep alive sockets, so the second
8379 // request with auth should use a new socket.
8380 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
8381 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
8382 load_timing_info.socket_log_id);
8383 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
8384 load_timing_info.connect_timing.connect_start);
8385 }
8386
[email protected]3b23a222013-05-15 21:33:258387 // Repeat request with end-to-end validation. Since auth-basic results in a
8388 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258389 // response should be fetched from the cache.
8390 {
8391 TestDelegate d;
8392 d.set_credentials(AuthCredentials(kUser, kSecret));
8393
Ryan Sleevib8449e02018-07-15 04:31:078394 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168395 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8396 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198397 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8398 r->Start();
[email protected]58e32bb2013-01-21 18:23:258399
Wez2a31b222018-06-07 22:07:158400 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258401
8402 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8403
8404 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198405 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258406
[email protected]3b23a222013-05-15 21:33:258407 // Since there was a request that went over the wire, the load timing
8408 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258409 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198410 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258411 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258412 }
8413}
8414
[email protected]316c1e5e2012-09-12 15:17:448415// In this test, we do a POST which the server will 302 redirect.
8416// The subsequent transaction should use GET, and should not send the
8417// Content-Type header.
8418// http://code.google.com/p/chromium/issues/detail?id=843
8419TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558420 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448421
8422 const char kData[] = "hello world";
8423
8424 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078425 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168426 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8427 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198428 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078429 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448430
8431 // Set headers (some of which are specific to the POST).
8432 HttpRequestHeaders headers;
Yeol45b9e0a2018-07-27 02:03:298433 headers.SetHeader("Content-Type",
8434 "multipart/form-data;"
8435 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ");
8436 headers.SetHeader("Accept",
8437 "text/xml,application/xml,application/xhtml+xml,"
8438 "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
8439 headers.SetHeader("Accept-Language", "en-US,en");
8440 headers.SetHeader("Accept-Charset", "ISO-8859-1,*,utf-8");
8441 headers.SetHeader("Content-Length", "11");
8442 headers.SetHeader("Origin", "http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198443 req->SetExtraRequestHeaders(headers);
8444 req->Start();
Wez2a31b222018-06-07 22:07:158445 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448446
8447 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198448 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448449 EXPECT_EQ("text/html", mime_type);
8450
8451 const std::string& data = d.data_received();
8452
8453 // Check that the post-specific headers were stripped:
8454 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8455 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498456 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448457
8458 // These extra request headers should not have been stripped.
8459 EXPECT_TRUE(ContainsString(data, "Accept:"));
8460 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8461 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8462}
8463
jww5fe460ff2015-03-28 00:22:518464// The following tests check that we handle mutating the request for HTTP
8465// redirects as expected.
8466// See https://crbug.com/56373, https://crbug.com/102130, and
8467// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448468
8469TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558470 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448471
tommycli59a63432015-11-06 00:10:558472 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518473 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558474 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448475
8476 HTTPRedirectMethodTest(url, "POST", "GET", true);
8477 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8478 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518479
8480 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8481 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498482 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8483 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8484 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408485 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8486 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448487}
8488
8489TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558490 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448491
tommycli59a63432015-11-06 00:10:558492 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518493 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558494 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448495
8496 HTTPRedirectMethodTest(url, "POST", "GET", true);
8497 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8498 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518499
8500 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8501 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498502 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8503 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8504 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408505 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8506 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448507}
8508
8509TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558510 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448511
tommycli59a63432015-11-06 00:10:558512 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518513 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558514 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448515
8516 HTTPRedirectMethodTest(url, "POST", "GET", true);
8517 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8518 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518519
Alex Clarke1e08882b32017-10-06 14:22:408520 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8521 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8522 std::string());
8523 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8524 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8525 std::string());
jww5fe460ff2015-03-28 00:22:518526 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8527 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408528 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8529 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8530 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8531 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8532 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498533 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8534 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8535 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408536 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
8537 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:448538}
8539
8540TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558541 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448542
tommycli59a63432015-11-06 00:10:558543 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518544 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558545 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448546
8547 HTTPRedirectMethodTest(url, "POST", "POST", true);
8548 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8549 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518550
8551 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8552 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8553 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8554 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408555 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8556 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448557}
8558
[email protected]0a17aab32014-04-24 03:32:378559TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558560 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378561
tommycli59a63432015-11-06 00:10:558562 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518563 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558564 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378565
8566 HTTPRedirectMethodTest(url, "POST", "POST", true);
8567 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8568 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518569
8570 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8571 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8572 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8573 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408574 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8575 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:378576}
8577
8578// Make sure that 308 responses without bodies are not treated as redirects.
8579// Certain legacy apis that pre-date the response code expect this behavior
8580// (Like Google Drive).
8581TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558582 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378583
8584 TestDelegate d;
tommycli59a63432015-11-06 00:10:558585 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378586
Ryan Sleevib8449e02018-07-15 04:31:078587 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168588 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378589
[email protected]f7022f32014-08-21 16:32:198590 request->Start();
Wez2a31b222018-06-07 22:07:158591 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:508592 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378593 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198594 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378595 EXPECT_EQ("This is not a redirect.", d.data_received());
8596}
8597
[email protected]f878230e2014-04-03 15:36:148598TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558599 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148600
tommycli59a63432015-11-06 00:10:558601 GURL original_url(
8602 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8603 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148604
8605 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148606 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8607 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148608
Josh Karlinbe37f912018-12-07 01:05:148609 r->Start();
8610 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148611
Josh Karlinbe37f912018-12-07 01:05:148612 EXPECT_EQ(2U, r->url_chain().size());
8613 EXPECT_EQ(OK, d.request_status());
8614 EXPECT_EQ(original_url, r->original_url());
8615 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148616}
8617
[email protected]cba24642014-08-15 20:49:598618TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558619 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598620
tommycli59a63432015-11-06 00:10:558621 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598622 GURL first_party_url("http://example.com");
8623
8624 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148625 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8626 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8627 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598628
Josh Karlinbe37f912018-12-07 01:05:148629 r->Start();
8630 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598631
Josh Karlinbe37f912018-12-07 01:05:148632 EXPECT_EQ(2U, r->url_chain().size());
8633 EXPECT_EQ(OK, d.request_status());
8634 EXPECT_EQ(first_party_url, r->site_for_cookies());
8635}
8636
8637TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameOrigin) {
8638 ASSERT_TRUE(http_test_server()->Start());
8639
8640 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8641 url::Origin top_frame_origin =
8642 url::Origin::Create(GURL("http://example.com"));
8643 TestDelegate d;
8644
8645 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8646 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8647 r->set_top_frame_origin(top_frame_origin);
8648
8649 r->Start();
8650 d.RunUntilComplete();
8651
8652 EXPECT_EQ(2U, r->url_chain().size());
8653 EXPECT_EQ(OK, d.request_status());
8654 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
8655}
8656
8657TEST_F(URLRequestTestHTTP, RedirectPreserveUnsetTopFrameOrigin) {
8658 ASSERT_TRUE(http_test_server()->Start());
8659
8660 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8661 TestDelegate d;
8662
8663 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8664 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8665 // Since we're not setting a top frame origin, we wouldn't expect one after
8666 // the redirect.
8667 r->Start();
8668 d.RunUntilComplete();
8669
8670 EXPECT_EQ(2U, r->url_chain().size());
8671 EXPECT_EQ(OK, d.request_status());
8672 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:598673}
8674
Josh Karlinf3caee1642018-12-10 22:54:278675TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameURL) {
8676 ASSERT_TRUE(http_test_server()->Start());
8677
8678 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8679 url::Origin top_frame_origin =
8680 url::Origin::Create(GURL("http://example.com"));
8681 TestDelegate d;
8682 {
8683 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8684 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8685 r->set_top_frame_origin(top_frame_origin);
8686
8687 r->Start();
8688 d.RunUntilComplete();
8689
8690 EXPECT_EQ(2U, r->url_chain().size());
8691 EXPECT_EQ(OK, d.request_status());
8692 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
8693 }
8694}
8695
[email protected]cba24642014-08-15 20:49:598696TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558697 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598698
tommycli59a63432015-11-06 00:10:558699 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598700 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558701 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598702
8703 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148704
Ryan Sleevib8449e02018-07-15 04:31:078705 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168706 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468707 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198708 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598709 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8710
[email protected]f7022f32014-08-21 16:32:198711 r->Start();
Wez2a31b222018-06-07 22:07:158712 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598713
[email protected]f7022f32014-08-21 16:32:198714 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508715 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468716 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
Josh Karlinbe37f912018-12-07 01:05:148717}
8718
8719TEST_F(URLRequestTestHTTP, RedirectUpdateTopFrameOrigin) {
8720 ASSERT_TRUE(http_test_server()->Start());
8721
8722 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8723 url::Origin original_top_frame_origin =
8724 url::Origin::Create(GURL("http://example.com"));
8725 url::Origin expected_top_frame_origin =
8726 url::Origin::Create(GURL(http_test_server()->GetURL("/echo")));
8727
8728 TestDelegate d;
8729
8730 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8731 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8732 r->set_top_frame_origin(original_top_frame_origin);
8733 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8734
8735 r->Start();
8736 d.RunUntilComplete();
8737
8738 EXPECT_EQ(2U, r->url_chain().size());
8739 EXPECT_EQ(OK, d.request_status());
8740 EXPECT_EQ(expected_top_frame_origin, *r->top_frame_origin());
8741}
8742
8743TEST_F(URLRequestTestHTTP, RedirectIgnoreUnsetTopFrameOrigin) {
8744 ASSERT_TRUE(http_test_server()->Start());
8745
8746 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8747 TestDelegate d;
8748
8749 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8750 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8751 // Since we're not setting a top frame origin, we wouldn't expect one after
8752 // the redirect.
8753 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8754
8755 r->Start();
8756 d.RunUntilComplete();
8757
8758 EXPECT_EQ(2U, r->url_chain().size());
8759 EXPECT_EQ(OK, d.request_status());
8760 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:598761}
8762
[email protected]316c1e5e2012-09-12 15:17:448763TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558764 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448765
8766 const char kData[] = "hello world";
8767
8768 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078769 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168770 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8771 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198772 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078773 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448774 HttpRequestHeaders headers;
8775 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:248776 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198777 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448778
danakj8522a25b2016-04-16 00:17:368779 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558780 req.get(), &default_network_delegate_,
8781 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428782 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8783 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448784
[email protected]f7022f32014-08-21 16:32:198785 req->Start();
Wez2a31b222018-06-07 22:07:158786 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198787 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:448788}
8789
8790TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:558791 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448792
8793 const char kData[] = "hello world";
8794
8795 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078796 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168797 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8798 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198799 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078800 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448801 HttpRequestHeaders headers;
8802 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:248803 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198804 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448805
danakj8522a25b2016-04-16 00:17:368806 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558807 req.get(), &default_network_delegate_,
8808 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:098809 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:428810 "Very Good Reason"));
8811 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448812
[email protected]f7022f32014-08-21 16:32:198813 req->Start();
Wez2a31b222018-06-07 22:07:158814 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198815 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:448816 EXPECT_EQ(kData, d.data_received());
8817}
8818
8819// Check that default A-L header is sent.
8820TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558821 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448822
[email protected]8790210c2013-12-02 05:29:538823 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:248824 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448825 TestURLRequestContext context(true);
8826 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:438827 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448828 context.Init();
8829
8830 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368831 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558832 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168833 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198834 req->Start();
Wez2a31b222018-06-07 22:07:158835 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448836 EXPECT_EQ("en", d.data_received());
8837}
8838
8839// Check that an empty A-L header is not sent. http://crbug.com/77365.
8840TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558841 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448842
[email protected]8790210c2013-12-02 05:29:538843 std::string empty_string; // Avoid most vexing parse on line below.
8844 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:248845 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448846 TestURLRequestContext context(true);
8847 context.set_network_delegate(&network_delegate);
8848 context.Init();
8849 // We override the language after initialization because empty entries
8850 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:438851 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448852
8853 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368854 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558855 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168856 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198857 req->Start();
Wez2a31b222018-06-07 22:07:158858 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448859 EXPECT_EQ("None", d.data_received());
8860}
8861
8862// Check that if request overrides the A-L header, the default is not appended.
8863// See http://crbug.com/20894
8864TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
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-Language"),
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::kAcceptLanguage, "ru");
[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_EQ(std::string("ru"), d.data_received());
8877}
8878
8879// Check that default A-E header is sent.
8880TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558881 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448882
8883 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078884 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558885 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168886 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448887 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:198888 req->SetExtraRequestHeaders(headers);
8889 req->Start();
Wez2a31b222018-06-07 22:07:158890 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448891 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
8892}
8893
8894// Check that if request overrides the A-E header, the default is not appended.
8895// See http://crbug.com/47381
8896TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558897 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448898
8899 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078900 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558901 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168902 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448903 HttpRequestHeaders headers;
8904 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:198905 req->SetExtraRequestHeaders(headers);
8906 req->Start();
Wez2a31b222018-06-07 22:07:158907 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448908 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
8909 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
8910}
8911
[email protected]84f05432013-03-15 01:00:128912// Check that setting the A-C header sends the proper header.
8913TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:558914 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448915
8916 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078917 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558918 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:168919 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448920 HttpRequestHeaders headers;
8921 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:198922 req->SetExtraRequestHeaders(headers);
8923 req->Start();
Wez2a31b222018-06-07 22:07:158924 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448925 EXPECT_EQ(std::string("koi-8r"), d.data_received());
8926}
8927
8928// Check that default User-Agent header is sent.
8929TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:558930 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448931
8932 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078933 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558934 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168935 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198936 req->Start();
Wez2a31b222018-06-07 22:07:158937 d.RunUntilComplete();
Ryan Sleevib8449e02018-07-15 04:31:078938 EXPECT_EQ(default_context().http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:378939 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448940}
8941
8942// Check that if request overrides the User-Agent header,
8943// the default is not appended.
marqf14fff8d2015-12-02 15:52:298944// TODO(crbug.com/564656) This test is flaky on iOS.
8945#if defined(OS_IOS)
8946#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
8947#else
8948#define MAYBE_OverrideUserAgent OverrideUserAgent
8949#endif
8950TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:558951 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448952
8953 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078954 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558955 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168956 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448957 HttpRequestHeaders headers;
8958 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:198959 req->SetExtraRequestHeaders(headers);
8960 req->Start();
Wez2a31b222018-06-07 22:07:158961 d.RunUntilComplete();
[email protected]cd6f2522014-01-16 18:27:358962 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448963}
8964
[email protected]ee4c30d2012-11-07 15:08:438965// Check that a NULL HttpUserAgentSettings causes the corresponding empty
8966// User-Agent header to be sent but does not send the Accept-Language and
8967// Accept-Charset headers.
8968TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:558969 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:438970
[email protected]ceefd7fd2012-11-29 00:36:248971 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:438972 TestURLRequestContext context(true);
8973 context.set_network_delegate(&network_delegate);
8974 context.Init();
8975 // We override the HttpUserAgentSettings after initialization because empty
8976 // entries get overridden by Init().
Raul Tambre94493c652019-03-11 17:18:358977 context.set_http_user_agent_settings(nullptr);
[email protected]ee4c30d2012-11-07 15:08:438978
8979 struct {
8980 const char* request;
8981 const char* expected_response;
tommycli59a63432015-11-06 00:10:558982 } tests[] = {{"/echoheader?Accept-Language", "None"},
8983 {"/echoheader?Accept-Charset", "None"},
8984 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:438985
Avi Drissman4365a4782018-12-28 19:26:248986 for (size_t i = 0; i < base::size(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:438987 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368988 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168989 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
8990 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198991 req->Start();
Wez2a31b222018-06-07 22:07:158992 d.RunUntilComplete();
[email protected]ee4c30d2012-11-07 15:08:438993 EXPECT_EQ(tests[i].expected_response, d.data_received())
8994 << " Request = \"" << tests[i].request << "\"";
8995 }
8996}
8997
[email protected]5033ab82013-03-22 20:17:468998// Make sure that URLRequest passes on its priority updates to
8999// newly-created jobs after the first one.
9000TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:559001 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:469002
9003 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079004 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169005 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9006 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199007 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:469008
danakj8522a25b2016-04-16 00:17:369009 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559010 req.get(), &default_network_delegate_,
9011 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429012 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9013 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:469014
[email protected]f7022f32014-08-21 16:32:199015 req->SetPriority(LOW);
9016 req->Start();
9017 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:469018
mmenkeed0498b2015-12-08 23:20:429019 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:369020 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:429021 req.get(), &default_network_delegate_, &job_priority));
9022 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:469023
9024 // Should trigger |job| to be started.
Wez2a31b222018-06-07 22:07:159025 d.RunUntilComplete();
mmenkeed0498b2015-12-08 23:20:429026 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:469027}
9028
[email protected]80abdad2014-03-15 00:20:549029// Check that creating a network request while entering/exiting suspend mode
9030// fails as it should. This is the only case where an HttpTransactionFactory
9031// does not return an HttpTransaction.
9032TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
9033 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:369034 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
Ryan Sleevib8449e02018-07-15 04:31:079035 default_context().http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:549036 network_layer->OnSuspend();
9037
dchengc7eeda422015-12-26 03:56:489038 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:039039 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:279040 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:549041
9042 TestURLRequestContext context(true);
9043 context.set_http_transaction_factory(&http_cache);
9044 context.Init();
9045
9046 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369047 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169048 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9049 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199050 req->Start();
Wez2a31b222018-06-07 22:07:159051 d.RunUntilComplete();
[email protected]80abdad2014-03-15 00:20:549052
9053 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:509054 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:549055}
9056
mmenke2281f3762015-11-02 20:38:179057namespace {
[email protected]80abdad2014-03-15 00:20:549058
mmenke2281f3762015-11-02 20:38:179059// HttpTransactionFactory that synchronously fails to create transactions.
9060class FailingHttpTransactionFactory : public HttpTransactionFactory {
9061 public:
9062 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
9063 : network_session_(network_session) {}
9064
Chris Watkins7a41d3552017-12-01 02:13:279065 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:179066
9067 // HttpTransactionFactory methods:
9068 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:369069 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:179070 return ERR_FAILED;
9071 }
9072
9073 HttpCache* GetCache() override { return nullptr; }
9074
9075 HttpNetworkSession* GetSession() override { return network_session_; }
9076
9077 private:
9078 HttpNetworkSession* network_session_;
9079
9080 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
9081};
9082
9083} // namespace
9084
9085// Check that when a request that fails to create an HttpTransaction can be
9086// cancelled while the failure notification is pending, and doesn't send two
9087// failure notifications.
9088//
9089// This currently only happens when in suspend mode and there's no cache, but
9090// just use a special HttpTransactionFactory, to avoid depending on those
9091// behaviors.
9092TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
9093 FailingHttpTransactionFactory http_transaction_factory(
Ryan Sleevib8449e02018-07-15 04:31:079094 default_context().http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:549095 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:179096 context.set_http_transaction_factory(&http_transaction_factory);
9097 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:549098 context.Init();
9099
9100 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369101 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169102 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9103 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:179104 // Don't send cookies (Collecting cookies is asynchronous, and need request to
9105 // try to create an HttpNetworkTransaction synchronously on start).
9106 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:199107 req->Start();
mmenke2281f3762015-11-02 20:38:179108 req->Cancel();
Wez2a31b222018-06-07 22:07:159109 d.RunUntilComplete();
mmenke2281f3762015-11-02 20:38:179110 // Run pending error task, if there is one.
9111 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:549112
9113 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:179114 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509115 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:179116
9117 // NetworkDelegate should see the cancellation, but not the error.
9118 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
9119 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:549120}
9121
ttuttlec0c828492015-05-15 01:25:559122TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:559123 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559124
9125 TestDelegate d;
tommycli59a63432015-11-06 00:10:559126 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079127 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169128 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559129
9130 req->Start();
Wez2a31b222018-06-07 22:07:159131 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559132
9133 EXPECT_TRUE(req->response_info().network_accessed);
9134}
9135
9136TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:559137 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559138
9139 // Populate the cache.
9140 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079141 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169142 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9143 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559144 req->Start();
Wez2a31b222018-06-07 22:07:159145 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559146
maksim.sisovb53724b52016-09-16 05:30:509147 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559148 EXPECT_TRUE(req->response_info().network_accessed);
9149 EXPECT_FALSE(req->response_info().was_cached);
9150
Ryan Sleevib8449e02018-07-15 04:31:079151 req = default_context().CreateRequest(
9152 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9153 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:559154 req->Start();
Wez2a31b222018-06-07 22:07:159155 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559156
maksim.sisovb53724b52016-09-16 05:30:509157 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559158 EXPECT_FALSE(req->response_info().network_accessed);
9159 EXPECT_TRUE(req->response_info().was_cached);
9160}
9161
9162TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:559163 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559164
9165 TestDelegate d;
tommycli59a63432015-11-06 00:10:559166 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079167 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169168 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:339169 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:559170
9171 req->Start();
Wez2a31b222018-06-07 22:07:159172 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559173
9174 EXPECT_FALSE(req->response_info().network_accessed);
9175}
9176
rdsmithbf8c3c12016-11-18 18:16:249177// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:089178// correctly in the absence of contention.
9179TEST_F(URLRequestTestHTTP, ThrottledPriority) {
9180 ASSERT_TRUE(http_test_server()->Start());
9181
9182 TestDelegate d;
9183 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079184 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169185 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:089186 req->Start();
Wez2a31b222018-06-07 22:07:159187 d.RunUntilComplete();
rdsmith5eb6fbc2016-10-21 17:36:089188
9189 EXPECT_TRUE(req->status().is_success());
9190}
9191
ricea3a1c71f2016-06-17 10:05:269192TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
9193 ASSERT_TRUE(http_test_server()->Start());
9194
9195 TestDelegate d;
9196 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169197 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9198 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269199 req->Start();
Wez2a31b222018-06-07 22:07:159200 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269201
9202 EXPECT_EQ(5, req->GetRawBodyBytes());
9203}
9204
9205TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
9206 ASSERT_TRUE(http_test_server()->Start());
9207
9208 TestDelegate d;
9209 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169210 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
9211 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269212 req->Start();
Wez2a31b222018-06-07 22:07:159213 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269214
9215 EXPECT_EQ(30, req->GetRawBodyBytes());
9216}
9217
jamd3f5a3c2016-10-27 18:52:029218// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
9219// the delegate isn't called back synchronously.
9220TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
9221 ASSERT_TRUE(http_test_server()->Start());
9222 default_network_delegate_.set_before_start_transaction_fails();
9223
9224 TestDelegate d;
9225 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169226 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
9227 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:029228 req->Start();
9229 DCHECK(!d.response_completed());
Wez2a31b222018-06-07 22:07:159230 d.RunUntilComplete();
jamd3f5a3c2016-10-27 18:52:029231 DCHECK(d.response_completed());
9232 EXPECT_EQ(ERR_FAILED, d.request_status());
9233}
9234
bengr1bf8e942014-11-07 01:36:509235class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9236 public:
9237 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9238 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9239 // tests into the factory tests.
Raul Tambre94493c652019-03-11 17:18:359240 URLRequestInterceptorTestHTTP()
9241 : URLRequestTestHTTP(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:509242
9243 void SetUpFactory() override {
9244 interceptor_ = new MockURLRequestInterceptor();
9245 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369246 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509247 }
9248
9249 MockURLRequestInterceptor* interceptor() const {
9250 return interceptor_;
9251 }
9252
9253 private:
9254 MockURLRequestInterceptor* interceptor_;
9255};
9256
9257TEST_F(URLRequestInterceptorTestHTTP,
9258 NetworkDelegateNotificationOnRedirectIntercept) {
9259 interceptor()->set_intercept_redirect(true);
9260 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9261 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9262
tommycli59a63432015-11-06 00:10:559263 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509264
9265 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369266 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169267 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9268 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509269 req->Start();
Wez2a31b222018-06-07 22:07:159270 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509271
9272 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9273 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509274 int status = d.request_status();
9275 EXPECT_EQ(OK, status);
9276 if (status == OK)
bengr1bf8e942014-11-07 01:36:509277 EXPECT_EQ(200, req->response_headers()->response_code());
9278
9279 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9280 EXPECT_EQ(1, d.response_started_count());
9281 EXPECT_EQ(0, d.received_redirect_count());
9282
9283 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009284 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509285 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9286}
9287
9288TEST_F(URLRequestInterceptorTestHTTP,
9289 NetworkDelegateNotificationOnErrorIntercept) {
9290 // Intercept that error and respond with an OK response.
9291 interceptor()->set_intercept_final_response(true);
9292 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9293 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9294 default_network_delegate()->set_can_be_intercepted_on_error(true);
9295
tommycli59a63432015-11-06 00:10:559296 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509297
9298 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369299 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559300 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169301 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509302 req->set_method("GET");
9303 req->Start();
Wez2a31b222018-06-07 22:07:159304 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509305
9306 EXPECT_TRUE(interceptor()->did_intercept_final());
9307
9308 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509309 int status = d.request_status();
9310 EXPECT_EQ(OK, status);
9311 if (status == OK)
bengr1bf8e942014-11-07 01:36:509312 EXPECT_EQ(200, req->response_headers()->response_code());
9313 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9314 EXPECT_EQ(1, d.response_started_count());
9315 EXPECT_EQ(0, d.received_redirect_count());
9316
9317 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009318 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509319 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9320}
9321
9322TEST_F(URLRequestInterceptorTestHTTP,
9323 NetworkDelegateNotificationOnResponseIntercept) {
9324 // Intercept that error and respond with an OK response.
9325 interceptor()->set_intercept_final_response(true);
9326
9327 // Intercept with a real URLRequestHttpJob.
9328 interceptor()->set_use_url_request_http_job(true);
9329
tommycli59a63432015-11-06 00:10:559330 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509331
9332 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369333 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169334 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9335 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509336 req->set_method("GET");
9337 req->Start();
Wez2a31b222018-06-07 22:07:159338 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509339
9340 EXPECT_TRUE(interceptor()->did_intercept_final());
9341
9342 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509343 int status = d.request_status();
9344 EXPECT_EQ(OK, status);
9345 if (status == OK)
bengr1bf8e942014-11-07 01:36:509346 EXPECT_EQ(200, req->response_headers()->response_code());
9347 EXPECT_EQ("hello", d.data_received());
9348 EXPECT_EQ(1, d.response_started_count());
9349 EXPECT_EQ(0, d.received_redirect_count());
9350
9351 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009352 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509353 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9354}
9355
mkwst0c5eab872014-11-21 14:18:549356class URLRequestTestReferrerPolicy : public URLRequestTest {
9357 public:
Chris Watkins7a41d3552017-12-01 02:13:279358 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:549359
tommycli59a63432015-11-06 00:10:559360 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9361 origin_server_.reset(new EmbeddedTestServer(type));
9362 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9363 origin_server_->AddDefaultHandlers(
9364 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9365 } else {
9366 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9367 }
mkwst0c5eab872014-11-21 14:18:549368 ASSERT_TRUE(origin_server_->Start());
9369 }
9370
tommycli59a63432015-11-06 00:10:559371 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9372 net::EmbeddedTestServer::Type dest_type) {
9373 origin_server_.reset(new EmbeddedTestServer(origin_type));
9374 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9375 origin_server_->AddDefaultHandlers(
9376 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9377 } else {
9378 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9379 }
mkwst0c5eab872014-11-21 14:18:549380 ASSERT_TRUE(origin_server_->Start());
9381
tommycli59a63432015-11-06 00:10:559382 destination_server_.reset(new EmbeddedTestServer(dest_type));
9383 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9384 destination_server_->AddDefaultHandlers(
9385 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9386 } else {
9387 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9388 }
mkwst0c5eab872014-11-21 14:18:549389 ASSERT_TRUE(destination_server_->Start());
9390 }
9391
9392 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9393 const GURL& referrer,
9394 const GURL& expected) {
9395 // Create and execute the request: we'll only have a |destination_server_|
9396 // if the origins are meant to be distinct. Otherwise, we'll use the
9397 // |origin_server_| for both endpoints.
9398 GURL destination_url =
tommycli59a63432015-11-06 00:10:559399 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9400 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549401 GURL origin_url =
tommycli59a63432015-11-06 00:10:559402 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549403
9404 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079405 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169406 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549407 req->set_referrer_policy(policy);
9408 req->SetReferrer(referrer.spec());
9409 req->Start();
Wez2a31b222018-06-07 22:07:159410 d.RunUntilComplete();
mkwst0c5eab872014-11-21 14:18:549411
9412 EXPECT_EQ(1, d.response_started_count());
9413 EXPECT_EQ(1, d.received_redirect_count());
9414 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509415 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549416 EXPECT_EQ(200, req->response_headers()->response_code());
9417
9418 EXPECT_EQ(expected.spec(), req->referrer());
9419 if (expected.is_empty())
9420 EXPECT_EQ("None", d.data_received());
9421 else
9422 EXPECT_EQ(expected.spec(), d.data_received());
9423 }
9424
tommycli59a63432015-11-06 00:10:559425 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549426
9427 private:
danakj8522a25b2016-04-16 00:17:369428 std::unique_ptr<EmbeddedTestServer> origin_server_;
9429 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549430};
9431
9432TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559433 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549434
estarkc8ccba82017-06-13 22:37:409435 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549436 VerifyReferrerAfterRedirect(
9437 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409438 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549439
9440 VerifyReferrerAfterRedirect(
9441 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409442 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549443
9444 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409445 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549446
estarkc8ccba82017-06-13 22:37:409447 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9448 referrer);
9449
9450 // The original referrer set on the request is expected to obey the referrer
9451 // policy and already be stripped to the origin; thus this test case just
9452 // checks that this policy doesn't cause the referrer to change when following
9453 // a redirect.
9454 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9455 referrer.GetOrigin());
9456
9457 VerifyReferrerAfterRedirect(
9458 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9459 referrer);
9460
9461 // The original referrer set on the request is expected to obey the referrer
9462 // policy and already be stripped to the origin; thus this test case just
9463 // checks that this policy doesn't cause the referrer to change when following
9464 // a redirect.
9465 VerifyReferrerAfterRedirect(
9466 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9467 referrer.GetOrigin(), referrer.GetOrigin());
9468
9469 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549470}
9471
tommycli59a63432015-11-06 00:10:559472TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9473 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9474 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409475 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549476
9477 VerifyReferrerAfterRedirect(
9478 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409479 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549480
9481 VerifyReferrerAfterRedirect(
9482 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409483 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549484
9485 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409486 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9487 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549488
estarkc8ccba82017-06-13 22:37:409489 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9490 referrer);
9491
9492 // The original referrer set on the request is expected to obey the referrer
9493 // policy and already be stripped to the origin; thus this test case just
9494 // checks that this policy doesn't cause the referrer to change when following
9495 // a redirect.
9496 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9497 referrer.GetOrigin());
9498
9499 VerifyReferrerAfterRedirect(
9500 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9501
9502 // The original referrer set on the request is expected to obey the referrer
9503 // policy and already be stripped to the origin; thus this test case just
9504 // checks that this policy doesn't cause the referrer to change when following
9505 // a redirect.
9506 VerifyReferrerAfterRedirect(
9507 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9508 referrer.GetOrigin(), referrer.GetOrigin());
9509
9510 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549511}
9512
9513TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559514 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409515 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549516
9517 VerifyReferrerAfterRedirect(
9518 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409519 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549520
9521 VerifyReferrerAfterRedirect(
9522 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409523 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549524
9525 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409526 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549527
estarkc8ccba82017-06-13 22:37:409528 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9529 referrer);
9530
9531 // The original referrer set on the request is expected to obey the referrer
9532 // policy and already be stripped to the origin; thus this test case just
9533 // checks that this policy doesn't cause the referrer to change when following
9534 // a redirect.
9535 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9536 referrer.GetOrigin());
9537
9538 VerifyReferrerAfterRedirect(
9539 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9540 referrer);
9541
9542 // The original referrer set on the request is expected to obey the referrer
9543 // policy and already be stripped to the origin; thus this test case just
9544 // checks that this policy doesn't cause the referrer to change when following
9545 // a redirect.
9546 VerifyReferrerAfterRedirect(
9547 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9548 referrer.GetOrigin(), referrer.GetOrigin());
9549
9550 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549551}
9552
tommycli59a63432015-11-06 00:10:559553TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
9554 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9555 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409556 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549557
9558 VerifyReferrerAfterRedirect(
9559 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409560 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549561
9562 VerifyReferrerAfterRedirect(
9563 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409564 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549565
9566 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409567 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559568 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549569
estarkc8ccba82017-06-13 22:37:409570 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9571 referrer);
9572
9573 // The original referrer set on the request is expected to obey the referrer
9574 // policy and already be stripped to the origin; thus this test case just
9575 // checks that this policy doesn't cause the referrer to change when following
9576 // a redirect.
9577 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9578 referrer.GetOrigin());
9579
9580 VerifyReferrerAfterRedirect(
9581 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9582
9583 // The original referrer set on the request is expected to obey the referrer
9584 // policy and already be stripped to the origin; thus this test case just
9585 // checks that this policy doesn't cause the referrer to change when following
9586 // a redirect.
9587 VerifyReferrerAfterRedirect(
9588 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9589 referrer.GetOrigin(), referrer.GetOrigin());
9590
9591 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549592}
9593
tommycli59a63432015-11-06 00:10:559594TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
9595 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9596 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409597 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549598
9599 VerifyReferrerAfterRedirect(
9600 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409601 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549602
9603 VerifyReferrerAfterRedirect(
9604 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409605 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549606
9607 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409608 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559609 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549610
estarkc8ccba82017-06-13 22:37:409611 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9612 referrer);
9613
9614 // The original referrer set on the request is expected to obey the referrer
9615 // policy and already be stripped to the origin; thus this test case just
9616 // checks that this policy doesn't cause the referrer to change when following
9617 // a redirect.
9618 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9619 referrer.GetOrigin());
9620
9621 VerifyReferrerAfterRedirect(
9622 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9623
9624 // The original referrer set on the request is expected to obey the referrer
9625 // policy and already be stripped to the origin; thus this test case just
9626 // checks that this policy doesn't cause the referrer to change when following
9627 // a redirect.
9628 VerifyReferrerAfterRedirect(
9629 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9630 referrer.GetOrigin(), referrer.GetOrigin());
9631
9632 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549633}
9634
tommycli59a63432015-11-06 00:10:559635TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
9636 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9637 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409638 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549639
9640 VerifyReferrerAfterRedirect(
9641 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409642 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549643
9644 VerifyReferrerAfterRedirect(
9645 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409646 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549647
9648 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409649 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559650 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549651
estarkc8ccba82017-06-13 22:37:409652 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9653 referrer);
9654
9655 // The original referrer set on the request is expected to obey the referrer
9656 // policy and already be stripped to the origin; thus this test case just
9657 // checks that this policy doesn't cause the referrer to change when following
9658 // a redirect.
9659 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9660 referrer.GetOrigin());
9661
9662 VerifyReferrerAfterRedirect(
9663 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9664
9665 // The original referrer set on the request is expected to obey the referrer
9666 // policy and already be stripped to the origin, though it should be
9667 // subsequently cleared during the downgrading redirect.
9668 VerifyReferrerAfterRedirect(
9669 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9670 referrer.GetOrigin(), GURL());
9671
9672 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549673}
9674
Bence Béky98447b12018-05-08 03:14:019675class HTTPSRequestTest : public TestWithScopedTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:509676 public:
fdorayf33fede2017-05-11 21:18:109677 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:099678 default_context_.set_network_delegate(&default_network_delegate_);
9679 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:509680 }
Martijn Croonenb1383da2017-10-11 11:56:359681 ~HTTPSRequestTest() override {
9682 SetTransportSecurityStateSourceForTesting(nullptr);
9683 }
[email protected]87a09a92011-07-14 15:50:509684
9685 protected:
[email protected]ceefd7fd2012-11-29 00:36:249686 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:099687 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:469688};
9689
[email protected]c044616e2013-02-20 02:01:269690TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:559691 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9692 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229693 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119694 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469695
[email protected]ea224582008-12-07 20:25:469696 TestDelegate d;
9697 {
danakj8522a25b2016-04-16 00:17:369698 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169699 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9700 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199701 r->Start();
9702 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469703
Wez2a31b222018-06-07 22:07:159704 d.RunUntilComplete();
[email protected]ea224582008-12-07 20:25:469705
9706 EXPECT_EQ(1, d.response_started_count());
9707 EXPECT_FALSE(d.received_data_before_response());
9708 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199709 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199710 EXPECT_EQ(test_server.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:379711 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
[email protected]6d81b482011-02-22 19:47:199712 EXPECT_EQ(test_server.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:379713 r->GetResponseRemoteEndpoint().port());
[email protected]ea224582008-12-07 20:25:469714 }
[email protected]ea224582008-12-07 20:25:469715}
9716
[email protected]5774ada2010-07-15 06:30:549717TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559718 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9719 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9720 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229721 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119722 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339723
9724 bool err_allowed = true;
9725 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9726 TestDelegate d;
9727 {
9728 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369729 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169730 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9731 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339732
[email protected]f7022f32014-08-21 16:32:199733 r->Start();
9734 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339735
Wez2a31b222018-06-07 22:07:159736 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339737
9738 EXPECT_EQ(1, d.response_started_count());
9739 EXPECT_FALSE(d.received_data_before_response());
9740 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179741 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339742 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199743 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179744 } else {
[email protected]bacff652009-03-31 17:50:339745 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179746 }
[email protected]bacff652009-03-31 17:50:339747 }
9748 }
9749}
9750
[email protected]5774ada2010-07-15 06:30:549751TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559752 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9753 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9754 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229755 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119756 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339757
9758 // Iterate from false to true, just so that we do the opposite of the
9759 // previous test in order to increase test coverage.
9760 bool err_allowed = false;
9761 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9762 TestDelegate d;
9763 {
9764 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369765 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169766 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9767 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339768
[email protected]f7022f32014-08-21 16:32:199769 r->Start();
9770 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339771
Wez2a31b222018-06-07 22:07:159772 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339773
9774 EXPECT_EQ(1, d.response_started_count());
9775 EXPECT_FALSE(d.received_data_before_response());
9776 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179777 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339778 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199779 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179780 } else {
[email protected]bacff652009-03-31 17:50:339781 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179782 }
[email protected]bacff652009-03-31 17:50:339783 }
9784 }
9785}
[email protected]73e0bba2009-02-19 22:57:099786
tommycli59a63432015-11-06 00:10:559787// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
9788// security state. (see http://crbug.com/550977).
9789#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:359790// This tests that a load of a domain with preloaded HSTS and HPKP with a
9791// certificate error sets the |certificate_errors_are_fatal| flag correctly.
9792// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:449793TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359794 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9795
tommycli59a63432015-11-06 00:10:559796 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9797 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9798 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449799 ASSERT_TRUE(test_server.Start());
9800
Martijn Croonenb1383da2017-10-11 11:56:359801 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9802 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9803 // means that we have to use a MockHostResolver in order to direct
9804 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9805 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449806
9807 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249808 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449809 TestURLRequestContext context(true);
9810 context.set_network_delegate(&network_delegate);
9811 context.set_host_resolver(&host_resolver);
9812 TransportSecurityState transport_security_state;
9813 context.set_transport_security_state(&transport_security_state);
9814 context.Init();
9815
9816 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369817 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359818 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369819 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169820 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449821
[email protected]f7022f32014-08-21 16:32:199822 r->Start();
9823 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449824
Wez2a31b222018-06-07 22:07:159825 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449826
9827 EXPECT_EQ(1, d.response_started_count());
9828 EXPECT_FALSE(d.received_data_before_response());
9829 EXPECT_TRUE(d.have_certificate_errors());
9830 EXPECT_TRUE(d.certificate_errors_are_fatal());
9831}
9832
9833// This tests that cached HTTPS page loads do not cause any updates to the
9834// TransportSecurityState.
9835TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359836 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9837
[email protected]316c1e5e2012-09-12 15:17:449838 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
9839 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:559840 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9841 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9842 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449843 ASSERT_TRUE(test_server.Start());
9844
Martijn Croonenb1383da2017-10-11 11:56:359845 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9846 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9847 // means that we have to use a MockHostResolver in order to direct
9848 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9849 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449850
9851 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249852 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449853 TestURLRequestContext context(true);
9854 context.set_network_delegate(&network_delegate);
9855 context.set_host_resolver(&host_resolver);
9856 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:269857
martijnc0d6b622015-06-30 19:14:409858 TransportSecurityState::STSState static_sts_state;
9859 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269860 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359861 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:449862 context.set_transport_security_state(&transport_security_state);
9863 context.Init();
9864
martijnc0d6b622015-06-30 19:14:409865 TransportSecurityState::STSState dynamic_sts_state;
9866 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:359867 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
9868 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
9869 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
9870 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269871
[email protected]316c1e5e2012-09-12 15:17:449872 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369873 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359874 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369875 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169876 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449877
[email protected]f7022f32014-08-21 16:32:199878 r->Start();
9879 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449880
Wez2a31b222018-06-07 22:07:159881 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449882
9883 EXPECT_EQ(1, d.response_started_count());
9884 EXPECT_FALSE(d.received_data_before_response());
9885 EXPECT_TRUE(d.have_certificate_errors());
9886 EXPECT_TRUE(d.certificate_errors_are_fatal());
9887
[email protected]9e6968d2014-05-07 21:46:269888 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:409889 TransportSecurityState::STSState new_static_sts_state;
9890 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269891 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359892 "hsts-hpkp-preloaded.test", &new_static_sts_state,
9893 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:409894 TransportSecurityState::STSState new_dynamic_sts_state;
9895 TransportSecurityState::PKPState new_dynamic_pkp_state;
9896 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:359897 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:409898 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:359899 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269900
martijnc0d6b622015-06-30 19:14:409901 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
9902 EXPECT_EQ(new_static_sts_state.include_subdomains,
9903 static_sts_state.include_subdomains);
9904 EXPECT_EQ(new_static_pkp_state.include_subdomains,
9905 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:489906 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
9907 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
9908 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:449909}
9910
[email protected]8ccc69f2012-11-28 19:52:149911// Make sure HSTS preserves a POST request's method and body.
9912TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
9913 static const char kData[] = "hello world";
9914
tommycli59a63432015-11-06 00:10:559915 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9916 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229917 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:149918 ASSERT_TRUE(test_server.Start());
9919
9920
9921 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9922 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:559923 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:229924 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:149925 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:149926
9927 // Force https for www.somewhere.com.
9928 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:209929 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
9930 bool include_subdomains = false;
9931 transport_security_state.AddHSTS("www.somewhere.com", expiry,
9932 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:149933
9934 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9935
9936 TestURLRequestContext context(true);
9937 context.set_host_resolver(&host_resolver);
9938 context.set_transport_security_state(&transport_security_state);
9939 context.set_network_delegate(&network_delegate);
9940 context.Init();
9941
9942 TestDelegate d;
9943 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
9944 // cause a certificate error. Ignore the error.
9945 d.set_allow_certificate_errors(true);
9946
danakj8522a25b2016-04-16 00:17:369947 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199948 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:369949 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169950 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199951 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079952 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:149953
[email protected]f7022f32014-08-21 16:32:199954 req->Start();
Wez2a31b222018-06-07 22:07:159955 d.RunUntilComplete();
[email protected]8ccc69f2012-11-28 19:52:149956
[email protected]f7022f32014-08-21 16:32:199957 EXPECT_EQ("https", req->url().scheme());
9958 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:149959 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:409960
9961 LoadTimingInfo load_timing_info;
9962 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
9963 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
9964 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:149965}
9966
rob4e0be1f2014-09-11 23:40:229967// Make sure that the CORS headers are added to cross-origin HSTS redirects.
9968TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
9969 static const char kOriginHeaderValue[] = "http://www.example.com";
9970
tommycli59a63432015-11-06 00:10:559971 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9972 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:229973 ASSERT_TRUE(test_server.Start());
9974
9975 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9976 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:559977 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
9978 // default.
rob4e0be1f2014-09-11 23:40:229979 MockHostResolver host_resolver;
9980
9981 TransportSecurityState transport_security_state;
9982 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
9983 bool include_subdomains = false;
9984 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
9985
9986 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9987
9988 MockCertVerifier cert_verifier;
9989 cert_verifier.set_default_result(OK);
9990
9991 TestURLRequestContext context(true);
9992 context.set_host_resolver(&host_resolver);
9993 context.set_transport_security_state(&transport_security_state);
9994 context.set_network_delegate(&network_delegate);
9995 context.set_cert_verifier(&cert_verifier);
9996 context.Init();
9997
9998 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
9999 test_server.host_port_pair().port()));
10000 url::Replacements<char> replacements;
10001 const char kNewScheme[] = "https";
10002 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
10003 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
10004
10005 TestDelegate d;
rob4e0be1f2014-09-11 23:40:2210006
rhalavatib7bd7c792017-04-27 05:25:1610007 std::unique_ptr<URLRequest> req(context.CreateRequest(
10008 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:2210009 // Set Origin header to simulate a cross-origin request.
10010 HttpRequestHeaders request_headers;
10011 request_headers.SetHeader("Origin", kOriginHeaderValue);
10012 req->SetExtraRequestHeaders(request_headers);
10013
10014 req->Start();
Wez0e717112018-06-18 23:09:2210015 d.RunUntilRedirect();
rob4e0be1f2014-09-11 23:40:2210016
10017 EXPECT_EQ(1, d.received_redirect_count());
10018
10019 const HttpResponseHeaders* headers = req->response_headers();
10020 std::string redirect_location;
Raul Tambre94493c652019-03-11 17:18:3510021 EXPECT_TRUE(
10022 headers->EnumerateHeader(nullptr, "Location", &redirect_location));
rob4e0be1f2014-09-11 23:40:2210023 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
10024
10025 std::string received_cors_header;
Raul Tambre94493c652019-03-11 17:18:3510026 EXPECT_TRUE(headers->EnumerateHeader(nullptr, "Access-Control-Allow-Origin",
rob4e0be1f2014-09-11 23:40:2210027 &received_cors_header));
10028 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
10029}
10030
[email protected]316c1e5e2012-09-12 15:17:4410031namespace {
10032
10033class SSLClientAuthTestDelegate : public TestDelegate {
10034 public:
10035 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
Wez0e717112018-06-18 23:09:2210036 set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:4410037 }
dchengb03027d2014-10-21 12:00:2010038 void OnCertificateRequested(URLRequest* request,
10039 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:4410040 on_certificate_requested_count_++;
Wez0e717112018-06-18 23:09:2210041 std::move(on_certificate_requested_).Run();
10042 }
10043 void RunUntilCertificateRequested() {
10044 base::RunLoop run_loop;
10045 on_certificate_requested_ = run_loop.QuitClosure();
10046 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:4410047 }
10048 int on_certificate_requested_count() {
10049 return on_certificate_requested_count_;
10050 }
10051 private:
10052 int on_certificate_requested_count_;
Wez0e717112018-06-18 23:09:2210053 base::OnceClosure on_certificate_requested_;
[email protected]316c1e5e2012-09-12 15:17:4410054};
10055
David Benjamin76a40ad2018-02-24 22:22:0810056class TestSSLPrivateKey : public SSLPrivateKey {
10057 public:
10058 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
10059 : key_(std::move(key)) {}
10060
10061 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
10062 int sign_count() const { return sign_count_; }
10063
David Benjaminb65b0732018-11-09 20:33:5310064 std::string GetProviderName() override { return key_->GetProviderName(); }
David Benjamin76a40ad2018-02-24 22:22:0810065 std::vector<uint16_t> GetAlgorithmPreferences() override {
10066 return key_->GetAlgorithmPreferences();
10067 }
10068 void Sign(uint16_t algorithm,
10069 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:2610070 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:0810071 sign_count_++;
10072 if (fail_signing_) {
10073 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:2610074 FROM_HERE, base::BindOnce(std::move(callback),
10075 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
10076 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:0810077 } else {
David Benjamin8f2d2c12018-02-27 00:08:2610078 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:0810079 }
10080 }
10081
10082 private:
10083 ~TestSSLPrivateKey() override = default;
10084
10085 scoped_refptr<SSLPrivateKey> key_;
10086 bool fail_signing_ = false;
10087 int sign_count_ = 0;
10088};
10089
[email protected]316c1e5e2012-09-12 15:17:4410090} // namespace
10091
10092// TODO(davidben): Test the rest of the code. Specifically,
10093// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:4410094// - Getting a certificate request in an SSL renegotiation sending the
10095// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:0810096TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:5510097 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10098 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:1210099 ssl_config.client_cert_type =
10100 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:0810101 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:5510102 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210103 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410104 ASSERT_TRUE(test_server.Start());
10105
10106 SSLClientAuthTestDelegate d;
10107 {
danakj8522a25b2016-04-16 00:17:3610108 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610109 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10110 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410111
[email protected]f7022f32014-08-21 16:32:1910112 r->Start();
10113 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410114
Wez0e717112018-06-18 23:09:2210115 d.RunUntilCertificateRequested();
10116 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410117
10118 EXPECT_EQ(1, d.on_certificate_requested_count());
10119 EXPECT_FALSE(d.received_data_before_response());
10120 EXPECT_EQ(0, d.bytes_received());
10121
10122 // Send no certificate.
10123 // TODO(davidben): Get temporary client cert import (with keys) working on
10124 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:5410125 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:4410126
Wez2a31b222018-06-07 22:07:1510127 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410128
David Benjamin76a40ad2018-02-24 22:22:0810129 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:4410130 EXPECT_EQ(1, d.response_started_count());
10131 EXPECT_FALSE(d.received_data_before_response());
10132 EXPECT_NE(0, d.bytes_received());
10133 }
10134}
10135
David Benjamin76a40ad2018-02-24 22:22:0810136TEST_F(HTTPSRequestTest, ClientAuth) {
10137 std::unique_ptr<FakeClientCertIdentity> identity =
10138 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10139 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10140 ASSERT_TRUE(identity);
10141 scoped_refptr<TestSSLPrivateKey> private_key =
10142 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10143
10144 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10145 net::SSLServerConfig ssl_config;
10146 ssl_config.client_cert_type =
10147 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10148 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10149 test_server.AddDefaultHandlers(
10150 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10151 ASSERT_TRUE(test_server.Start());
10152
10153 {
10154 SSLClientAuthTestDelegate d;
10155 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10156 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10157 TRAFFIC_ANNOTATION_FOR_TESTS));
10158
10159 r->Start();
10160 EXPECT_TRUE(r->is_pending());
10161
Wez0e717112018-06-18 23:09:2210162 d.RunUntilCertificateRequested();
10163 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810164
10165 EXPECT_EQ(1, d.on_certificate_requested_count());
10166 EXPECT_FALSE(d.received_data_before_response());
10167 EXPECT_EQ(0, d.bytes_received());
10168
10169 // Send a certificate.
10170 r->ContinueWithCertificate(identity->certificate(), private_key);
10171
Wez2a31b222018-06-07 22:07:1510172 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810173
10174 EXPECT_EQ(OK, d.request_status());
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(1, private_key->sign_count());
10181 }
10182
10183 // Close all connections and clear the session cache to force a new handshake.
10184 default_context_.http_transaction_factory()
10185 ->GetSession()
10186 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710187 default_context_.http_transaction_factory()
10188 ->GetSession()
10189 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810190
10191 // Connecting again should not call OnCertificateRequested. The identity is
10192 // taken from the client auth cache.
10193 {
10194 SSLClientAuthTestDelegate d;
10195 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10196 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10197 TRAFFIC_ANNOTATION_FOR_TESTS));
10198
10199 r->Start();
10200 EXPECT_TRUE(r->is_pending());
10201
Wez2a31b222018-06-07 22:07:1510202 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810203
10204 EXPECT_EQ(OK, d.request_status());
10205 EXPECT_EQ(0, d.on_certificate_requested_count());
10206 EXPECT_FALSE(d.received_data_before_response());
10207 EXPECT_EQ(1, d.response_started_count());
10208 EXPECT_FALSE(d.received_data_before_response());
10209 EXPECT_NE(0, d.bytes_received());
10210
10211 // The private key should have been used.
10212 EXPECT_EQ(2, private_key->sign_count());
10213 }
10214}
10215
10216// Test that private keys that fail to sign anything get evicted from the cache.
10217TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
10218 std::unique_ptr<FakeClientCertIdentity> identity =
10219 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10220 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10221 ASSERT_TRUE(identity);
10222 scoped_refptr<TestSSLPrivateKey> private_key =
10223 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10224 private_key->set_fail_signing(true);
10225
10226 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10227 net::SSLServerConfig ssl_config;
10228 ssl_config.client_cert_type =
10229 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10230 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10231 test_server.AddDefaultHandlers(
10232 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10233 ASSERT_TRUE(test_server.Start());
10234
10235 {
10236 SSLClientAuthTestDelegate d;
10237 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10238 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10239 TRAFFIC_ANNOTATION_FOR_TESTS));
10240
10241 r->Start();
10242 EXPECT_TRUE(r->is_pending());
Wez0e717112018-06-18 23:09:2210243
10244 d.RunUntilCertificateRequested();
10245 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810246
10247 EXPECT_EQ(1, d.on_certificate_requested_count());
10248 EXPECT_FALSE(d.received_data_before_response());
10249 EXPECT_EQ(0, d.bytes_received());
10250
10251 // Send a certificate.
10252 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510253 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810254
10255 // The private key cannot sign anything, so we report an error.
10256 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
10257 EXPECT_EQ(1, d.response_started_count());
10258 EXPECT_FALSE(d.received_data_before_response());
10259 EXPECT_EQ(0, d.bytes_received());
10260
10261 // The private key should have been used.
10262 EXPECT_EQ(1, private_key->sign_count());
10263 }
10264
10265 // Close all connections and clear the session cache to force a new handshake.
10266 default_context_.http_transaction_factory()
10267 ->GetSession()
10268 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710269 default_context_.http_transaction_factory()
10270 ->GetSession()
10271 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810272
10273 // The bad identity should have been evicted from the cache, so connecting
10274 // again should call OnCertificateRequested again.
10275 {
10276 SSLClientAuthTestDelegate d;
10277 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10278 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10279 TRAFFIC_ANNOTATION_FOR_TESTS));
10280
10281 r->Start();
10282 EXPECT_TRUE(r->is_pending());
10283
Wez0e717112018-06-18 23:09:2210284 d.RunUntilCertificateRequested();
10285 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810286
10287 EXPECT_EQ(1, d.on_certificate_requested_count());
10288 EXPECT_FALSE(d.received_data_before_response());
10289 EXPECT_EQ(0, d.bytes_received());
10290
10291 // There should have been no additional uses of the private key.
10292 EXPECT_EQ(1, private_key->sign_count());
10293 }
10294}
10295
10296// Test that cached private keys that fail to sign anything trigger a
10297// retry. This is so we handle unplugged smartcards
10298// gracefully. https://crbug.com/813022.
10299TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
10300 std::unique_ptr<FakeClientCertIdentity> identity =
10301 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10302 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10303 ASSERT_TRUE(identity);
10304 scoped_refptr<TestSSLPrivateKey> private_key =
10305 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10306
10307 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10308 net::SSLServerConfig ssl_config;
10309 ssl_config.client_cert_type =
10310 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10311 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10312 test_server.AddDefaultHandlers(
10313 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10314 ASSERT_TRUE(test_server.Start());
10315
10316 // Connect with a client certificate to put it in the client auth cache.
10317 {
10318 SSLClientAuthTestDelegate d;
10319 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10320 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10321 TRAFFIC_ANNOTATION_FOR_TESTS));
10322
10323 r->Start();
10324 EXPECT_TRUE(r->is_pending());
10325
Wez0e717112018-06-18 23:09:2210326 d.RunUntilCertificateRequested();
10327 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810328
10329 EXPECT_EQ(1, d.on_certificate_requested_count());
10330 EXPECT_FALSE(d.received_data_before_response());
10331 EXPECT_EQ(0, d.bytes_received());
10332
10333 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510334 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810335
10336 EXPECT_EQ(OK, d.request_status());
10337 EXPECT_EQ(1, d.response_started_count());
10338 EXPECT_FALSE(d.received_data_before_response());
10339 EXPECT_NE(0, d.bytes_received());
10340
10341 // The private key should have been used.
10342 EXPECT_EQ(1, private_key->sign_count());
10343 }
10344
10345 // Close all connections and clear the session cache to force a new handshake.
10346 default_context_.http_transaction_factory()
10347 ->GetSession()
10348 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710349 default_context_.http_transaction_factory()
10350 ->GetSession()
10351 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810352
10353 // Cause the private key to fail. Connecting again should attempt to use it,
10354 // notice the failure, and then request a new identity via
10355 // OnCertificateRequested.
10356 private_key->set_fail_signing(true);
10357
10358 {
10359 SSLClientAuthTestDelegate d;
10360 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10361 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10362 TRAFFIC_ANNOTATION_FOR_TESTS));
10363
10364 r->Start();
10365 EXPECT_TRUE(r->is_pending());
10366
Wez0e717112018-06-18 23:09:2210367 d.RunUntilCertificateRequested();
10368 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810369
10370 // There was an additional signing call on the private key (the one which
10371 // failed).
10372 EXPECT_EQ(2, private_key->sign_count());
10373
10374 // That caused another OnCertificateRequested call.
10375 EXPECT_EQ(1, d.on_certificate_requested_count());
10376 EXPECT_FALSE(d.received_data_before_response());
10377 EXPECT_EQ(0, d.bytes_received());
10378 }
10379}
10380
[email protected]316c1e5e2012-09-12 15:17:4410381TEST_F(HTTPSRequestTest, ResumeTest) {
10382 // Test that we attempt a session resume when making two connections to the
10383 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:2210384 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410385 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210386 SpawnedTestServer test_server(
10387 SpawnedTestServer::TYPE_HTTPS,
10388 ssl_options,
10389 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410390 ASSERT_TRUE(test_server.Start());
10391
Daniel McArdle3a663d62019-01-31 00:48:4710392 default_context_.http_transaction_factory()
10393 ->GetSession()
10394 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4410395
10396 {
10397 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610398 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610399 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10400 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410401
[email protected]f7022f32014-08-21 16:32:1910402 r->Start();
10403 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410404
Wez2a31b222018-06-07 22:07:1510405 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410406
10407 EXPECT_EQ(1, d.response_started_count());
10408 }
10409
10410 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10411 CloseAllConnections();
10412
10413 {
10414 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610415 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610416 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10417 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410418
[email protected]f7022f32014-08-21 16:32:1910419 r->Start();
10420 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410421
Wez2a31b222018-06-07 22:07:1510422 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410423
10424 // The response will look like;
Steven Valdez0ef94d02018-11-19 23:28:1310425 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]316c1e5e2012-09-12 15:17:4410426 // insert abc
10427 // lookup abc
10428 // insert xyz
10429 //
10430 // With a newline at the end which makes the split think that there are
10431 // four lines.
10432
10433 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2910434 std::vector<std::string> lines = base::SplitString(
10435 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Steven Valdez0ef94d02018-11-19 23:28:1310436 ASSERT_EQ(5u, lines.size()) << d.data_received();
[email protected]316c1e5e2012-09-12 15:17:4410437
10438 std::string session_id;
10439
Steven Valdez0ef94d02018-11-19 23:28:1310440 for (size_t i = 0; i < 3; i++) {
brettw3a2c6902015-07-06 19:43:2910441 std::vector<std::string> parts = base::SplitString(
10442 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410443 ASSERT_EQ(2u, parts.size());
Steven Valdez0ef94d02018-11-19 23:28:1310444 if (i % 2 == 1) {
[email protected]316c1e5e2012-09-12 15:17:4410445 EXPECT_EQ("insert", parts[0]);
10446 session_id = parts[1];
10447 } else {
10448 EXPECT_EQ("lookup", parts[0]);
Steven Valdez0ef94d02018-11-19 23:28:1310449 if (i != 0)
10450 EXPECT_EQ(session_id, parts[1]);
[email protected]316c1e5e2012-09-12 15:17:4410451 }
10452 }
10453 }
10454}
10455
10456TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
10457 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
10458 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2210459 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410460 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210461 SpawnedTestServer test_server(
10462 SpawnedTestServer::TYPE_HTTPS,
10463 ssl_options,
10464 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410465 ASSERT_TRUE(test_server.Start());
10466
Daniel McArdle3a663d62019-01-31 00:48:4710467 default_context_.http_transaction_factory()
10468 ->GetSession()
10469 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4410470
10471 {
10472 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610473 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0410474 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1610475 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410476
[email protected]f7022f32014-08-21 16:32:1910477 r->Start();
10478 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410479
Wez2a31b222018-06-07 22:07:1510480 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410481
10482 EXPECT_EQ(1, d.response_started_count());
10483 }
10484
10485 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4110486 HttpNetworkSession::Context session_context;
10487 session_context.host_resolver = default_context_.host_resolver();
10488 session_context.cert_verifier = default_context_.cert_verifier();
10489 session_context.transport_security_state =
10490 default_context_.transport_security_state();
10491 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2010492 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4110493 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5910494 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4110495 session_context.ssl_config_service = default_context_.ssl_config_service();
10496 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4410497 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4110498 session_context.http_server_properties =
10499 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4410500
mmenke6ddfbea2017-05-31 21:48:4110501 HttpNetworkSession network_session(HttpNetworkSession::Params(),
10502 session_context);
zhongyi4928bd52017-02-08 02:16:2710503 std::unique_ptr<HttpCache> cache(
10504 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
10505 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4410506
10507 default_context_.set_http_transaction_factory(cache.get());
10508
10509 {
10510 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610511 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610512 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10513 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410514
[email protected]f7022f32014-08-21 16:32:1910515 r->Start();
10516 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410517
Wez2a31b222018-06-07 22:07:1510518 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410519
[email protected]316c1e5e2012-09-12 15:17:4410520 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0410521 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]316c1e5e2012-09-12 15:17:4410522 }
10523}
10524
Daniel McArdleda3fa942019-02-15 16:41:2110525// Test that sessions started with privacy mode enabled cannot be resumed when
10526// it is disabled, and vice versa.
10527TEST_F(HTTPSRequestTest, NoSessionResumptionBetweenPrivacyModes) {
10528 // Start a server.
10529 SpawnedTestServer test_server(
10530 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(),
10531 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10532 ASSERT_TRUE(test_server.Start());
10533 const auto url = test_server.GetURL("/");
10534
10535 auto ConnectAndCheckHandshake = [this, url](bool allow_credentials,
10536 auto expected_handshake) {
10537 // Construct request and indirectly set the privacy mode.
10538 TestDelegate d;
10539 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10540 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
10541 r->set_allow_credentials(allow_credentials);
10542
10543 // Start the request and check the SSL handshake type.
10544 r->Start();
10545 EXPECT_TRUE(r->is_pending());
10546 d.RunUntilComplete();
10547 EXPECT_EQ(1, d.response_started_count());
10548 EXPECT_EQ(expected_handshake, r->ssl_info().handshake_type);
10549 };
10550
10551 // Exhaustively check all pairs of privacy mode values. Note that we are using
10552 // allow_credentials to indirectly enable/disable privacy mode.
10553 const bool kAllowCredentialsValues[] = {false, true};
10554 for (const auto allow_creds_1 : kAllowCredentialsValues) {
10555 for (const auto allow_creds_2 : kAllowCredentialsValues) {
10556 SCOPED_TRACE(base::StringPrintf("allow_creds_1=%d, allow_creds_2=%d",
10557 allow_creds_1, allow_creds_2));
10558
10559 // The session cache starts off empty, so we expect a full handshake.
10560 ConnectAndCheckHandshake(allow_creds_1, SSLInfo::HANDSHAKE_FULL);
10561
10562 // The second handshake depends on whether we are using the same session
10563 // cache as the first request.
10564 ConnectAndCheckHandshake(allow_creds_2, allow_creds_1 == allow_creds_2
10565 ? SSLInfo::HANDSHAKE_RESUME
10566 : SSLInfo::HANDSHAKE_FULL);
10567 // Flush both session caches.
10568 auto* network_session =
10569 default_context_.http_transaction_factory()->GetSession();
10570 network_session->ClearSSLSessionCache();
10571 }
10572 }
10573}
10574
Bence Béky98447b12018-05-08 03:14:0110575class HTTPSFallbackTest : public TestWithScopedTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:5510576 public:
fdorayf33fede2017-05-11 21:18:1010577 HTTPSFallbackTest() : context_(true) {
Nick Harper2243e8002018-09-28 20:33:2610578 ssl_config_service_ = std::make_unique<TestSSLConfigService>();
davidben095ebb52017-04-12 22:23:3410579 context_.set_ssl_config_service(ssl_config_service_.get());
10580 }
Chris Watkins7a41d3552017-12-01 02:13:2710581 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5510582
10583 protected:
davidben095ebb52017-04-12 22:23:3410584 TestSSLConfigService* ssl_config_service() {
10585 return ssl_config_service_.get();
10586 }
10587
[email protected]48d2b7c52014-06-27 01:16:5510588 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
10589 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0010590 context_.Init();
10591 delegate_.set_allow_certificate_errors(true);
10592
[email protected]48d2b7c52014-06-27 01:16:5510593 SpawnedTestServer test_server(
10594 SpawnedTestServer::TYPE_HTTPS,
10595 ssl_options,
10596 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10597 ASSERT_TRUE(test_server.Start());
10598
tommycli59a63432015-11-06 00:10:5510599 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1610600 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5510601 request_->Start();
10602
Wez2a31b222018-06-07 22:07:1510603 delegate_.RunUntilComplete();
[email protected]48d2b7c52014-06-27 01:16:5510604 }
10605
davidben095ebb52017-04-12 22:23:3410606 void ExpectConnection(int version) {
10607 EXPECT_EQ(1, delegate_.response_started_count());
10608 EXPECT_NE(0, delegate_.bytes_received());
10609 EXPECT_EQ(version, SSLConnectionStatusToVersion(
10610 request_->ssl_info().connection_status));
10611 }
10612
[email protected]48d2b7c52014-06-27 01:16:5510613 void ExpectFailure(int error) {
10614 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5010615 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5510616 }
10617
10618 private:
Ryan Sleevib8449e02018-07-15 04:31:0710619 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5510620 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4710621 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610622 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:5510623};
10624
davidbenb127ca82015-06-15 19:05:4210625// Tests the TLS 1.0 fallback doesn't happen.
10626TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5510627 SpawnedTestServer::SSLOptions ssl_options(
10628 SpawnedTestServer::SSLOptions::CERT_OK);
10629 ssl_options.tls_intolerant =
10630 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
10631
10632 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5510633 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4210634}
10635
davidben5a312152016-06-27 22:11:4710636// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5510637TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4210638 SpawnedTestServer::SSLOptions ssl_options(
10639 SpawnedTestServer::SSLOptions::CERT_OK);
10640 ssl_options.tls_intolerant =
10641 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
10642
10643 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5510644 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
10645}
10646
davidben095ebb52017-04-12 22:23:3410647// Tests that TLS 1.3 interference results in a dedicated error code.
10648TEST_F(HTTPSFallbackTest, TLSv1_3Interference) {
10649 SpawnedTestServer::SSLOptions ssl_options(
10650 SpawnedTestServer::SSLOptions::CERT_OK);
10651 ssl_options.tls_intolerant =
10652 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10653 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
10654
10655 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10656 ExpectFailure(ERR_SSL_VERSION_INTERFERENCE);
10657}
10658
10659// Tests that disabling TLS 1.3 leaves TLS 1.3 interference unnoticed.
10660TEST_F(HTTPSFallbackTest, TLSv1_3InterferenceDisableVersion) {
10661 SpawnedTestServer::SSLOptions ssl_options(
10662 SpawnedTestServer::SSLOptions::CERT_OK);
10663 ssl_options.tls_intolerant =
10664 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10665 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_2);
10666
10667 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10668 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_2);
10669}
10670
Bence Béky98447b12018-05-08 03:14:0110671class HTTPSSessionTest : public TestWithScopedTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:2410672 public:
fdorayf33fede2017-05-11 21:18:1010673 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5910674 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410675
10676 default_context_.set_network_delegate(&default_network_delegate_);
10677 default_context_.set_cert_verifier(&cert_verifier_);
10678 default_context_.Init();
10679 }
Chris Watkins7a41d3552017-12-01 02:13:2710680 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2410681
10682 protected:
10683 MockCertVerifier cert_verifier_;
10684 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
10685 TestURLRequestContext default_context_;
10686};
10687
10688// Tests that session resumption is not attempted if an invalid certificate
10689// is presented.
10690TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
10691 SpawnedTestServer::SSLOptions ssl_options;
10692 ssl_options.record_resume = true;
10693 SpawnedTestServer test_server(
10694 SpawnedTestServer::TYPE_HTTPS,
10695 ssl_options,
10696 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10697 ASSERT_TRUE(test_server.Start());
10698
Daniel McArdle3a663d62019-01-31 00:48:4710699 default_context_.http_transaction_factory()
10700 ->GetSession()
10701 ->ClearSSLSessionCache();
[email protected]a8fed1742013-12-27 02:14:2410702
10703 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5910704 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2410705 {
10706 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610707 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0410708 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1610709 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410710
[email protected]f7022f32014-08-21 16:32:1910711 r->Start();
10712 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410713
Wez2a31b222018-06-07 22:07:1510714 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410715
10716 EXPECT_EQ(1, d.response_started_count());
10717 }
10718
10719 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10720 CloseAllConnections();
10721
10722 // Now change the certificate to be acceptable (so that the response is
10723 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910724 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410725 {
10726 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610727 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610728 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10729 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410730
[email protected]f7022f32014-08-21 16:32:1910731 r->Start();
10732 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410733
Wez2a31b222018-06-07 22:07:1510734 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410735
[email protected]a8fed1742013-12-27 02:14:2410736 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0410737 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]a8fed1742013-12-27 02:14:2410738 }
10739}
10740
[email protected]dffe8242012-03-20 15:14:2710741// This the fingerprint of the "Testing CA" certificate used by the testserver.
10742// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5810743static const SHA256HashValue kOCSPTestCertFingerprint = {{
10744 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
10745 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
10746 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1510747}};
[email protected]dffe8242012-03-20 15:14:2710748
[email protected]51523f52013-07-31 21:57:2810749// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
10750// testserver.
mattm0b12a6f2016-11-29 19:57:1610751static const SHA256HashValue kOCSPTestCertSPKI = {{
10752 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
10753 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
10754 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
10755}};
[email protected]51523f52013-07-31 21:57:2810756
[email protected]dffe8242012-03-20 15:14:2710757// This is the policy OID contained in the certificates that testserver
10758// generates.
10759static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
10760
10761class HTTPSOCSPTest : public HTTPSRequestTest {
10762 public:
10763 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0910764 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0810765 ev_test_policy_(
10766 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
10767 kOCSPTestCertFingerprint,
10768 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0210769 }
10770
dcheng67be2b1f2014-10-27 21:47:2910771 void SetUp() override {
Ryan Sleevi8a9c9c12018-05-09 02:36:2310772 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
[email protected]ef2bf422012-05-11 03:27:0910773 context_.Init();
[email protected]dffe8242012-03-20 15:14:2710774
Ryan Sleevi24fe2682018-08-16 21:33:4610775 context_.cert_verifier()->SetConfig(GetCertVerifierConfig());
10776
[email protected]cba24642014-08-15 20:49:5910777 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2010778 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
Raul Tambre94493c652019-03-11 17:18:3510779 CHECK_NE(static_cast<X509Certificate*>(nullptr), root_cert.get());
[email protected]90499482013-06-01 00:39:5010780 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2710781
Matt Muellerfb271992018-01-30 18:10:4810782#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510783 SetGlobalCertNetFetcherForTesting(net::CreateCertNetFetcher(&context_));
10784#endif
10785
svaldez2135be52016-04-20 16:34:5310786#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0910787 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2710788#endif
10789 }
10790
dadrian612337a2016-07-20 22:36:5810791 void DoConnectionWithDelegate(
10792 const SpawnedTestServer::SSLOptions& ssl_options,
10793 TestDelegate* delegate,
10794 SSLInfo* out_ssl_info) {
10795 // Always overwrite |out_ssl_info|.
10796 out_ssl_info->Reset();
10797
[email protected]ce7d0cbc2013-05-03 18:57:2210798 SpawnedTestServer test_server(
10799 SpawnedTestServer::TYPE_HTTPS,
10800 ssl_options,
10801 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2710802 ASSERT_TRUE(test_server.Start());
10803
dadrian612337a2016-07-20 22:36:5810804 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1610805 std::unique_ptr<URLRequest> r(
10806 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
10807 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910808 r->Start();
[email protected]dffe8242012-03-20 15:14:2710809
Wez2a31b222018-06-07 22:07:1510810 delegate->RunUntilComplete();
dadrian612337a2016-07-20 22:36:5810811 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2710812
dadrian612337a2016-07-20 22:36:5810813 *out_ssl_info = r->ssl_info();
10814 }
10815
10816 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
10817 CertStatus* out_cert_status) {
10818 // Always overwrite |out_cert_status|.
10819 *out_cert_status = 0;
10820
10821 TestDelegate d;
10822 SSLInfo ssl_info;
10823 ASSERT_NO_FATAL_FAILURE(
10824 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
10825
10826 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2710827 }
10828
dcheng67be2b1f2014-10-27 21:47:2910829 ~HTTPSOCSPTest() override {
Matt Muellerfb271992018-01-30 18:10:4810830#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510831 ShutdownGlobalCertNetFetcher();
10832#endif
10833
svaldez2135be52016-04-20 16:34:5310834#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1810835 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2710836#endif
10837 }
10838
[email protected]a13234c2012-03-20 21:45:0210839 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4610840 // GetCertVerifierConfig() configures the URLRequestContext that will be used
10841 // for making connections to the testserver. This can be overridden in test
10842 // subclasses for different behaviour.
10843 virtual CertVerifier::Config GetCertVerifierConfig() {
10844 CertVerifier::Config config;
10845 config.enable_rev_checking = true;
10846 return config;
[email protected]a13234c2012-03-20 21:45:0210847 }
10848
danakj8522a25b2016-04-16 00:17:3610849 std::unique_ptr<ScopedTestRoot> test_root_;
Ryan Sleevib8449e02018-07-15 04:31:0710850 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]ef2bf422012-05-11 03:27:0910851 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610852 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2710853};
10854
[email protected]a13234c2012-03-20 21:45:0210855static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2010856#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0210857 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
10858 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0410859 // TODO(eroman): Should this also be the return value for
10860 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0210861 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
10862#else
10863 return 0;
10864#endif
10865}
10866
[email protected]3a86a712013-07-30 07:16:2010867// SystemSupportsHardFailRevocationChecking returns true iff the current
10868// operating system supports revocation checking and can distinguish between
10869// situations where a given certificate lacks any revocation information (eg:
10870// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
10871// revocation information cannot be obtained (eg: the CRL was unreachable).
10872// If it does not, then tests which rely on 'hard fail' behaviour should be
10873// skipped.
10874static bool SystemSupportsHardFailRevocationChecking() {
Eric Roman1b628daa2017-10-19 19:52:0410875#if defined(OS_WIN) || defined(USE_NSS_CERTS) || \
10876 defined(USE_BUILTIN_CERT_VERIFIER)
[email protected]3a86a712013-07-30 07:16:2010877 return true;
10878#else
10879 return false;
10880#endif
10881}
10882
[email protected]a13234c2012-03-20 21:45:0210883// SystemUsesChromiumEVMetadata returns true iff the current operating system
10884// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
10885// several tests are effected because our testing EV certificate won't be
10886// recognised as EV.
10887static bool SystemUsesChromiumEVMetadata() {
Eric Roman5f8d9d22017-10-17 02:32:5210888#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0110889 return true;
Eric Roman5f8d9d22017-10-17 02:32:5210890#else
10891 return false;
[email protected]05454a432012-03-20 20:04:0110892#endif
10893}
10894
mattmaf868e72016-09-23 23:25:2010895// Returns the expected CertStatus for tests that expect an online revocation
10896// check failure as a result of checking a test EV cert, which will not
10897// actually trigger an online revocation check on some platforms.
10898static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
10899 if (SystemUsesChromiumEVMetadata()) {
10900 return ExpectedCertStatusForFailedOnlineRevocationCheck();
10901 } else {
10902 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
10903 // be enabled, and thus there will not be a revocation check to fail.
10904 return 0u;
10905 }
10906}
10907
[email protected]b6f2de32012-08-17 04:35:0810908static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3910909#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0210910 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
10911 return false;
10912#else
10913 return true;
10914#endif
10915}
10916
davidbend1fb2f12014-11-08 02:51:0010917static bool SystemSupportsOCSPStapling() {
Eric Roman1b628daa2017-10-19 19:52:0410918#if defined(USE_NSS_CERTS) || defined(OS_WIN) || \
10919 defined(USE_BUILTIN_CERT_VERIFIER)
mathpc992e602015-10-21 20:34:0310920 return true;
mathpc992e602015-10-21 20:34:0310921#else
10922 return false;
10923#endif
davidbend1fb2f12014-11-08 02:51:0010924}
10925
[email protected]dffe8242012-03-20 15:14:2710926TEST_F(HTTPSOCSPTest, Valid) {
10927 if (!SystemSupportsOCSP()) {
10928 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10929 return;
10930 }
10931
[email protected]ce7d0cbc2013-05-03 18:57:2210932 SpawnedTestServer::SSLOptions ssl_options(
10933 SpawnedTestServer::SSLOptions::CERT_AUTO);
10934 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2710935
[email protected]924e9f92012-12-16 22:00:5310936 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210937 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710938
10939 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10940
[email protected]a13234c2012-03-20 21:45:0210941 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10942 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2710943
10944 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10945}
10946
10947TEST_F(HTTPSOCSPTest, Revoked) {
10948 if (!SystemSupportsOCSP()) {
10949 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10950 return;
10951 }
10952
[email protected]ce7d0cbc2013-05-03 18:57:2210953 SpawnedTestServer::SSLOptions ssl_options(
10954 SpawnedTestServer::SSLOptions::CERT_AUTO);
10955 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2710956
10957 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210958 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710959
[email protected]dffe8242012-03-20 15:14:2710960 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2710961 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10962 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10963}
10964
10965TEST_F(HTTPSOCSPTest, Invalid) {
10966 if (!SystemSupportsOCSP()) {
10967 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10968 return;
10969 }
10970
[email protected]ce7d0cbc2013-05-03 18:57:2210971 SpawnedTestServer::SSLOptions ssl_options(
10972 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810973 ssl_options.ocsp_status =
10974 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2710975
[email protected]924e9f92012-12-16 22:00:5310976 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210977 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710978
Eric Roman1b628daa2017-10-19 19:52:0410979#if defined(USE_BUILTIN_CERT_VERIFIER)
10980 // TODO(649017): This test uses soft-fail revocation checking, but returns an
10981 // invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
10982 // doesn't consider this a candidate for soft-fail (only considers
10983 // network-level failures as skippable).
10984 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
10985 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
10986#else
[email protected]a13234c2012-03-20 21:45:0210987 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2710988 cert_status & CERT_STATUS_ALL_ERRORS);
Eric Roman1b628daa2017-10-19 19:52:0410989#endif
[email protected]dffe8242012-03-20 15:14:2710990
10991 // Without a positive OCSP response, we shouldn't show the EV status.
10992 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10993 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10994}
[email protected]a13234c2012-03-20 21:45:0210995
Matt Mueller5339d862018-05-02 18:53:5710996TEST_F(HTTPSOCSPTest, IntermediateValid) {
10997 if (!SystemSupportsOCSP()) {
10998 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10999 return;
11000 }
11001
11002 SpawnedTestServer::SSLOptions ssl_options(
11003 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11004 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11005 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11006
11007 CertStatus cert_status;
11008 DoConnection(ssl_options, &cert_status);
11009
11010 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11011
11012 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11013 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11014
11015 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11016}
11017
11018TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
11019 if (!SystemSupportsOCSP()) {
11020 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11021 return;
11022 }
11023
11024 SpawnedTestServer::SSLOptions ssl_options(
11025 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11026 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11027 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11028 // Use an OCSP response for the intermediate that would be too old for a leaf
11029 // cert, but is still valid for an intermediate.
11030 ssl_options.ocsp_intermediate_date =
11031 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
11032
11033 CertStatus cert_status;
11034 DoConnection(ssl_options, &cert_status);
11035
11036 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11037
11038 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11039 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11040
11041 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11042}
11043
11044TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
11045 if (!SystemSupportsOCSP()) {
11046 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11047 return;
11048 }
11049
11050 SpawnedTestServer::SSLOptions ssl_options(
11051 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11052 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11053 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11054 ssl_options.ocsp_intermediate_date =
11055 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
11056
11057 CertStatus cert_status;
11058 DoConnection(ssl_options, &cert_status);
11059
11060#if defined(USE_BUILTIN_CERT_VERIFIER)
11061 // The builtin verifier enforces the baseline requirements for max age of an
11062 // intermediate's OCSP response.
11063 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11064 cert_status & CERT_STATUS_ALL_ERRORS);
11065 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11066#else
11067 // The platform verifiers are more lenient.
11068 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11069 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11070 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11071#endif
11072 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11073}
11074
11075TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
11076 if (!SystemSupportsOCSP()) {
11077 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11078 return;
11079 }
11080
11081 SpawnedTestServer::SSLOptions ssl_options(
11082 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11083 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11084 ssl_options.ocsp_intermediate_status =
11085 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11086
11087 CertStatus cert_status;
11088 DoConnection(ssl_options, &cert_status);
11089
11090#if defined(OS_WIN)
11091 // TODO(mattm): why does CertVerifyProcWin accept this?
11092 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11093#else
11094 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11095#endif
11096 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11097 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11098}
11099
davidbend1fb2f12014-11-08 02:51:0011100TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0311101 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011102 LOG(WARNING)
11103 << "Skipping test because system doesn't support OCSP stapling";
11104 return;
11105 }
11106
11107 SpawnedTestServer::SSLOptions ssl_options(
11108 SpawnedTestServer::SSLOptions::CERT_AUTO);
11109 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11110 ssl_options.staple_ocsp_response = true;
11111 ssl_options.ocsp_server_unavailable = true;
11112
11113 CertStatus cert_status;
11114 DoConnection(ssl_options, &cert_status);
11115
11116 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11117
11118 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11119 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11120
11121 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11122}
11123
davidben6c3191b2014-11-21 22:38:0411124// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4811125#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0411126#define MAYBE_RevokedStapled DISABLED_RevokedStapled
11127#else
11128#define MAYBE_RevokedStapled RevokedStapled
11129#endif
11130TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0311131 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011132 LOG(WARNING)
11133 << "Skipping test because system doesn't support OCSP stapling";
11134 return;
11135 }
11136
11137 SpawnedTestServer::SSLOptions ssl_options(
11138 SpawnedTestServer::SSLOptions::CERT_AUTO);
11139 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11140 ssl_options.staple_ocsp_response = true;
11141 ssl_options.ocsp_server_unavailable = true;
11142
11143 CertStatus cert_status;
11144 DoConnection(ssl_options, &cert_status);
11145
11146 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11147 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11148 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11149}
11150
dadrian612337a2016-07-20 22:36:5811151static const struct OCSPVerifyTestData {
11152 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
11153 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
11154 OCSPVerifyResult::ResponseStatus response_status;
11155 bool has_revocation_status;
11156 OCSPRevocationStatus cert_status;
11157} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3111158 // 0
dadrian612337a2016-07-20 22:36:5811159 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11160 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11161 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11162 OCSPVerifyResult::PROVIDED,
11163 true,
11164 OCSPRevocationStatus::GOOD},
11165
Eric Roman8673b812017-09-20 18:57:3111166 // 1
dadrian612337a2016-07-20 22:36:5811167 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11168 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11169 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11170 OCSPVerifyResult::INVALID_DATE,
11171 false,
11172 OCSPRevocationStatus::UNKNOWN},
11173
Eric Roman8673b812017-09-20 18:57:3111174 // 2
dadrian612337a2016-07-20 22:36:5811175 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11176 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11177 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11178 OCSPVerifyResult::INVALID_DATE,
11179 false,
11180 OCSPRevocationStatus::UNKNOWN},
11181
Eric Roman8673b812017-09-20 18:57:3111182 // 3
dadrian612337a2016-07-20 22:36:5811183 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11184 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11185 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11186 OCSPVerifyResult::INVALID_DATE,
11187 false,
11188 OCSPRevocationStatus::UNKNOWN},
11189
Eric Roman8673b812017-09-20 18:57:3111190 // 4
dadrian612337a2016-07-20 22:36:5811191 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11192 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11193 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11194 OCSPVerifyResult::INVALID_DATE,
11195 false,
11196 OCSPRevocationStatus::UNKNOWN},
11197
Eric Roman8673b812017-09-20 18:57:3111198 // 5
dadrian612337a2016-07-20 22:36:5811199 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
11200 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11201 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11202 OCSPVerifyResult::ERROR_RESPONSE,
11203 false,
11204 OCSPRevocationStatus::UNKNOWN},
11205
Eric Roman8673b812017-09-20 18:57:3111206 // 6
dadrian612337a2016-07-20 22:36:5811207 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
11208 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11209 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11210 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
11211 false,
11212 OCSPRevocationStatus::UNKNOWN},
11213
Eric Roman8673b812017-09-20 18:57:3111214 // 7
dadrian612337a2016-07-20 22:36:5811215 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
11216 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11217 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11218 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
11219 false,
11220 OCSPRevocationStatus::UNKNOWN},
11221
Eric Roman8673b812017-09-20 18:57:3111222 // 8
dadrian612337a2016-07-20 22:36:5811223 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11224 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11225 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11226 OCSPVerifyResult::INVALID_DATE,
11227 false,
11228 OCSPRevocationStatus::UNKNOWN},
11229
Eric Roman8673b812017-09-20 18:57:3111230 // 9
dadrian612337a2016-07-20 22:36:5811231 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11232 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11233 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11234 OCSPVerifyResult::PROVIDED,
11235 true,
11236 OCSPRevocationStatus::UNKNOWN},
11237
Eric Roman8673b812017-09-20 18:57:3111238 // 10
dadrian612337a2016-07-20 22:36:5811239 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11240 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11241 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11242 OCSPVerifyResult::INVALID_DATE,
11243 false,
11244 OCSPRevocationStatus::UNKNOWN},
11245
Eric Roman8673b812017-09-20 18:57:3111246 // 11
dadrian612337a2016-07-20 22:36:5811247 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11248 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11249 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11250 OCSPVerifyResult::INVALID_DATE,
11251 false,
11252 OCSPRevocationStatus::UNKNOWN},
11253
Eric Roman8673b812017-09-20 18:57:3111254 // 12
dadrian612337a2016-07-20 22:36:5811255 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11256 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11257 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
11258 OCSPVerifyResult::BAD_PRODUCED_AT,
11259 false,
11260 OCSPRevocationStatus::UNKNOWN},
11261
Eric Roman8673b812017-09-20 18:57:3111262 // 13
dadrian612337a2016-07-20 22:36:5811263 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11264 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11265 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11266 OCSPVerifyResult::BAD_PRODUCED_AT,
11267 false,
11268 OCSPRevocationStatus::UNKNOWN},
11269
Eric Roman8673b812017-09-20 18:57:3111270 // 14
dadrian612337a2016-07-20 22:36:5811271 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11272 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11273 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11274 OCSPVerifyResult::BAD_PRODUCED_AT,
11275 false,
11276 OCSPRevocationStatus::UNKNOWN},
11277
Eric Roman8673b812017-09-20 18:57:3111278 // 15
dadrian612337a2016-07-20 22:36:5811279 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11280 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11281 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11282 OCSPVerifyResult::PROVIDED,
11283 true,
11284 OCSPRevocationStatus::GOOD},
11285
Eric Roman8673b812017-09-20 18:57:3111286 // 16
dadrian612337a2016-07-20 22:36:5811287 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11288 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11289 {SpawnedTestServer::SSLOptions::OCSP_OK,
11290 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11291 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11292 OCSPVerifyResult::PROVIDED,
11293 true,
11294 OCSPRevocationStatus::GOOD},
11295
Eric Roman8673b812017-09-20 18:57:3111296 // 17
dadrian612337a2016-07-20 22:36:5811297 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11298 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11299 {SpawnedTestServer::SSLOptions::OCSP_OK,
11300 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11301 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11302 OCSPVerifyResult::PROVIDED,
11303 true,
11304 OCSPRevocationStatus::GOOD},
11305
Eric Roman8673b812017-09-20 18:57:3111306 // 18
dadrian612337a2016-07-20 22:36:5811307 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11308 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11309 {SpawnedTestServer::SSLOptions::OCSP_OK,
11310 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11311 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11312 OCSPVerifyResult::PROVIDED,
11313 true,
11314 OCSPRevocationStatus::GOOD},
11315
Eric Roman8673b812017-09-20 18:57:3111316 // 19
dadrian612337a2016-07-20 22:36:5811317 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11318 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11319 {SpawnedTestServer::SSLOptions::OCSP_OK,
11320 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11321 {SpawnedTestServer::SSLOptions::OCSP_OK,
11322 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11323 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11324 OCSPVerifyResult::INVALID_DATE,
11325 false,
11326 OCSPRevocationStatus::UNKNOWN},
11327
Eric Roman8673b812017-09-20 18:57:3111328 // 20
dadrian612337a2016-07-20 22:36:5811329 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11330 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11331 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11332 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11333 {SpawnedTestServer::SSLOptions::OCSP_OK,
11334 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11335 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11336 OCSPVerifyResult::PROVIDED,
11337 true,
11338 OCSPRevocationStatus::REVOKED},
11339
Eric Roman8673b812017-09-20 18:57:3111340 // 21
dadrian612337a2016-07-20 22:36:5811341 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11342 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11343 {SpawnedTestServer::SSLOptions::OCSP_OK,
11344 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11345 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11346 OCSPVerifyResult::PROVIDED,
11347 true,
11348 OCSPRevocationStatus::UNKNOWN},
11349
Eric Roman8673b812017-09-20 18:57:3111350 // 22
dadrian612337a2016-07-20 22:36:5811351 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11352 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11353 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11354 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11355 {SpawnedTestServer::SSLOptions::OCSP_OK,
11356 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11357 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11358 OCSPVerifyResult::PROVIDED,
11359 true,
11360 OCSPRevocationStatus::UNKNOWN},
11361
Eric Roman8673b812017-09-20 18:57:3111362 // 23
dadrian612337a2016-07-20 22:36:5811363 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11364 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11365 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11366 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11367 false,
11368 OCSPRevocationStatus::UNKNOWN},
11369
Eric Roman8673b812017-09-20 18:57:3111370 // 24
dadrian612337a2016-07-20 22:36:5811371 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11372 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11373 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11374 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11375 false,
11376 OCSPRevocationStatus::UNKNOWN},
11377
Eric Roman8673b812017-09-20 18:57:3111378// These tests fail when using NSS for certificate verification, as NSS fails
11379// and doesn't return the partial path. As a result the OCSP checks being done
11380// at the CertVerifyProc layer cannot access the issuer certificate.
11381#if !defined(USE_NSS_CERTS)
11382 // 25
11383 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11384 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11385 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11386 OCSPVerifyResult::PROVIDED,
11387 true,
11388 OCSPRevocationStatus::REVOKED},
11389
11390 // 26
11391 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11392 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11393 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11394 OCSPVerifyResult::INVALID_DATE,
11395 false,
11396 OCSPRevocationStatus::UNKNOWN},
11397
11398 // 27
11399 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11400 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11401 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11402 OCSPVerifyResult::INVALID_DATE,
11403 false,
11404 OCSPRevocationStatus::UNKNOWN},
11405#endif
dadrian612337a2016-07-20 22:36:5811406};
11407
11408class HTTPSOCSPVerifyTest
11409 : public HTTPSOCSPTest,
11410 public testing::WithParamInterface<OCSPVerifyTestData> {};
11411
11412TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
11413 SpawnedTestServer::SSLOptions ssl_options(
11414 SpawnedTestServer::SSLOptions::CERT_AUTO);
11415 OCSPVerifyTestData test = GetParam();
11416
11417 ssl_options.ocsp_responses = test.ocsp_responses;
11418 ssl_options.ocsp_produced = test.ocsp_produced;
11419 ssl_options.staple_ocsp_response = true;
11420
11421 SSLInfo ssl_info;
11422 OCSPErrorTestDelegate delegate;
11423 ASSERT_NO_FATAL_FAILURE(
11424 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
11425
11426 // The SSLInfo must be extracted from |delegate| on error, due to how
11427 // URLRequest caches certificate errors.
11428 if (delegate.have_certificate_errors()) {
11429 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
11430 ssl_info = delegate.ssl_info();
11431 }
11432
11433 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
11434
11435 if (test.has_revocation_status)
11436 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
11437}
11438
Victor Costan8fb98f6f2019-02-01 17:08:2911439INSTANTIATE_TEST_SUITE_P(OCSPVerify,
11440 HTTPSOCSPVerifyTest,
11441 testing::ValuesIn(kOCSPVerifyData));
dadrian612337a2016-07-20 22:36:5811442
mattm0b12a6f2016-11-29 19:57:1611443class HTTPSAIATest : public HTTPSOCSPTest {
11444 public:
Ryan Sleevi24fe2682018-08-16 21:33:4611445 CertVerifier::Config GetCertVerifierConfig() override {
11446 CertVerifier::Config config;
11447 return config;
mattm0b12a6f2016-11-29 19:57:1611448 }
11449};
11450
11451TEST_F(HTTPSAIATest, AIAFetching) {
11452 SpawnedTestServer::SSLOptions ssl_options(
11453 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
11454 SpawnedTestServer test_server(
11455 SpawnedTestServer::TYPE_HTTPS, ssl_options,
11456 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11457 ASSERT_TRUE(test_server.Start());
11458
Ryan Sleevi5b4702a2018-04-06 22:23:5611459 // Unmark the certificate's OID as EV, which will disable revocation
11460 // checking.
11461 ev_test_policy_.reset();
11462
mattm0b12a6f2016-11-29 19:57:1611463 TestDelegate d;
11464 d.set_allow_certificate_errors(true);
11465 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611466 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11467 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611468
11469 r->Start();
11470 EXPECT_TRUE(r->is_pending());
11471
Wez2a31b222018-06-07 22:07:1511472 d.RunUntilComplete();
mattm0b12a6f2016-11-29 19:57:1611473
11474 EXPECT_EQ(1, d.response_started_count());
11475
11476 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4811477 EXPECT_EQ(OK, d.request_status());
11478 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11479 ASSERT_TRUE(r->ssl_info().cert);
11480 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611481 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3411482 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611483}
11484
[email protected]3a86a712013-07-30 07:16:2011485class HTTPSHardFailTest : public HTTPSOCSPTest {
11486 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611487 CertVerifier::Config GetCertVerifierConfig() override {
11488 CertVerifier::Config config;
11489 config.require_rev_checking_local_anchors = true;
11490 return config;
[email protected]3a86a712013-07-30 07:16:2011491 }
11492};
11493
[email protected]3a86a712013-07-30 07:16:2011494TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
11495 if (!SystemSupportsOCSP()) {
11496 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11497 return;
11498 }
11499
11500 if (!SystemSupportsHardFailRevocationChecking()) {
11501 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
11502 << "revocation checking";
11503 return;
11504 }
11505
11506 SpawnedTestServer::SSLOptions ssl_options(
11507 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811508 ssl_options.ocsp_status =
11509 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2011510
11511 CertStatus cert_status;
11512 DoConnection(ssl_options, &cert_status);
11513
Eric Roman1b628daa2017-10-19 19:52:0411514#if defined(USE_BUILTIN_CERT_VERIFIER)
11515 // TODO(crbug.com/649017): Should we consider invalid response as
11516 // affirmatively revoked?
11517 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11518 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11519#else
11520 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
11521#endif
[email protected]3a86a712013-07-30 07:16:2011522
11523 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0411524 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2011525 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11526}
11527
[email protected]a13234c2012-03-20 21:45:0211528class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
11529 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611530 CertVerifier::Config GetCertVerifierConfig() override {
11531 CertVerifier::Config config;
11532 return config;
[email protected]a13234c2012-03-20 21:45:0211533 }
11534};
11535
11536TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
11537 if (!SystemSupportsOCSP()) {
11538 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11539 return;
11540 }
11541
[email protected]ce7d0cbc2013-05-03 18:57:2211542 SpawnedTestServer::SSLOptions ssl_options(
11543 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811544 ssl_options.ocsp_status =
11545 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211546
[email protected]924e9f92012-12-16 22:00:5311547 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211548 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211549
mattmaf868e72016-09-23 23:25:2011550 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211551 cert_status & CERT_STATUS_ALL_ERRORS);
11552
11553 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811554 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11555 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211556}
11557
[email protected]be0fff62013-08-29 23:37:4811558TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
11559 if (!SystemSupportsOCSP()) {
11560 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11561 return;
11562 }
11563
11564 SpawnedTestServer::SSLOptions ssl_options(
11565 SpawnedTestServer::SSLOptions::CERT_AUTO);
11566 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]be0fff62013-08-29 23:37:4811567
11568 CertStatus cert_status;
11569 DoConnection(ssl_options, &cert_status);
11570
mattm1a282f52016-11-10 21:49:4211571// Currently only works for Windows and OS X. When using NSS, it's not
11572// possible to determine whether the check failed because of actual
11573// revocation or because there was an OCSP failure.
11574#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4811575 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11576#else
11577 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11578#endif
11579
11580 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11581 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11582 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11583}
11584
[email protected]a13234c2012-03-20 21:45:0211585TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
11586 if (!SystemSupportsOCSP()) {
11587 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11588 return;
11589 }
11590
[email protected]ce7d0cbc2013-05-03 18:57:2211591 SpawnedTestServer::SSLOptions ssl_options(
11592 SpawnedTestServer::SSLOptions::CERT_AUTO);
11593 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0211594
11595 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211596 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211597
11598 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11599
11600 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11601 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0811602 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11603 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211604}
11605
11606TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
11607 if (!SystemSupportsOCSP()) {
11608 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11609 return;
11610 }
11611
[email protected]ce7d0cbc2013-05-03 18:57:2211612 SpawnedTestServer::SSLOptions ssl_options(
11613 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811614 ssl_options.ocsp_status =
11615 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211616 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11617 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11618 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211619
11620 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211621 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211622
mattmaf868e72016-09-23 23:25:2011623 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211624 cert_status & CERT_STATUS_ALL_ERRORS);
11625
11626 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811627 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11628 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211629}
11630
[email protected]51523f52013-07-31 21:57:2811631TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
11632 if (!SystemSupportsOCSP()) {
11633 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11634 return;
11635 }
11636
11637 SpawnedTestServer::SSLOptions ssl_options(
11638 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811639 ssl_options.ocsp_status =
11640 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211641 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11642 cert_verifier_config.crl_set =
11643 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {});
11644 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2811645
11646 CertStatus cert_status;
11647 DoConnection(ssl_options, &cert_status);
11648
11649 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
11650 // revocation check for EV.
11651 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11652 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11653 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11654 EXPECT_FALSE(
11655 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11656}
11657
11658TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
11659 if (!SystemSupportsOCSP()) {
11660 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11661 return;
11662 }
11663
[email protected]ce7d0cbc2013-05-03 18:57:2211664 SpawnedTestServer::SSLOptions ssl_options(
11665 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811666 ssl_options.ocsp_status =
11667 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211668 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11669 cert_verifier_config.crl_set = CRLSet::EmptyCRLSetForTesting();
11670 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211671
[email protected]51523f52013-07-31 21:57:2811672 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1211673 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211674
[email protected]51523f52013-07-31 21:57:2811675 // Even with a fresh CRLSet, we should still do online revocation checks when
11676 // the certificate chain isn't covered by the CRLSet, which it isn't in this
11677 // test.
mattmaf868e72016-09-23 23:25:2011678 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2811679 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0211680
[email protected]51523f52013-07-31 21:57:2811681 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0211682 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2811683 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211684}
11685
11686class HTTPSCRLSetTest : public HTTPSOCSPTest {
11687 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611688 CertVerifier::Config GetCertVerifierConfig() override {
11689 CertVerifier::Config config;
11690 return config;
Ryan Sleevi5b4702a2018-04-06 22:23:5611691 }
11692
11693 void SetUp() override {
11694 HTTPSOCSPTest::SetUp();
11695
11696 // Unmark the certificate's OID as EV, which should disable revocation
11697 // checking (as per the user preference).
11698 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0211699 }
11700};
11701
11702TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2211703 SpawnedTestServer::SSLOptions ssl_options(
11704 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811705 ssl_options.ocsp_status =
11706 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211707 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11708 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11709 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211710
[email protected]924e9f92012-12-16 22:00:5311711 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211712 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211713
11714 // If we're not trying EV verification then, even if the CRLSet has expired,
11715 // we don't fall back to online revocation checks.
11716 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11717 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11718 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11719}
[email protected]51523f52013-07-31 21:57:2811720
Ryan Sleevi5b4702a2018-04-06 22:23:5611721TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
11722 // Test that when online revocation checking is disabled, and the leaf
11723 // certificate is not EV, that no revocation checking actually happens.
11724 if (!SystemSupportsOCSP()) {
11725 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11726 return;
11727 }
11728
11729 SpawnedTestServer::SSLOptions ssl_options(
11730 SpawnedTestServer::SSLOptions::CERT_AUTO);
11731 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Ryan Sleevib369d712018-08-20 16:43:2211732
11733 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11734 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11735 context_.cert_verifier()->SetConfig(cert_verifier_config);
Ryan Sleevi5b4702a2018-04-06 22:23:5611736
11737 CertStatus cert_status;
11738 DoConnection(ssl_options, &cert_status);
11739
11740 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11741
11742 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11743 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11744}
11745
[email protected]51523f52013-07-31 21:57:2811746TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2511747#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2811748 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11749 return;
11750#endif
11751
11752 SpawnedTestServer::SSLOptions ssl_options(
11753 SpawnedTestServer::SSLOptions::CERT_AUTO);
11754 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11755 ssl_options.cert_serial = 10;
Ryan Sleevib369d712018-08-20 16:43:2211756
11757 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11758 cert_verifier_config.crl_set =
11759 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {});
11760 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2811761
11762 CertStatus cert_status = 0;
11763 DoConnection(ssl_options, &cert_status);
11764
11765 // If the certificate is recorded as revoked in the CRLSet, that should be
11766 // reflected without online revocation checking.
11767 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11768 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5611769 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2811770}
Adam Langleyea6d6782017-12-05 23:57:3311771
11772TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
11773#if defined(OS_ANDROID)
11774 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11775 return;
11776#endif
11777
11778 SpawnedTestServer::SSLOptions ssl_options(
11779 SpawnedTestServer::SSLOptions::CERT_AUTO);
11780 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11781 static const char kCommonName[] = "Test CN";
11782 ssl_options.cert_common_name = kCommonName;
11783
11784 {
Ryan Sleevib369d712018-08-20 16:43:2211785 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11786 cert_verifier_config.crl_set =
11787 CRLSet::ForTesting(false, nullptr, "", kCommonName, {});
11788 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3311789
11790 CertStatus cert_status = 0;
11791 DoConnection(ssl_options, &cert_status);
11792
11793 // If the certificate is recorded as revoked in the CRLSet, that should be
11794 // reflected without online revocation checking.
11795 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11796 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5611797 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3311798 }
11799
11800 const uint8_t kTestServerSPKISHA256[32] = {
11801 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
11802 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
11803 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
11804 };
11805 const std::string spki_hash(
11806 reinterpret_cast<const char*>(kTestServerSPKISHA256),
11807 sizeof(kTestServerSPKISHA256));
11808
11809 {
Ryan Sleevib369d712018-08-20 16:43:2211810 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11811 cert_verifier_config.crl_set =
11812 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash});
11813 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3311814
11815 CertStatus cert_status = 0;
11816 DoConnection(ssl_options, &cert_status);
11817
11818 // When the correct SPKI hash is specified, the connection should succeed
11819 // even though the subject is listed in the CRLSet.
11820 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11821 }
11822}
[email protected]316c1e5e2012-09-12 15:17:4411823#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2711824
Sergey Ulanovc4580e72017-09-13 23:30:1111825#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
11826 !defined(OS_FUCHSIA)
11827// FTP uses a second TCP connection with the port number allocated dynamically
11828// on the server side, so it would be hard to make RemoteTestServer proxy FTP
11829// connections reliably. FTP tests are disabled on platforms that use
11830// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3111831class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1111832 public:
[email protected]d9fca99a2012-02-24 16:16:2011833 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0511834 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5511835 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4711836 // Can't use |default_context_|'s HostResolver to set up the
11837 // FTPTransactionFactory because it hasn't been created yet.
Ryan Sleevib8449e02018-07-15 04:31:0711838 default_context().set_host_resolver(&host_resolver_);
mmenke9f2ec60c2015-06-01 20:59:4711839 }
11840
11841 // URLRequestTest interface:
11842 void SetUpFactory() override {
11843 // Add FTP support to the default URLRequestContext.
11844 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0511845 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4711846 }
11847
11848 std::string GetTestFileContents() {
11849 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1911850 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4711851 path = path.Append(kTestFilePath);
11852 path = path.AppendASCII(kFtpTestFile);
11853 std::string contents;
11854 EXPECT_TRUE(base::ReadFileToString(path, &contents));
11855 return contents;
[email protected]95409e12010-08-17 20:07:1111856 }
11857
[email protected]b89ca032009-08-31 21:41:3111858 protected:
mmenke9f2ec60c2015-06-01 20:59:4711859 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4711860
tommycli59a63432015-11-06 00:10:5511861 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3111862};
11863
[email protected]d2a133182012-08-05 16:44:0811864// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0911865TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0811866 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0811867
11868 TestDelegate d;
11869 {
Ryan Sleevib8449e02018-07-15 04:31:0711870 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611871 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911872 r->Start();
11873 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0811874
Wez2a31b222018-06-07 22:07:1511875 d.RunUntilComplete();
[email protected]d2a133182012-08-05 16:44:0811876
[email protected]f7022f32014-08-21 16:32:1911877 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5011878 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0811879 }
11880}
11881
mmenke9f2ec60c2015-06-01 20:59:4711882TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5511883 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111884
[email protected]a25e90e2009-09-09 17:05:3711885 TestDelegate d;
11886 {
Ryan Sleevib8449e02018-07-15 04:31:0711887 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611888 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
11889 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911890 r->Start();
11891 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711892
Wez2a31b222018-06-07 22:07:1511893 d.RunUntilComplete();
[email protected]a25e90e2009-09-09 17:05:3711894
[email protected]f7022f32014-08-21 16:32:1911895 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711896 EXPECT_EQ(1, d.response_started_count());
11897 EXPECT_FALSE(d.received_data_before_response());
11898 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5511899 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711900 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5511901 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711902 r->GetResponseRemoteEndpoint().port());
[email protected]a25e90e2009-09-09 17:05:3711903 }
11904}
11905
mmenke9f2ec60c2015-06-01 20:59:4711906TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5511907 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111908
[email protected]dd265012009-01-08 20:45:2711909 TestDelegate d;
11910 {
Ryan Sleevib8449e02018-07-15 04:31:0711911 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611912 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
11913 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911914 r->Start();
11915 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711916
Wez2a31b222018-06-07 22:07:1511917 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711918
[email protected]f7022f32014-08-21 16:32:1911919 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711920 EXPECT_EQ(1, d.response_started_count());
11921 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711922 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511923 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711924 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5511925 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711926 r->GetResponseRemoteEndpoint().port());
[email protected]dd265012009-01-08 20:45:2711927 }
11928}
11929
Mike West80462a12018-11-27 16:05:0611930TEST_F(URLRequestTestFTP, FTPMimeType) {
11931 ASSERT_TRUE(ftp_test_server_.Start());
11932
11933 struct {
11934 const char* path;
11935 const char* mime;
11936 } test_cases[] = {
11937 {"/", "text/vnd.chromium.ftp-dir"},
11938 {kFtpTestFile, "application/octet-stream"},
11939 };
11940
11941 for (const auto test : test_cases) {
11942 TestDelegate d;
11943
11944 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
11945 ftp_test_server_.GetURL(test.path), DEFAULT_PRIORITY, &d,
11946 TRAFFIC_ANNOTATION_FOR_TESTS));
11947 r->Start();
11948 EXPECT_TRUE(r->is_pending());
11949
11950 d.RunUntilComplete();
11951
11952 std::string mime;
11953 r->GetMimeType(&mime);
11954 EXPECT_EQ(test.mime, mime);
11955 }
11956}
11957
mmenke9f2ec60c2015-06-01 20:59:4711958TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5511959 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111960
[email protected]dd265012009-01-08 20:45:2711961 TestDelegate d;
11962 {
Ryan Sleevib8449e02018-07-15 04:31:0711963 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511964 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11965 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611966 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911967 r->Start();
11968 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711969
Wez2a31b222018-06-07 22:07:1511970 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711971
[email protected]f7022f32014-08-21 16:32:1911972 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4711973 EXPECT_EQ(1, d.response_started_count());
11974 EXPECT_FALSE(d.received_data_before_response());
11975 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511976 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711977 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5511978 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3711979 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:2511980
11981 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1911982 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2511983 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2711984 }
11985}
11986
mmenke9f2ec60c2015-06-01 20:59:4711987TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5511988 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111989
[email protected]dd265012009-01-08 20:45:2711990 TestDelegate d;
11991 {
Ryan Sleevib8449e02018-07-15 04:31:0711992 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511993 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11994 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611995 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911996 r->Start();
11997 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711998
Wez2a31b222018-06-07 22:07:1511999 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712000
[email protected]f7022f32014-08-21 16:32:1912001 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712002 EXPECT_EQ(1, d.response_started_count());
12003 EXPECT_FALSE(d.received_data_before_response());
12004 EXPECT_EQ(d.bytes_received(), 0);
12005 }
12006}
12007
mmenke9f2ec60c2015-06-01 20:59:4712008TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5512009 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112010
[email protected]8b8a197d2009-08-26 15:57:5812011 TestDelegate d;
12012 // Set correct login credentials. The delegate will be asked for them when
12013 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812014 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812015 {
Ryan Sleevib8449e02018-07-15 04:31:0712016 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512017 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12018 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612019 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912020 r->Start();
12021 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812022
Wez2a31b222018-06-07 22:07:1512023 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812024
[email protected]f7022f32014-08-21 16:32:1912025 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812026 EXPECT_EQ(1, d.response_started_count());
12027 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712028 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812029 }
12030}
12031
mmenke9f2ec60c2015-06-01 20:59:4712032TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5512033 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112034
[email protected]dd265012009-01-08 20:45:2712035 TestDelegate d;
12036 {
Ryan Sleevib8449e02018-07-15 04:31:0712037 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512038 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12039 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612040 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912041 r->Start();
12042 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712043
Wez2a31b222018-06-07 22:07:1512044 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712045
[email protected]f7022f32014-08-21 16:32:1912046 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712047 EXPECT_EQ(1, d.response_started_count());
12048 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712049 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2712050 }
12051}
[email protected]8b8a197d2009-08-26 15:57:5812052
mmenke9f2ec60c2015-06-01 20:59:4712053TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5512054 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112055
[email protected]8b8a197d2009-08-26 15:57:5812056 TestDelegate d;
12057 // Set correct login credentials. The delegate will be asked for them when
12058 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812059 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812060 {
Ryan Sleevib8449e02018-07-15 04:31:0712061 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512062 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12063 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612064 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912065 r->Start();
12066 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812067
Wez2a31b222018-06-07 22:07:1512068 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812069
[email protected]f7022f32014-08-21 16:32:1912070 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812071 EXPECT_EQ(1, d.response_started_count());
12072 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712073 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812074 }
12075}
[email protected]60a3df52009-09-22 16:13:2412076
mmenke9f2ec60c2015-06-01 20:59:4712077TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5512078 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112079
danakj8522a25b2016-04-16 00:17:3612080 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412081 {
12082 // Pass correct login identity in the URL.
Ryan Sleevib8449e02018-07-15 04:31:0712083 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512084 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12085 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612086 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912087 r->Start();
12088 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412089
Wez2a31b222018-06-07 22:07:1512090 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412091
[email protected]f7022f32014-08-21 16:32:1912092 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412093 EXPECT_EQ(1, d->response_started_count());
12094 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712095 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412096 }
12097
12098 d.reset(new TestDelegate);
12099 {
12100 // This request should use cached identity from previous request.
Ryan Sleevib8449e02018-07-15 04:31:0712101 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612102 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12103 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912104 r->Start();
12105 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412106
Wez2a31b222018-06-07 22:07:1512107 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412108
[email protected]f7022f32014-08-21 16:32:1912109 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412110 EXPECT_EQ(1, d->response_started_count());
12111 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712112 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412113 }
12114}
12115
mmenke9f2ec60c2015-06-01 20:59:4712116TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5512117 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112118
danakj8522a25b2016-04-16 00:17:3612119 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412120 // Set correct login credentials. The delegate will be asked for them when
12121 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812122 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2412123 {
Ryan Sleevib8449e02018-07-15 04:31:0712124 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512125 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12126 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612127 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912128 r->Start();
12129 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412130
Wez2a31b222018-06-07 22:07:1512131 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412132
[email protected]f7022f32014-08-21 16:32:1912133 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412134 EXPECT_EQ(1, d->response_started_count());
12135 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712136 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412137 }
12138
12139 // Use a new delegate without explicit credentials. The cached ones should be
12140 // used.
12141 d.reset(new TestDelegate);
12142 {
12143 // Don't pass wrong credentials in the URL, they would override valid cached
12144 // ones.
Ryan Sleevib8449e02018-07-15 04:31:0712145 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612146 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12147 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912148 r->Start();
12149 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412150
Wez2a31b222018-06-07 22:07:1512151 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412152
[email protected]f7022f32014-08-21 16:32:1912153 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412154 EXPECT_EQ(1, d->response_started_count());
12155 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712156 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412157 }
12158}
ricea3a1c71f2016-06-17 10:05:2612159
12160TEST_F(URLRequestTestFTP, RawBodyBytes) {
12161 ASSERT_TRUE(ftp_test_server_.Start());
12162
12163 TestDelegate d;
12164 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612165 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12166 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2612167 req->Start();
Wez2a31b222018-06-07 22:07:1512168 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:2612169
12170 EXPECT_EQ(6, req->GetRawBodyBytes());
12171}
12172
brettwa1228ebb2016-10-28 03:51:3412173#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5112174
ttuttlec0c828492015-05-15 01:25:5512175TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
12176 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712177 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612178 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512179
12180 EXPECT_FALSE(req->response_info().network_accessed);
12181
12182 req->Start();
Wez2a31b222018-06-07 22:07:1512183 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512184
12185 EXPECT_EQ(1, default_network_delegate_.completed_requests());
12186 EXPECT_FALSE(req->response_info().network_accessed);
12187}
12188
12189TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
12190 MockHostResolver host_resolver;
12191 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
12192 TestURLRequestContext context(true);
12193 context.set_network_delegate(&network_delegate);
12194 context.set_host_resolver(&host_resolver);
12195 host_resolver.rules()->AddSimulatedFailure("*");
12196 context.Init();
12197
12198 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612199 std::unique_ptr<URLRequest> req(
12200 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
12201 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512202
12203 EXPECT_FALSE(req->response_info().network_accessed);
12204
12205 req->Start();
Wez2a31b222018-06-07 22:07:1512206 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512207 EXPECT_TRUE(req->response_info().network_accessed);
12208}
12209
mmenkeed0498b2015-12-08 23:20:4212210// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2212211// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4212212TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2212213 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712214 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612215 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
12216 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2212217
danakj8522a25b2016-04-16 00:17:3612218 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2212219 req.get(), &default_network_delegate_,
12220 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4212221 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
12222 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2212223
12224 req->Start();
12225 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2212226 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5012227 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2212228 EXPECT_EQ(0, d.received_redirect_count());
12229}
12230
Andrey Kosyakov2e893e62017-08-31 17:00:5212231TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412232 ASSERT_TRUE(http_test_server()->Start());
12233 TestURLRequestContext context;
12234 GURL url(http_test_server()->GetURL("/cachetime"));
12235 TestDelegate delegate;
12236 HttpRequestHeaders extra_headers;
12237 extra_headers.SetHeader("X-Foo", "bar");
12238
12239 {
Andrey Kosyakov2e893e62017-08-31 17:00:5212240 HttpRawRequestHeaders raw_req_headers;
12241 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12242
Andrey Kosyakov83a6eee2017-08-14 19:20:0412243 std::unique_ptr<URLRequest> r(context.CreateRequest(
12244 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12245 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212246 r->SetRequestHeadersCallback(base::Bind(
12247 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
12248 r->SetResponseHeadersCallback(base::Bind(
12249 [](scoped_refptr<const HttpResponseHeaders>* left,
12250 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12251 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412252 r->Start();
12253 while (!delegate.response_started_count())
12254 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5212255 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412256 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212257 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412258 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212259 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412260 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212261 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
12262 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
12263 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
12264 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412265 }
12266 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412267 std::unique_ptr<URLRequest> r(context.CreateRequest(
12268 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12269 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212270 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412271 FAIL() << "Callback should not be called unless request is sent";
12272 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212273 r->SetResponseHeadersCallback(
12274 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
12275 FAIL() << "Callback should not be called unless request is sent";
12276 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412277 r->Start();
Wez2a31b222018-06-07 22:07:1512278 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412279 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412280 }
12281}
12282
Andrey Kosyakov2e893e62017-08-31 17:00:5212283TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412284 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5212285 HttpRawRequestHeaders raw_req_headers;
12286 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12287
Andrey Kosyakov83a6eee2017-08-14 19:20:0412288 TestURLRequestContext context;
12289 TestDelegate delegate;
12290 HttpRequestHeaders extra_headers;
12291 extra_headers.SetHeader("X-Foo", "bar");
Andrey Kosyakov83a6eee2017-08-14 19:20:0412292 GURL url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:0712293 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412294 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12295 r->SetExtraRequestHeaders(extra_headers);
12296 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5212297 base::Unretained(&raw_req_headers)));
12298 r->SetResponseHeadersCallback(base::Bind(
12299 [](scoped_refptr<const HttpResponseHeaders>* left,
12300 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12301 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412302 r->Start();
Wez0e717112018-06-18 23:09:2212303 delegate.RunUntilRedirect();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412304
12305 ASSERT_EQ(1, delegate.received_redirect_count());
12306 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212307 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412308 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212309 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412310 EXPECT_EQ("gzip, deflate", value);
12311 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5212312 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
12313 raw_req_headers.request_line());
12314 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
12315 EXPECT_EQ(302, raw_resp_headers->response_code());
12316 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412317
Andrey Kosyakov2e893e62017-08-31 17:00:5212318 raw_req_headers = HttpRawRequestHeaders();
12319 raw_resp_headers = nullptr;
Arthur Sonzognib8465ff72019-01-04 18:44:3512320 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
12321 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:1512322 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212323 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412324 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212325 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412326 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212327 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
12328 raw_req_headers.request_line());
12329 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412330}
12331
Andrey Kosyakov2e893e62017-08-31 17:00:5212332TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412333 TestDelegate request_delegate;
12334
Ryan Sleevib8449e02018-07-15 04:31:0712335 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412336 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
12337 TRAFFIC_ANNOTATION_FOR_TESTS));
12338 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
12339 FAIL() << "Callback should not be called unless request is sent";
12340 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212341 r->SetResponseHeadersCallback(
12342 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12343 FAIL() << "Callback should not be called unless request is sent";
12344 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412345 r->Start();
Wez2a31b222018-06-07 22:07:1512346 request_delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412347 EXPECT_FALSE(r->is_pending());
12348}
12349
Andrey Kosyakov2e893e62017-08-31 17:00:5212350TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412351 ASSERT_TRUE(http_test_server()->Start());
12352 GURL url(http_test_server()->GetURL("/auth-basic"));
12353
12354 TestURLRequestContext context;
12355 TestDelegate delegate;
12356
12357 delegate.set_credentials(AuthCredentials(kUser, kSecret));
12358 HttpRequestHeaders extra_headers;
12359 extra_headers.SetHeader("X-Foo", "bar");
12360
Andrey Kosyakov2e893e62017-08-31 17:00:5212361 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
12362 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0412363
Andrey Kosyakov2e893e62017-08-31 17:00:5212364 using RespHeadersVector =
12365 std::vector<scoped_refptr<const HttpResponseHeaders>>;
12366 RespHeadersVector raw_resp_headers;
12367
12368 auto req_headers_callback = base::Bind(
12369 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
12370 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
12371 },
12372 &raw_req_headers);
12373 auto resp_headers_callback = base::Bind(
12374 [](RespHeadersVector* vec,
12375 scoped_refptr<const HttpResponseHeaders> headers) {
12376 vec->push_back(headers);
12377 },
12378 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412379 std::unique_ptr<URLRequest> r(context.CreateRequest(
12380 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12381 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212382 r->SetRequestHeadersCallback(req_headers_callback);
12383 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412384 r->Start();
Wez2a31b222018-06-07 22:07:1512385 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412386 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5212387 ASSERT_EQ(raw_req_headers.size(), 2u);
12388 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412389 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212390 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
12391 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412392 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212393 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
12394 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412395 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212396 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
12397 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
12398 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
12399 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
12400
12401 std::unique_ptr<URLRequest> r2(context.CreateRequest(
12402 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12403 r2->SetExtraRequestHeaders(extra_headers);
12404 r2->SetRequestHeadersCallback(req_headers_callback);
12405 r2->SetResponseHeadersCallback(resp_headers_callback);
12406 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
12407 r2->Start();
Wez2a31b222018-06-07 22:07:1512408 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212409 EXPECT_FALSE(r2->is_pending());
12410 ASSERT_EQ(raw_req_headers.size(), 3u);
12411 ASSERT_EQ(raw_resp_headers.size(), 3u);
12412 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
12413 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
12414 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
12415 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412416}
12417
Andrey Kosyakov2e893e62017-08-31 17:00:5212418TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412419 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
12420 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712421 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412422 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12423 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5212424 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0412425 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212426 r->SetResponseHeadersCallback(
12427 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12428 FAIL() << "Callback should not be called for non-HTTP schemes";
12429 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412430 r->Start();
Wez2a31b222018-06-07 22:07:1512431 d.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412432 EXPECT_FALSE(r->is_pending());
12433}
12434
Carlos ILaef65d62018-06-04 21:24:1312435TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
12436 TestDelegate d;
12437 BlockingNetworkDelegate network_delegate(
12438 BlockingNetworkDelegate::SYNCHRONOUS);
12439 const GURL kOriginalUrl("https://original.test");
12440 const GURL kRedirectUrl("http://redirect.test");
12441 network_delegate.set_redirect_url(kRedirectUrl);
12442 TestURLRequestContext context(true /* delay_initialization */);
12443 context.set_network_delegate(&network_delegate);
12444 context.Init();
12445
12446 std::unique_ptr<URLRequest> r(context.CreateRequest(
12447 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12448 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312449 r->Start();
Wez0e717112018-06-18 23:09:2212450 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312451 GURL::Replacements replacements;
12452 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12453 // was set.
12454 replacements.SetSchemeStr("https");
12455 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12456 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412457 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312458}
12459
12460TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
12461 TestDelegate d;
12462 BlockingNetworkDelegate network_delegate(
12463 BlockingNetworkDelegate::SYNCHRONOUS);
12464 const GURL kOriginalUrl("https://original.test");
12465 const GURL kRedirectUrl("http://redirect.test:80");
12466 network_delegate.set_redirect_url(kRedirectUrl);
12467 TestURLRequestContext context(true /* delay_initialization */);
12468 context.set_network_delegate(&network_delegate);
12469 context.Init();
12470
12471 std::unique_ptr<URLRequest> r(context.CreateRequest(
12472 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12473 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312474 r->Start();
Wez0e717112018-06-18 23:09:2212475 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312476 GURL::Replacements replacements;
12477 // The URL host should have not been changed.
12478 EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
12479 // The scheme should now be https, and the effective port should now be 443.
12480 EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
12481 EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
Carlos IL0d67fc72018-06-22 17:18:4412482 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312483}
12484
12485TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
12486 TestDelegate d;
12487 BlockingNetworkDelegate network_delegate(
12488 BlockingNetworkDelegate::SYNCHRONOUS);
12489 const GURL kOriginalUrl("https://original.test");
12490 const GURL kRedirectUrl("http://redirect.test:1234");
12491 network_delegate.set_redirect_url(kRedirectUrl);
12492 TestURLRequestContext context(true /* delay_initialization */);
12493 context.set_network_delegate(&network_delegate);
12494 context.Init();
12495
12496 std::unique_ptr<URLRequest> r(context.CreateRequest(
12497 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12498 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312499 r->Start();
Wez0e717112018-06-18 23:09:2212500 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312501 GURL::Replacements replacements;
12502 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12503 // was set, nonstandard port should not have been modified.
12504 replacements.SetSchemeStr("https");
12505 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12506 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412507 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312508}
12509
12510TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
12511 TestDelegate d;
12512 BlockingNetworkDelegate network_delegate(
12513 BlockingNetworkDelegate::SYNCHRONOUS);
12514 const GURL kOriginalUrl("https://original.test");
12515 const GURL kRedirectUrl("http://redirect.test");
12516 network_delegate.set_redirect_url(kRedirectUrl);
12517 TestURLRequestContext context(true /* delay_initialization */);
12518 context.set_network_delegate(&network_delegate);
12519 context.Init();
12520 std::unique_ptr<URLRequest> r(context.CreateRequest(
12521 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12522 r->set_upgrade_if_insecure(false);
Carlos ILaef65d62018-06-04 21:24:1312523 r->Start();
Wez0e717112018-06-18 23:09:2212524 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312525 // The redirect URL should not be changed if the upgrade_if_insecure flag is
12526 // not set.
12527 EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412528 EXPECT_FALSE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312529}
12530
Paul Jensen60e45532018-02-19 16:04:1812531// Test that URLRequests get properly tagged.
12532#if defined(OS_ANDROID)
12533TEST_F(URLRequestTestHTTP, TestTagging) {
Peter Collingbourne8ccab722019-02-12 18:10:4812534 if (!CanGetTaggedBytes()) {
12535 DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
12536 return;
12537 }
12538
Paul Jensen60e45532018-02-19 16:04:1812539 ASSERT_TRUE(http_test_server()->Start());
12540
12541 // The tag under which the system reports untagged traffic.
12542 static const int32_t UNTAGGED_TAG = 0;
12543
12544 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
12545
12546 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
12547 TestDelegate delegate;
Ryan Sleevib8449e02018-07-15 04:31:0712548 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Paul Jensen60e45532018-02-19 16:04:1812549 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
12550 TRAFFIC_ANNOTATION_FOR_TESTS));
12551 EXPECT_EQ(SocketTag(), req->socket_tag());
12552 req->Start();
Wez2a31b222018-06-07 22:07:1512553 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812554
12555 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
12556
12557 int32_t tag_val1 = 0x12345678;
12558 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
12559 old_traffic = GetTaggedBytes(tag_val1);
12560
12561 // Test specific tag value.
Ryan Sleevib8449e02018-07-15 04:31:0712562 req = default_context().CreateRequest(http_test_server()->GetURL("/"),
12563 DEFAULT_PRIORITY, &delegate,
12564 TRAFFIC_ANNOTATION_FOR_TESTS);
Paul Jensen60e45532018-02-19 16:04:1812565 req->set_socket_tag(tag1);
12566 EXPECT_EQ(tag1, req->socket_tag());
12567 req->Start();
Wez2a31b222018-06-07 22:07:1512568 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812569
12570 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
12571}
12572#endif
12573
[email protected]7461a402011-03-24 23:19:5112574} // namespace net