blob: 9347ebbe0f7a25b465e0a9c11cc2bc0ffa5a0925 [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"
Mike Westfbd44112019-05-08 18:23:3757#include "net/base/features.h"
Aaron Tagliaboschi028009e2019-03-07 16:28:0658#include "net/base/layered_network_delegate.h"
initial.commit586acc5fe2008-07-26 22:42:5259#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2560#include "net/base/load_timing_info.h"
61#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0662#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5263#include "net/base/net_module.h"
Lily Houghton582d4622018-01-22 22:43:4064#include "net/base/proxy_server.h"
[email protected]2ca01e52013-10-31 22:05:1965#include "net/base/request_priority.h"
zhongyi18ddddd2017-02-03 19:06:3666#include "net/base/test_completion_callback.h"
[email protected]f288ef02012-12-15 20:28:2867#include "net/base/upload_bytes_element_reader.h"
68#include "net/base/upload_data_stream.h"
69#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4470#include "net/base/url_util.h"
Matt Muellera4aaa9d2019-04-24 21:09:1471#include "net/cert/cert_net_fetcher.h"
Ryan Sleevib369d712018-08-20 16:43:2272#include "net/cert/crl_set.h"
rsleevid6de8302016-06-21 01:33:2073#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4774#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3675#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1176#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2477#include "net/cert/mock_cert_verifier.h"
zhongyi18ddddd2017-02-03 19:06:3678#include "net/cert/multi_log_ct_verifier.h"
eranmdcec9632016-10-10 14:16:1079#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1180#include "net/cert/test_root_certs.h"
Matt Muellera4aaa9d2019-04-24 21:09:1481#include "net/cert_net/cert_net_fetcher_impl.h"
[email protected]aa84a7e2012-03-15 21:29:0682#include "net/cookies/cookie_monster.h"
83#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5284#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5385#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3886#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5287#include "net/http/http_cache.h"
88#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1989#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2590#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2191#include "net/http/http_response_headers.h"
zhongyi18ddddd2017-02-03 19:06:3692#include "net/http/http_server_properties_impl.h"
[email protected]e50efea2014-03-24 18:41:0093#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0094#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1995#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5196#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4697#include "net/log/test_net_log_entry.h"
98#include "net/log/test_net_log_util.h"
Scott Violet0caaaf432018-03-24 00:43:5999#include "net/net_buildflags.h"
Lily Houghtonffe89daa02018-03-09 18:30:03100#include "net/proxy_resolution/proxy_resolution_service.h"
Ryan Hamiltona3ee93a72018-08-01 22:03:08101#include "net/quic/mock_crypto_client_stream_factory.h"
102#include "net/quic/quic_server_info.h"
zhongyi18ddddd2017-02-03 19:06:36103#include "net/socket/socket_test_util.h"
[email protected]c3456bb2011-12-12 22:22:19104#include "net/socket/ssl_client_socket.h"
David Benjamin76a40ad2018-02-24 22:22:08105#include "net/ssl/client_cert_identity_test_util.h"
[email protected]536fd0b2013-03-14 17:41:57106#include "net/ssl/ssl_connection_status_flags.h"
David Benjamin76a40ad2018-02-24 22:22:08107#include "net/ssl/ssl_private_key.h"
tommycli59a63432015-11-06 00:10:55108#include "net/ssl/ssl_server_config.h"
[email protected]6e7845ae2013-03-29 21:48:11109#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:36110#include "net/test/embedded_test_server/embedded_test_server.h"
111#include "net/test/embedded_test_server/http_request.h"
112#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:01113#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21114#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43115#include "net/test/test_data_directory.h"
Bence Béky98447b12018-05-08 03:14:01116#include "net/test/test_with_scoped_task_environment.h"
mmenkefb18c772015-09-30 22:22:50117#include "net/test/url_request/url_request_failed_job.h"
Carlos ILaef65d62018-06-04 21:24:13118#include "net/test/url_request/url_request_mock_http_job.h"
rhalavatib7bd7c792017-04-27 05:25:16119#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34120#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43121#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52122#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50123#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14124#include "net/url_request/url_request_http_job.h"
Thiemo Nagel0793b9c532018-04-18 16:57:58125#include "net/url_request/url_request_http_job_histogram.h"
bengr1bf8e942014-11-07 01:36:50126#include "net/url_request/url_request_intercepting_job_factory.h"
127#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49128#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51129#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47130#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44131#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01132#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52133#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15134#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52135
Eric Romanefddd0a2017-10-10 02:14:25136#if defined(OS_FUCHSIA)
137#define USE_BUILTIN_CERT_VERIFIER
138#endif
139
brettwa1228ebb2016-10-28 03:51:34140#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55141#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29142#include "net/url_request/file_protocol_handler.h"
143#include "net/url_request/url_request_file_dir_job.h"
144#endif
145
brettwa1228ebb2016-10-28 03:51:34146#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47147#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29148#include "net/url_request/ftp_protocol_handler.h"
149#endif
150
[email protected]dffe8242012-03-20 15:14:27151#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48152#include "base/win/scoped_com_initializer.h"
[email protected]dffe8242012-03-20 15:14:27153#endif
154
Matt Mueller7f60dc42019-04-26 22:47:10155#if defined(OS_MACOSX)
156#include "base/mac/mac_util.h"
157#endif
158
mmenkefd9d15c2017-06-29 13:45:54159#if BUILDFLAG(ENABLE_REPORTING)
Julia Tuttlecba7d222018-02-23 19:37:27160#include "net/network_error_logging/network_error_logging_service.h"
Lily Chenfec60d92019-01-24 01:16:42161#include "net/network_error_logging/network_error_logging_test_util.h"
mmenkefd9d15c2017-06-29 13:45:54162#endif // BUILDFLAG(ENABLE_REPORTING)
163
Eric Romanefddd0a2017-10-10 02:14:25164#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,
Emily Stark79fba5842019-04-25 04:59:36794 int net_error,
dadrian612337a2016-07-20 22:36:58795 const SSLInfo& ssl_info,
796 bool fatal) override {
797 ssl_info_ = ssl_info;
798 on_ssl_certificate_error_called_ = true;
Emily Stark79fba5842019-04-25 04:59:36799 TestDelegate::OnSSLCertificateError(request, net_error, ssl_info, fatal);
dadrian612337a2016-07-20 22:36:58800 }
801
802 bool on_ssl_certificate_error_called() {
803 return on_ssl_certificate_error_called_;
804 }
805
806 SSLInfo ssl_info() { return ssl_info_; }
807
808 private:
809 bool on_ssl_certificate_error_called_ = false;
810 SSLInfo ssl_info_;
811};
812
[email protected]d5a4dd62012-05-23 01:41:04813} // namespace
814
[email protected]a592c0432012-12-01 18:10:29815// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
Bence Béky98447b12018-05-08 03:14:01816class URLRequestTest : public PlatformTest, public WithScopedTaskEnvironment {
[email protected]abb26092010-11-11 22:19:00817 public:
Ryan Sleevib8449e02018-07-15 04:31:07818 URLRequestTest()
819 : default_context_(std::make_unique<TestURLRequestContext>(true)) {
820 default_context_->set_network_delegate(&default_network_delegate_);
821 default_context_->set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50822 job_factory_impl_ = new URLRequestJobFactoryImpl();
823 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50824 }
bengr1bf8e942014-11-07 01:36:50825
dcheng67be2b1f2014-10-27 21:47:29826 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18827 // URLRequestJobs may post clean-up tasks on destruction.
828 base::RunLoop().RunUntilIdle();
Martijn Croonenb1383da2017-10-11 11:56:35829
830 SetTransportSecurityStateSourceForTesting(nullptr);
[email protected]e4034ad2013-09-20 08:36:18831 }
[email protected]87a09a92011-07-14 15:50:50832
dcheng2339883c2014-12-23 00:23:05833 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50834 SetUpFactory();
Ryan Sleevib8449e02018-07-15 04:31:07835 default_context_->set_job_factory(job_factory_.get());
836 default_context_->Init();
bengr1bf8e942014-11-07 01:36:50837 PlatformTest::SetUp();
838 }
839
Ryan Sleevib8449e02018-07-15 04:31:07840 void TearDown() override { default_context_.reset(); }
841
bengr1bf8e942014-11-07 01:36:50842 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20843 job_factory_impl_->SetProtocolHandler(
Bence Béky8f9d7d3952017-10-09 19:58:04844 "data", std::make_unique<DataProtocolHandler>());
brettwa1228ebb2016-10-28 03:51:34845#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50846 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19847 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07848 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50849#endif
850 }
851
852 TestNetworkDelegate* default_network_delegate() {
853 return &default_network_delegate_;
854 }
855
Ryan Sleevib8449e02018-07-15 04:31:07856 TestURLRequestContext& default_context() const { return *default_context_; }
bengr1bf8e942014-11-07 01:36:50857
[email protected]3c5ca8c2011-09-29 01:14:51858 // Adds the TestJobInterceptor to the default context.
859 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23860 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20861 job_factory_impl_->SetProtocolHandler("http", nullptr);
862 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36863 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23864 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51865 }
866
Sergey Ulanov2e49f492017-09-14 19:37:51867 // Creates a temp test file and writes |data| to the file. The file will be
868 // deleted after the test completes.
869 void CreateTestFile(const char* data,
870 size_t data_size,
871 base::FilePath* test_file) {
872 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
873 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
874 // now, Mac and Android bots return a path with a symbolic link.
875 base::FilePath absolute_temp_dir =
876 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
877
878 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
879 ASSERT_EQ(static_cast<int>(data_size),
880 base::WriteFile(*test_file, data, data_size));
881 }
882
[email protected]87a09a92011-07-14 15:50:50883 protected:
vishal.b62985ca92015-04-17 08:45:51884 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24885 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50886 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36887 std::unique_ptr<URLRequestJobFactory> job_factory_;
Ryan Sleevib8449e02018-07-15 04:31:07888 std::unique_ptr<TestURLRequestContext> default_context_;
Sergey Ulanov2e49f492017-09-14 19:37:51889 base::ScopedTempDir temp_dir_;
[email protected]7a0bb4bf2008-11-19 21:41:48890};
891
satoruxddac0442017-05-29 06:06:18892// This NetworkDelegate is picky about what files are accessible. Only
893// whitelisted files are allowed.
894class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
895 public:
Chris Watkins7a41d3552017-12-01 02:13:27896 CookieBlockingNetworkDelegate() = default;
satoruxddac0442017-05-29 06:06:18897
898 // Adds |directory| to the access white list.
899 void AddToWhitelist(const base::FilePath& directory) {
900 whitelist_.insert(directory);
901 }
902
903 private:
904 // Returns true if |path| matches the white list.
905 bool OnCanAccessFileInternal(const base::FilePath& path) const {
906 for (const auto& directory : whitelist_) {
907 if (directory == path || directory.IsParent(path))
908 return true;
909 }
910 return false;
911 }
912
913 // Returns true only if both |original_path| and |absolute_path| match the
914 // white list.
915 bool OnCanAccessFile(const URLRequest& request,
916 const base::FilePath& original_path,
917 const base::FilePath& absolute_path) const override {
918 return (OnCanAccessFileInternal(original_path) &&
919 OnCanAccessFileInternal(absolute_path));
920 }
921
922 std::set<base::FilePath> whitelist_;
923
924 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
925};
926
[email protected]316c1e5e2012-09-12 15:17:44927TEST_F(URLRequestTest, AboutBlankTest) {
928 TestDelegate d;
929 {
rhalavatib7bd7c792017-04-27 05:25:16930 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:07931 default_context().CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
932 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44933
[email protected]f7022f32014-08-21 16:32:19934 r->Start();
935 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44936
Wez2a31b222018-06-07 22:07:15937 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44938
[email protected]f7022f32014-08-21 16:32:19939 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44940 EXPECT_FALSE(d.received_data_before_response());
941 EXPECT_EQ(d.bytes_received(), 0);
Tsuyoshi Horo01faed62019-02-20 22:11:37942 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
943 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04944
945 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19946 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44947 }
948}
949
950TEST_F(URLRequestTest, DataURLImageTest) {
951 TestDelegate d;
952 {
953 // Use our nice little Chrome logo.
Ryan Sleevib8449e02018-07-15 04:31:07954 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
danakj8522a25b2016-04-16 00:17:36955 GURL("data:image/png;base64,"
956 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
957 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
958 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
959 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
960 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
961 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
962 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
963 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
964 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
965 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
966 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
967 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
968 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
969 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
970 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
971 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
972 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
973 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
974 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16975 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44976
[email protected]f7022f32014-08-21 16:32:19977 r->Start();
978 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44979
Wez2a31b222018-06-07 22:07:15980 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44981
[email protected]f7022f32014-08-21 16:32:19982 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44983 EXPECT_FALSE(d.received_data_before_response());
984 EXPECT_EQ(d.bytes_received(), 911);
Tsuyoshi Horo01faed62019-02-20 22:11:37985 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
986 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04987
988 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19989 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44990 }
991}
992
brettwa1228ebb2016-10-28 03:51:34993#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44994TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51995 const char kTestFileContent[] = "Hello";
996 base::FilePath test_file;
997 ASSERT_NO_FATAL_FAILURE(
998 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04999
Sergey Ulanov2e49f492017-09-14 19:37:511000 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441001
1002 TestDelegate d;
1003 {
Ryan Sleevib8449e02018-07-15 04:31:071004 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511005 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441006
[email protected]f7022f32014-08-21 16:32:191007 r->Start();
1008 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441009
Wez2a31b222018-06-07 22:07:151010 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441011
[email protected]f7022f32014-08-21 16:32:191012 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441013 EXPECT_EQ(1, d.response_started_count());
1014 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:511015 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
Tsuyoshi Horo01faed62019-02-20 22:11:371016 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
1017 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:041018
1019 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:191020 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:441021 }
1022}
1023
[email protected]ba40bb762012-12-17 07:11:041024TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:511025 const char kTestFileContent[] = "Hello";
1026 base::FilePath test_file;
1027 ASSERT_NO_FATAL_FAILURE(
1028 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
1029
1030 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:041031
1032 TestDelegate d;
1033 {
Ryan Sleevib8449e02018-07-15 04:31:071034 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511035 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:041036
[email protected]f7022f32014-08-21 16:32:191037 r->Start();
1038 EXPECT_TRUE(r->is_pending());
1039 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:041040 }
[email protected]79e1fd62013-06-20 06:50:041041 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:041042 // destroyed.
[email protected]255620da2013-08-19 13:14:291043 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041044}
1045
[email protected]316c1e5e2012-09-12 15:17:441046TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1047 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361048 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441049 FillBuffer(buffer.get(), buffer_size);
1050
Sergey Ulanov2e49f492017-09-14 19:37:511051 base::FilePath test_file;
1052 ASSERT_NO_FATAL_FAILURE(
1053 CreateTestFile(buffer.get(), buffer_size, &test_file));
1054 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441055
1056 const size_t first_byte_position = 500;
1057 const size_t last_byte_position = buffer_size - first_byte_position;
1058 const size_t content_length = last_byte_position - first_byte_position + 1;
1059 std::string partial_buffer_string(buffer.get() + first_byte_position,
1060 buffer.get() + last_byte_position + 1);
1061
1062 TestDelegate d;
1063 {
Ryan Sleevib8449e02018-07-15 04:31:071064 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161065 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441066
1067 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381068 headers.SetHeader(
1069 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591070 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381071 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191072 r->SetExtraRequestHeaders(headers);
1073 r->Start();
1074 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441075
Wez2a31b222018-06-07 22:07:151076 d.RunUntilComplete();
1077
[email protected]f7022f32014-08-21 16:32:191078 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441079 EXPECT_EQ(1, d.response_started_count());
1080 EXPECT_FALSE(d.received_data_before_response());
1081 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1082 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1083 EXPECT_TRUE(partial_buffer_string == d.data_received());
1084 }
[email protected]316c1e5e2012-09-12 15:17:441085}
1086
1087TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1088 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361089 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441090 FillBuffer(buffer.get(), buffer_size);
1091
Sergey Ulanov2e49f492017-09-14 19:37:511092 base::FilePath test_file;
1093 ASSERT_NO_FATAL_FAILURE(
1094 CreateTestFile(buffer.get(), buffer_size, &test_file));
1095 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441096
1097 const size_t first_byte_position = 500;
1098 const size_t last_byte_position = buffer_size - 1;
1099 const size_t content_length = last_byte_position - first_byte_position + 1;
1100 std::string partial_buffer_string(buffer.get() + first_byte_position,
1101 buffer.get() + last_byte_position + 1);
1102
1103 TestDelegate d;
1104 {
Ryan Sleevib8449e02018-07-15 04:31:071105 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161106 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441107
1108 HttpRequestHeaders headers;
1109 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591110 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381111 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191112 r->SetExtraRequestHeaders(headers);
1113 r->Start();
1114 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441115
[email protected]255620da2013-08-19 13:14:291116 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191117 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441118 EXPECT_EQ(1, d.response_started_count());
1119 EXPECT_FALSE(d.received_data_before_response());
1120 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1121 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1122 EXPECT_TRUE(partial_buffer_string == d.data_received());
1123 }
[email protected]316c1e5e2012-09-12 15:17:441124}
1125
1126TEST_F(URLRequestTest, FileTestMultipleRanges) {
1127 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361128 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441129 FillBuffer(buffer.get(), buffer_size);
1130
Sergey Ulanov2e49f492017-09-14 19:37:511131 base::FilePath test_file;
1132 ASSERT_NO_FATAL_FAILURE(
1133 CreateTestFile(buffer.get(), buffer_size, &test_file));
1134 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441135
1136 TestDelegate d;
1137 {
Ryan Sleevib8449e02018-07-15 04:31:071138 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161139 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441140
1141 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381142 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191143 r->SetExtraRequestHeaders(headers);
1144 r->Start();
1145 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441146
Wez2a31b222018-06-07 22:07:151147 d.RunUntilComplete();
1148
[email protected]316c1e5e2012-09-12 15:17:441149 EXPECT_TRUE(d.request_failed());
1150 }
[email protected]316c1e5e2012-09-12 15:17:441151}
1152
[email protected]3ca8b362013-11-11 22:18:071153TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511154 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071155 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511156 ASSERT_NO_FATAL_FAILURE(
1157 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1158
satoruxddac0442017-05-29 06:06:181159 // The directory part of the path returned from CreateTemporaryFileInDir()
1160 // can be slightly different from |absolute_temp_dir| on Windows.
1161 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1162 // Hence the test should use the directory name of |test_file|, rather than
1163 // |absolute_temp_dir|, for whitelisting.
1164 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591165 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071166 {
1167 TestDelegate d;
satoruxddac0442017-05-29 06:06:181168 CookieBlockingNetworkDelegate network_delegate;
1169 network_delegate.AddToWhitelist(real_temp_dir);
Ryan Sleevib8449e02018-07-15 04:31:071170 default_context().set_network_delegate(&network_delegate);
1171 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161172 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191173 r->Start();
Wez2a31b222018-06-07 22:07:151174 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181175 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071176 EXPECT_FALSE(d.request_failed());
1177 EXPECT_EQ(test_data, d.data_received());
1178 }
1179
1180 {
1181 TestDelegate d;
satoruxddac0442017-05-29 06:06:181182 CookieBlockingNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:071183 default_context().set_network_delegate(&network_delegate);
1184 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161185 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191186 r->Start();
Wez2a31b222018-06-07 22:07:151187 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181188 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071189 EXPECT_TRUE(d.request_failed());
1190 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181191 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071192 }
1193}
1194
Wez35539132018-07-17 11:26:051195#if defined(OS_POSIX) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181196
1197TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511198 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181199 // Get an absolute path since temp_dir can contain a symbolic link.
1200 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511201 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181202
1203 // Create a good directory (will be whitelisted) and a good file.
1204 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1205 ASSERT_TRUE(base::CreateDirectory(good_dir));
1206 base::FilePath good_file;
1207 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1208 std::string good_data("good");
1209 base::WriteFile(good_file, good_data.data(), good_data.size());
1210 // See the comment in AllowFileURLs() for why this is done.
1211 base::FilePath real_good_dir = good_file.DirName();
1212
1213 // Create a bad directory (will not be whitelisted) and a bad file.
1214 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1215 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1216 base::FilePath bad_file;
1217 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1218 std::string bad_data("bad");
1219 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1220
1221 // This symlink will point to the good file. Access to the symlink will be
1222 // allowed as both the symlink and the destination file are in the same
1223 // good directory.
1224 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1225 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1226 GURL good_file_url = FilePathToFileURL(good_symlink);
1227 // This symlink will point to the bad file. Even though the symlink is in
1228 // the good directory, access to the symlink will be rejected since it
1229 // points to the bad file.
1230 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1231 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1232 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1233
1234 CookieBlockingNetworkDelegate network_delegate;
1235 network_delegate.AddToWhitelist(real_good_dir);
1236 {
1237 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071238 default_context().set_network_delegate(&network_delegate);
1239 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371240 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181241 r->Start();
Wez2a31b222018-06-07 22:07:151242 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181243 // good_file_url should be allowed.
1244 EXPECT_FALSE(d.request_failed());
1245 EXPECT_EQ(good_data, d.data_received());
1246 }
1247
1248 {
1249 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071250 default_context().set_network_delegate(&network_delegate);
1251 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371252 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181253 r->Start();
Wez2a31b222018-06-07 22:07:151254 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181255 // bad_file_url should be rejected.
1256 EXPECT_TRUE(d.request_failed());
1257 EXPECT_EQ("", d.data_received());
1258 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1259 }
1260}
1261
1262TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511263 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181264 // Get an absolute path since temp_dir can contain a symbolic link.
1265 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511266 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181267
1268 // Create a good directory (will be whitelisted).
1269 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1270 ASSERT_TRUE(base::CreateDirectory(good_dir));
1271
1272 // Create a bad directory (will not be whitelisted).
1273 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1274 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1275
1276 // This symlink will point to the good directory. Access to the symlink
1277 // will be allowed as the symlink is in the good dir that'll be white
1278 // listed.
1279 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1280 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1281 GURL good_file_url = FilePathToFileURL(good_symlink);
1282 // This symlink will point to the bad directory. Even though the symlink is
1283 // in the good directory, access to the symlink will be rejected since it
1284 // points to the bad directory.
1285 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1286 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1287 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1288
1289 CookieBlockingNetworkDelegate network_delegate;
1290 network_delegate.AddToWhitelist(good_dir);
1291 {
1292 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071293 default_context().set_network_delegate(&network_delegate);
1294 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371295 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181296 r->Start();
Wez2a31b222018-06-07 22:07:151297 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181298 // good_file_url should be allowed.
1299 EXPECT_FALSE(d.request_failed());
1300 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1301 }
1302
1303 {
1304 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071305 default_context().set_network_delegate(&network_delegate);
1306 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371307 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181308 r->Start();
Wez2a31b222018-06-07 22:07:151309 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181310 // bad_file_url should be rejected.
1311 EXPECT_TRUE(d.request_failed());
1312 EXPECT_EQ("", d.data_received());
1313 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1314 }
1315}
1316
Wez35539132018-07-17 11:26:051317#endif // defined(OS_POSIX)
[email protected]316c1e5e2012-09-12 15:17:441318
1319TEST_F(URLRequestTest, FileDirCancelTest) {
1320 // Put in mock resource provider.
1321 NetModule::SetResourceProvider(TestNetResourceProvider);
1322
1323 TestDelegate d;
1324 {
[email protected]6cdfd7f2013-02-08 20:40:151325 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:191326 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
[email protected]316c1e5e2012-09-12 15:17:441327 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1328 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1329
Ryan Sleevib8449e02018-07-15 04:31:071330 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161331 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1332 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191333 req->Start();
1334 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441335
1336 d.set_cancel_in_received_data_pending(true);
1337
Wez2a31b222018-06-07 22:07:151338 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441339 }
1340
1341 // Take out mock resource provider.
Raul Tambre94493c652019-03-11 17:18:351342 NetModule::SetResourceProvider(nullptr);
[email protected]316c1e5e2012-09-12 15:17:441343}
1344
[email protected]5f9581402013-10-30 13:08:321345TEST_F(URLRequestTest, FileDirOutputSanity) {
1346 // Verify the general sanity of the the output of the file:
1347 // directory lister by checking for the output of a known existing
1348 // file.
1349 const char sentinel_name[] = "filedir-sentinel";
1350
1351 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191352 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471353 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321354
1355 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161356 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071357 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1358 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191359 req->Start();
Wez2a31b222018-06-07 22:07:151360 d.RunUntilComplete();
[email protected]5f9581402013-10-30 13:08:321361
1362 // Generate entry for the sentinel file.
1363 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581364 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491365 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321366 EXPECT_GT(info.size, 0);
1367 std::string sentinel_output = GetDirectoryListingEntry(
1368 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181369 std::string(sentinel_name), false /* is_dir */, info.size,
1370
[email protected]5f9581402013-10-30 13:08:321371 info.last_modified);
1372
1373 ASSERT_LT(0, d.bytes_received());
1374 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501375 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321376 // Check for the entry generated for the "sentinel" file.
1377 const std::string& data = d.data_received();
1378 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1379}
1380
[email protected]316c1e5e2012-09-12 15:17:441381TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1382 // There is an implicit redirect when loading a file path that matches a
1383 // directory and does not end with a slash. Ensure that following such
1384 // redirects does not crash. See http://crbug.com/18686.
1385
[email protected]6cdfd7f2013-02-08 20:40:151386 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191387 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471388 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441389
1390 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161391 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071392 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1393 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191394 req->Start();
Wez2a31b222018-06-07 22:07:151395 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441396
1397 ASSERT_EQ(1, d.received_redirect_count());
1398 ASSERT_LT(0, d.bytes_received());
1399 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501400 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441401}
1402
1403#if defined(OS_WIN)
1404// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1405TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1406 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071407 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161408 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191409 req->Start();
Wez2a31b222018-06-07 22:07:151410 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441411
1412 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501413 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441414}
[email protected]5ecf7cb282014-05-11 01:49:551415#endif // defined(OS_WIN)
1416
brettwa1228ebb2016-10-28 03:51:341417#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551418
1419TEST_F(URLRequestTest, InvalidUrlTest) {
1420 TestDelegate d;
1421 {
rhalavatib7bd7c792017-04-27 05:25:161422 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:071423 default_context().CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1424 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551425
[email protected]f7022f32014-08-21 16:32:191426 r->Start();
1427 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551428
Wez2a31b222018-06-07 22:07:151429 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551430 EXPECT_TRUE(d.request_failed());
1431 }
1432}
1433
jochen0e3b3a62014-09-16 18:31:231434TEST_F(URLRequestTest, InvalidReferrerTest) {
1435 TestURLRequestContext context;
1436 TestNetworkDelegate network_delegate;
1437 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1438 context.set_network_delegate(&network_delegate);
1439 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361440 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161441 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1442 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231443 req->SetReferrer("https://somewhere.com/");
1444
1445 req->Start();
Wez2a31b222018-06-07 22:07:151446 d.RunUntilComplete();
jochen0e3b3a62014-09-16 18:31:231447 EXPECT_TRUE(d.request_failed());
1448}
1449
[email protected]5ecf7cb282014-05-11 01:49:551450#if defined(OS_WIN)
1451TEST_F(URLRequestTest, ResolveShortcutTest) {
1452 base::FilePath app_path;
Avi Drissman5c80d832018-05-01 17:01:191453 base::PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471454 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551455 app_path = app_path.AppendASCII("with-headers.html");
1456
jdoerrie6312bf62019-02-01 22:03:421457 base::string16 lnk_path = app_path.value() + FILE_PATH_LITERAL(".lnk");
[email protected]5ecf7cb282014-05-11 01:49:551458
1459 base::win::ScopedCOMInitializer com_initializer;
1460
1461 // Temporarily create a shortcut for test
1462 {
Robert Liaoc88f99d12017-10-17 21:48:331463 Microsoft::WRL::ComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161464 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
Raul Tambre94493c652019-03-11 17:18:351465 CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
Robert Liaoc88f99d12017-10-17 21:48:331466 Microsoft::WRL::ComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001467 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
jdoerriebacc1962019-02-07 13:39:221468 EXPECT_TRUE(SUCCEEDED(shell->SetPath(base::as_wcstr(app_path.value()))));
[email protected]5ecf7cb282014-05-11 01:49:551469 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
jdoerriebacc1962019-02-07 13:39:221470 EXPECT_TRUE(SUCCEEDED(persist->Save(base::as_wcstr(lnk_path), TRUE)));
[email protected]5ecf7cb282014-05-11 01:49:551471 }
1472
1473 TestDelegate d;
1474 {
Ryan Sleevib8449e02018-07-15 04:31:071475 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161476 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1477 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551478
[email protected]f7022f32014-08-21 16:32:191479 r->Start();
1480 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551481
Wez2a31b222018-06-07 22:07:151482 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551483
1484 WIN32_FILE_ATTRIBUTE_DATA data;
jdoerriebacc1962019-02-07 13:39:221485 GetFileAttributesEx(base::as_wcstr(app_path.value()), GetFileExInfoStandard,
jdoerrie6312bf62019-02-01 22:03:421486 &data);
jdoerriebacc1962019-02-07 13:39:221487 HANDLE file = CreateFile(base::as_wcstr(app_path.value()), GENERIC_READ,
Raul Tambre94493c652019-03-11 17:18:351488 FILE_SHARE_READ, nullptr, OPEN_EXISTING,
1489 FILE_ATTRIBUTE_NORMAL, nullptr);
[email protected]5ecf7cb282014-05-11 01:49:551490 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361491 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551492 DWORD read_size;
1493 BOOL result;
Raul Tambre94493c652019-03-11 17:18:351494 result =
1495 ReadFile(file, buffer.get(), data.nFileSizeLow, &read_size, nullptr);
[email protected]5ecf7cb282014-05-11 01:49:551496 std::string content(buffer.get(), read_size);
1497 CloseHandle(file);
1498
[email protected]f7022f32014-08-21 16:32:191499 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551500 EXPECT_EQ(1, d.received_redirect_count());
1501 EXPECT_EQ(content, d.data_received());
1502 }
1503
1504 // Clean the shortcut
jdoerriebacc1962019-02-07 13:39:221505 DeleteFile(base::as_wcstr(lnk_path));
[email protected]5ecf7cb282014-05-11 01:49:551506}
1507#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441508
1509// Custom URLRequestJobs for use with interceptor tests
1510class RestartTestJob : public URLRequestTestJob {
1511 public:
1512 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1513 : URLRequestTestJob(request, network_delegate, true) {}
1514 protected:
dchengb03027d2014-10-21 12:00:201515 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441516 private:
Chris Watkins7a41d3552017-12-01 02:13:271517 ~RestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441518};
1519
1520class CancelTestJob : public URLRequestTestJob {
1521 public:
1522 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1523 : URLRequestTestJob(request, network_delegate, true) {}
1524 protected:
dchengb03027d2014-10-21 12:00:201525 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441526 private:
Chris Watkins7a41d3552017-12-01 02:13:271527 ~CancelTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441528};
1529
1530class CancelThenRestartTestJob : public URLRequestTestJob {
1531 public:
1532 explicit CancelThenRestartTestJob(URLRequest* request,
1533 NetworkDelegate* network_delegate)
1534 : URLRequestTestJob(request, network_delegate, true) {
1535 }
1536 protected:
dchengb03027d2014-10-21 12:00:201537 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441538 request_->Cancel();
1539 this->NotifyRestartRequired();
1540 }
1541 private:
Chris Watkins7a41d3552017-12-01 02:13:271542 ~CancelThenRestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441543};
1544
bengr1bf8e942014-11-07 01:36:501545// An Interceptor for use with interceptor tests.
1546class MockURLRequestInterceptor : public URLRequestInterceptor {
1547 public:
1548 // Static getters for canned response header and data strings.
1549 static std::string ok_data() {
1550 return URLRequestTestJob::test_data_1();
1551 }
1552
1553 static std::string ok_headers() {
1554 return URLRequestTestJob::test_headers();
1555 }
1556
1557 static std::string redirect_data() {
1558 return std::string();
1559 }
1560
1561 static std::string redirect_headers() {
1562 return URLRequestTestJob::test_redirect_headers();
1563 }
1564
1565 static std::string error_data() {
1566 return std::string("ohhh nooooo mr. bill!");
1567 }
1568
1569 static std::string error_headers() {
1570 return URLRequestTestJob::test_error_headers();
1571 }
1572
1573 MockURLRequestInterceptor()
1574 : intercept_main_request_(false), restart_main_request_(false),
1575 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1576 simulate_main_network_error_(false),
1577 intercept_redirect_(false), cancel_redirect_request_(false),
1578 intercept_final_response_(false), cancel_final_request_(false),
1579 use_url_request_http_job_(false),
1580 did_intercept_main_(false), did_restart_main_(false),
1581 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1582 did_simulate_error_main_(false),
1583 did_intercept_redirect_(false), did_cancel_redirect_(false),
1584 did_intercept_final_(false), did_cancel_final_(false) {
1585 }
1586
Chris Watkins7a41d3552017-12-01 02:13:271587 ~MockURLRequestInterceptor() override = default;
bengr1bf8e942014-11-07 01:36:501588
1589 // URLRequestInterceptor implementation:
1590 URLRequestJob* MaybeInterceptRequest(
1591 URLRequest* request,
1592 NetworkDelegate* network_delegate) const override {
1593 if (restart_main_request_) {
1594 restart_main_request_ = false;
1595 did_restart_main_ = true;
1596 return new RestartTestJob(request, network_delegate);
1597 }
1598 if (cancel_main_request_) {
1599 cancel_main_request_ = false;
1600 did_cancel_main_ = true;
1601 return new CancelTestJob(request, network_delegate);
1602 }
1603 if (cancel_then_restart_main_request_) {
1604 cancel_then_restart_main_request_ = false;
1605 did_cancel_then_restart_main_ = true;
1606 return new CancelThenRestartTestJob(request, network_delegate);
1607 }
1608 if (simulate_main_network_error_) {
1609 simulate_main_network_error_ = false;
1610 did_simulate_error_main_ = true;
1611 if (use_url_request_http_job_) {
1612 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1613 }
1614 // This job will result in error since the requested URL is not one of the
1615 // URLs supported by these tests.
1616 return new URLRequestTestJob(request, network_delegate, true);
1617 }
1618 if (!intercept_main_request_)
1619 return nullptr;
1620 intercept_main_request_ = false;
1621 did_intercept_main_ = true;
1622 URLRequestTestJob* job = new URLRequestTestJob(request,
1623 network_delegate,
1624 main_headers_,
1625 main_data_,
1626 true);
1627 job->set_load_timing_info(main_request_load_timing_info_);
1628 return job;
1629 }
1630
1631 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1632 NetworkDelegate* network_delegate,
1633 const GURL& location) const override {
1634 if (cancel_redirect_request_) {
1635 cancel_redirect_request_ = false;
1636 did_cancel_redirect_ = true;
1637 return new CancelTestJob(request, network_delegate);
1638 }
1639 if (!intercept_redirect_)
1640 return nullptr;
1641 intercept_redirect_ = false;
1642 did_intercept_redirect_ = true;
1643 if (use_url_request_http_job_) {
1644 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1645 }
1646 return new URLRequestTestJob(request,
1647 network_delegate,
1648 redirect_headers_,
1649 redirect_data_,
1650 true);
1651 }
1652
1653 URLRequestJob* MaybeInterceptResponse(
1654 URLRequest* request,
1655 NetworkDelegate* network_delegate) const override {
1656 if (cancel_final_request_) {
1657 cancel_final_request_ = false;
1658 did_cancel_final_ = true;
1659 return new CancelTestJob(request, network_delegate);
1660 }
1661 if (!intercept_final_response_)
1662 return nullptr;
1663 intercept_final_response_ = false;
1664 did_intercept_final_ = true;
1665 if (use_url_request_http_job_) {
1666 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1667 }
1668 return new URLRequestTestJob(request,
1669 network_delegate,
1670 final_headers_,
1671 final_data_,
1672 true);
1673 }
1674
1675 void set_intercept_main_request(bool intercept_main_request) {
1676 intercept_main_request_ = intercept_main_request;
1677 }
1678
1679 void set_main_headers(const std::string& main_headers) {
1680 main_headers_ = main_headers;
1681 }
1682
1683 void set_main_data(const std::string& main_data) {
1684 main_data_ = main_data;
1685 }
1686
1687 void set_main_request_load_timing_info(
1688 const LoadTimingInfo& main_request_load_timing_info) {
1689 main_request_load_timing_info_ = main_request_load_timing_info;
1690 }
1691
1692 void set_restart_main_request(bool restart_main_request) {
1693 restart_main_request_ = restart_main_request;
1694 }
1695
1696 void set_cancel_main_request(bool cancel_main_request) {
1697 cancel_main_request_ = cancel_main_request;
1698 }
1699
1700 void set_cancel_then_restart_main_request(
1701 bool cancel_then_restart_main_request) {
1702 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1703 }
1704
1705 void set_simulate_main_network_error(bool simulate_main_network_error) {
1706 simulate_main_network_error_ = simulate_main_network_error;
1707 }
1708
1709 void set_intercept_redirect(bool intercept_redirect) {
1710 intercept_redirect_ = intercept_redirect;
1711 }
1712
1713 void set_redirect_headers(const std::string& redirect_headers) {
1714 redirect_headers_ = redirect_headers;
1715 }
1716
1717 void set_redirect_data(const std::string& redirect_data) {
1718 redirect_data_ = redirect_data;
1719 }
1720
1721 void set_cancel_redirect_request(bool cancel_redirect_request) {
1722 cancel_redirect_request_ = cancel_redirect_request;
1723 }
1724
1725 void set_intercept_final_response(bool intercept_final_response) {
1726 intercept_final_response_ = intercept_final_response;
1727 }
1728
1729 void set_final_headers(const std::string& final_headers) {
1730 final_headers_ = final_headers;
1731 }
1732
1733 void set_final_data(const std::string& final_data) {
1734 final_data_ = final_data;
1735 }
1736
1737 void set_cancel_final_request(bool cancel_final_request) {
1738 cancel_final_request_ = cancel_final_request;
1739 }
1740
1741 void set_use_url_request_http_job(bool use_url_request_http_job) {
1742 use_url_request_http_job_ = use_url_request_http_job;
1743 }
1744
1745 bool did_intercept_main() const {
1746 return did_intercept_main_;
1747 }
1748
1749 bool did_restart_main() const {
1750 return did_restart_main_;
1751 }
1752
1753 bool did_cancel_main() const {
1754 return did_cancel_main_;
1755 }
1756
1757 bool did_cancel_then_restart_main() const {
1758 return did_cancel_then_restart_main_;
1759 }
1760
1761 bool did_simulate_error_main() const {
1762 return did_simulate_error_main_;
1763 }
1764
1765 bool did_intercept_redirect() const {
1766 return did_intercept_redirect_;
1767 }
1768
1769 bool did_cancel_redirect() const {
1770 return did_cancel_redirect_;
1771 }
1772
1773 bool did_intercept_final() const {
1774 return did_intercept_final_;
1775 }
1776
1777 bool did_cancel_final() const {
1778 return did_cancel_final_;
1779 }
1780
1781 private:
1782 // Indicate whether to intercept the main request, and if so specify the
1783 // response to return and the LoadTimingInfo to use.
1784 mutable bool intercept_main_request_;
1785 mutable std::string main_headers_;
1786 mutable std::string main_data_;
1787 mutable LoadTimingInfo main_request_load_timing_info_;
1788
1789 // These indicate actions that can be taken within MaybeInterceptRequest.
1790 mutable bool restart_main_request_;
1791 mutable bool cancel_main_request_;
1792 mutable bool cancel_then_restart_main_request_;
1793 mutable bool simulate_main_network_error_;
1794
1795 // Indicate whether to intercept redirects, and if so specify the response to
1796 // return.
1797 mutable bool intercept_redirect_;
1798 mutable std::string redirect_headers_;
1799 mutable std::string redirect_data_;
1800
1801 // Cancel the request within MaybeInterceptRedirect.
1802 mutable bool cancel_redirect_request_;
1803
1804 // Indicate whether to intercept the final response, and if so specify the
1805 // response to return.
1806 mutable bool intercept_final_response_;
1807 mutable std::string final_headers_;
1808 mutable std::string final_data_;
1809
1810 // Cancel the final request within MaybeInterceptResponse.
1811 mutable bool cancel_final_request_;
1812
1813 // Instruct the interceptor to use a real URLRequestHTTPJob.
1814 mutable bool use_url_request_http_job_;
1815
1816 // These indicate if the interceptor did something or not.
1817 mutable bool did_intercept_main_;
1818 mutable bool did_restart_main_;
1819 mutable bool did_cancel_main_;
1820 mutable bool did_cancel_then_restart_main_;
1821 mutable bool did_simulate_error_main_;
1822 mutable bool did_intercept_redirect_;
1823 mutable bool did_cancel_redirect_;
1824 mutable bool did_intercept_final_;
1825 mutable bool did_cancel_final_;
1826};
1827
1828// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1829class URLRequestInterceptorTest : public URLRequestTest {
1830 public:
Raul Tambre94493c652019-03-11 17:18:351831 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:501832
1833 ~URLRequestInterceptorTest() override {
1834 // URLRequestJobs may post clean-up tasks on destruction.
1835 base::RunLoop().RunUntilIdle();
1836 }
1837
1838 void SetUpFactory() override {
1839 interceptor_ = new MockURLRequestInterceptor();
1840 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361841 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501842 }
1843
1844 MockURLRequestInterceptor* interceptor() const {
1845 return interceptor_;
1846 }
1847
1848 private:
1849 MockURLRequestInterceptor* interceptor_;
1850};
1851
1852TEST_F(URLRequestInterceptorTest, Intercept) {
1853 // Intercept the main request and respond with a simple response.
1854 interceptor()->set_intercept_main_request(true);
1855 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1856 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591857 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361858 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161859 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1860 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501861 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1862 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1863 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091864 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041865 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1866 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501867 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191868 req->Start();
Wez2a31b222018-06-07 22:07:151869 d.RunUntilComplete();
[email protected]2bba3252013-04-08 19:50:591870
bengr1bf8e942014-11-07 01:36:501871 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091872 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501873 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1874 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591875
bengr1bf8e942014-11-07 01:36:501876 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501877 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501878 EXPECT_EQ(200, req->response_headers()->response_code());
1879 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1880 EXPECT_EQ(1, d.response_started_count());
1881 EXPECT_EQ(0, d.received_redirect_count());
1882}
[email protected]2bba3252013-04-08 19:50:591883
bengr1bf8e942014-11-07 01:36:501884TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1885 // Intercept the main request and respond with a redirect.
1886 interceptor()->set_intercept_main_request(true);
1887 interceptor()->set_main_headers(
1888 MockURLRequestInterceptor::redirect_headers());
1889 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1890
1891 // Intercept that redirect and respond with a final OK response.
1892 interceptor()->set_intercept_redirect(true);
1893 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1894 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1895
1896 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361897 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161898 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1899 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501900 req->set_method("GET");
1901 req->Start();
Wez2a31b222018-06-07 22:07:151902 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501903
1904 // Check that the interceptor got called as expected.
1905 EXPECT_TRUE(interceptor()->did_intercept_main());
1906 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1907
1908 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501909 int status = d.request_status();
1910 EXPECT_EQ(OK, status);
1911 if (status == OK)
bengr1bf8e942014-11-07 01:36:501912 EXPECT_EQ(200, req->response_headers()->response_code());
1913
1914 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1915 EXPECT_EQ(1, d.response_started_count());
1916 EXPECT_EQ(0, d.received_redirect_count());
1917}
1918
1919TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1920 // Intercept the main request to generate a server error response.
1921 interceptor()->set_intercept_main_request(true);
1922 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1923 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1924
1925 // Intercept that error and respond with an OK response.
1926 interceptor()->set_intercept_final_response(true);
1927 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1928 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1929
1930 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361931 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161932 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1933 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501934 req->set_method("GET");
1935 req->Start();
Wez2a31b222018-06-07 22:07:151936 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501937
1938 // Check that the interceptor got called as expected.
1939 EXPECT_TRUE(interceptor()->did_intercept_main());
1940 EXPECT_TRUE(interceptor()->did_intercept_final());
1941
1942 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501943 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501944 EXPECT_EQ(200, req->response_headers()->response_code());
1945 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1946 EXPECT_EQ(1, d.response_started_count());
1947 EXPECT_EQ(0, d.received_redirect_count());
1948}
1949
1950TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1951 // Intercept the main request to simulate a network error.
1952 interceptor()->set_simulate_main_network_error(true);
1953
1954 // Intercept that error and respond with an OK response.
1955 interceptor()->set_intercept_final_response(true);
1956 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1957 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1958
1959 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361960 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161961 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1962 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501963 req->set_method("GET");
1964 req->Start();
Wez2a31b222018-06-07 22:07:151965 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501966
1967 // Check that the interceptor got called as expected.
1968 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1969 EXPECT_TRUE(interceptor()->did_intercept_final());
1970
1971 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501972 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501973 EXPECT_EQ(200, req->response_headers()->response_code());
1974 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1975 EXPECT_EQ(1, d.response_started_count());
1976 EXPECT_EQ(0, d.received_redirect_count());
1977}
1978
1979TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1980 // Restart the main request.
1981 interceptor()->set_restart_main_request(true);
1982
1983 // then intercept the new main request and respond with an OK response
1984 interceptor()->set_intercept_main_request(true);
1985 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1986 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1987
1988 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361989 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161990 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1991 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501992 req->set_method("GET");
1993 req->Start();
Wez2a31b222018-06-07 22:07:151994 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501995
1996 // Check that the interceptor got called as expected.
1997 EXPECT_TRUE(interceptor()->did_restart_main());
1998 EXPECT_TRUE(interceptor()->did_intercept_main());
1999
2000 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:502001 int status = d.request_status();
2002 EXPECT_EQ(OK, status);
2003 if (status == OK)
bengr1bf8e942014-11-07 01:36:502004 EXPECT_EQ(200, req->response_headers()->response_code());
2005
2006 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2007 EXPECT_EQ(1, d.response_started_count());
2008 EXPECT_EQ(0, d.received_redirect_count());
2009}
2010
2011TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
2012 // Intercept the main request and cancel from within the restarted job.
2013 interceptor()->set_cancel_main_request(true);
2014
2015 // Set up to intercept the final response and override it with an OK response.
2016 interceptor()->set_intercept_final_response(true);
2017 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2018 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2019
2020 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362021 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162022 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2023 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502024 req->set_method("GET");
2025 req->Start();
Wez2a31b222018-06-07 22:07:152026 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502027
2028 // Check that the interceptor got called as expected.
2029 EXPECT_TRUE(interceptor()->did_cancel_main());
2030 EXPECT_FALSE(interceptor()->did_intercept_final());
2031
2032 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502033 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502034}
2035
2036TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2037 // Intercept the main request and respond with a redirect.
2038 interceptor()->set_intercept_main_request(true);
2039 interceptor()->set_main_headers(
2040 MockURLRequestInterceptor::redirect_headers());
2041 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2042
2043 // Intercept the redirect and cancel from within that job.
2044 interceptor()->set_cancel_redirect_request(true);
2045
2046 // Set up to intercept the final response and override it with an OK response.
2047 interceptor()->set_intercept_final_response(true);
2048 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2049 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2050
2051 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362052 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162053 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2054 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502055 req->set_method("GET");
2056 req->Start();
Wez2a31b222018-06-07 22:07:152057 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502058
2059 // Check that the interceptor got called as expected.
2060 EXPECT_TRUE(interceptor()->did_intercept_main());
2061 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2062 EXPECT_FALSE(interceptor()->did_intercept_final());
2063
2064 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502065 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502066}
2067
2068TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2069 // Intercept the main request to simulate a network error.
2070 interceptor()->set_simulate_main_network_error(true);
2071
2072 // Set up to intercept final the response and cancel from within that job.
2073 interceptor()->set_cancel_final_request(true);
2074
2075 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362076 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162077 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2078 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502079 req->set_method("GET");
2080 req->Start();
Wez2a31b222018-06-07 22:07:152081 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502082
2083 // Check that the interceptor got called as expected.
2084 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2085 EXPECT_TRUE(interceptor()->did_cancel_final());
2086
2087 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502088 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502089}
2090
2091TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2092 // Intercept the main request and cancel then restart from within that job.
2093 interceptor()->set_cancel_then_restart_main_request(true);
2094
2095 // Set up to intercept the final response and override it with an OK response.
2096 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502097 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2098 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502099
2100 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362101 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162102 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2103 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502104 req->set_method("GET");
2105 req->Start();
Wez2a31b222018-06-07 22:07:152106 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502107
2108 // Check that the interceptor got called as expected.
2109 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2110 EXPECT_FALSE(interceptor()->did_intercept_final());
2111
2112 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502113 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592114}
2115
2116// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2117// reused. |connect_time_flags| is used to indicate if there should be dns
2118// or SSL times, and |used_proxy| is used for proxy times.
2119LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2120 int connect_time_flags,
2121 bool used_proxy) {
2122 LoadTimingInfo load_timing;
2123 load_timing.socket_log_id = 1;
2124
2125 if (used_proxy) {
2126 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2127 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2128 }
2129
2130 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2131 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2132 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2133 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2134 }
2135 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2136 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2137 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2138 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2139 }
2140 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2141
2142 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2143 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382144 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2145 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592146 return load_timing;
2147}
2148
2149// Same as above, but in the case of a reused socket.
2150LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2151 bool used_proxy) {
2152 LoadTimingInfo load_timing;
2153 load_timing.socket_log_id = 1;
2154 load_timing.socket_reused = true;
2155
2156 if (used_proxy) {
2157 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2158 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2159 }
2160
2161 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2162 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382163 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2164 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592165 return load_timing;
2166}
2167
bengr1bf8e942014-11-07 01:36:502168LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2169 const LoadTimingInfo& job_load_timing,
2170 const URLRequestContext& context,
2171 MockURLRequestInterceptor* interceptor) {
2172 interceptor->set_intercept_main_request(true);
2173 interceptor->set_main_request_load_timing_info(job_load_timing);
2174 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162175 std::unique_ptr<URLRequest> req(
2176 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2177 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502178 req->Start();
Wez2a31b222018-06-07 22:07:152179 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502180
2181 LoadTimingInfo resulting_load_timing;
2182 req->GetLoadTimingInfo(&resulting_load_timing);
2183
2184 // None of these should be modified by the URLRequest.
2185 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2186 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2187 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2188 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382189 EXPECT_EQ(job_load_timing.receive_headers_start,
2190 resulting_load_timing.receive_headers_start);
bengr1bf8e942014-11-07 01:36:502191 EXPECT_EQ(job_load_timing.receive_headers_end,
2192 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572193 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2194 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502195
2196 return resulting_load_timing;
2197}
2198
[email protected]2bba3252013-04-08 19:50:592199// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502200TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592201 base::TimeTicks now = base::TimeTicks::Now();
2202 LoadTimingInfo job_load_timing =
2203 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2204
[email protected]2ca01e52013-10-31 22:05:192205 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502206 RunURLRequestInterceptorLoadTimingTest(
2207 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592208
2209 // Nothing should have been changed by the URLRequest.
2210 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2211 load_timing_result.proxy_resolve_start);
2212 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2213 load_timing_result.proxy_resolve_end);
2214 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2215 load_timing_result.connect_timing.dns_start);
2216 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2217 load_timing_result.connect_timing.dns_end);
2218 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2219 load_timing_result.connect_timing.connect_start);
2220 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2221 load_timing_result.connect_timing.connect_end);
2222 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2223 load_timing_result.connect_timing.ssl_start);
2224 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2225 load_timing_result.connect_timing.ssl_end);
2226
2227 // Redundant sanity check.
2228 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2229}
2230
2231// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502232TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592233 base::TimeTicks now = base::TimeTicks::Now();
2234 LoadTimingInfo job_load_timing =
2235 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2236
[email protected]2ca01e52013-10-31 22:05:192237 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502238 RunURLRequestInterceptorLoadTimingTest(
2239 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592240
2241 // Nothing should have been changed by the URLRequest.
2242 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2243 load_timing_result.proxy_resolve_start);
2244 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2245 load_timing_result.proxy_resolve_end);
2246 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2247 load_timing_result.connect_timing.dns_start);
2248 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2249 load_timing_result.connect_timing.dns_end);
2250 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2251 load_timing_result.connect_timing.connect_start);
2252 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2253 load_timing_result.connect_timing.connect_end);
2254 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2255 load_timing_result.connect_timing.ssl_start);
2256 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2257 load_timing_result.connect_timing.ssl_end);
2258
2259 // Redundant sanity check.
2260 TestLoadTimingNotReusedWithProxy(load_timing_result,
2261 CONNECT_TIMING_HAS_SSL_TIMES);
2262}
2263
2264// Make sure that URLRequest correctly adjusts proxy times when they're before
2265// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102266// the case of reusing a SPDY session. The connected socket is not considered
2267// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592268//
2269// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502270TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592271 base::TimeTicks now = base::TimeTicks::Now();
2272 LoadTimingInfo job_load_timing =
2273 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2274 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2275 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2276 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2277 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2278 job_load_timing.connect_timing.connect_start =
2279 now - base::TimeDelta::FromDays(2);
2280 job_load_timing.connect_timing.connect_end =
2281 now - base::TimeDelta::FromDays(1);
2282
[email protected]2ca01e52013-10-31 22:05:192283 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502284 RunURLRequestInterceptorLoadTimingTest(
2285 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592286
2287 // Proxy times, connect times, and DNS times should all be replaced with
2288 // request_start.
2289 EXPECT_EQ(load_timing_result.request_start,
2290 load_timing_result.proxy_resolve_start);
2291 EXPECT_EQ(load_timing_result.request_start,
2292 load_timing_result.proxy_resolve_end);
2293 EXPECT_EQ(load_timing_result.request_start,
2294 load_timing_result.connect_timing.dns_start);
2295 EXPECT_EQ(load_timing_result.request_start,
2296 load_timing_result.connect_timing.dns_end);
2297 EXPECT_EQ(load_timing_result.request_start,
2298 load_timing_result.connect_timing.connect_start);
2299 EXPECT_EQ(load_timing_result.request_start,
2300 load_timing_result.connect_timing.connect_end);
2301
2302 // Other times should have been left null.
2303 TestLoadTimingNotReusedWithProxy(load_timing_result,
2304 CONNECT_TIMING_HAS_DNS_TIMES);
2305}
2306
2307// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502308TEST_F(URLRequestInterceptorTest,
2309 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592310 base::TimeTicks now = base::TimeTicks::Now();
2311 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2312 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2313 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2314
[email protected]2ca01e52013-10-31 22:05:192315 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502316 RunURLRequestInterceptorLoadTimingTest(
2317 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592318
2319 // Proxy times and connect times should all be replaced with request_start.
2320 EXPECT_EQ(load_timing_result.request_start,
2321 load_timing_result.proxy_resolve_start);
2322 EXPECT_EQ(load_timing_result.request_start,
2323 load_timing_result.proxy_resolve_end);
2324
2325 // Other times should have been left null.
2326 TestLoadTimingReusedWithProxy(load_timing_result);
2327}
2328
2329// Make sure that URLRequest correctly adjusts connect times when they're before
2330// |request_start|, due to reusing a connected socket. The connected socket is
2331// not considered reused in this test (May be a preconnect).
2332//
2333// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502334TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592335 base::TimeTicks now = base::TimeTicks::Now();
2336 LoadTimingInfo job_load_timing =
2337 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2338 job_load_timing.connect_timing.connect_start =
2339 now - base::TimeDelta::FromDays(1);
2340 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2341 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2342 job_load_timing.connect_timing.connect_end =
2343 now - base::TimeDelta::FromDays(4);
2344
[email protected]2ca01e52013-10-31 22:05:192345 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502346 RunURLRequestInterceptorLoadTimingTest(
2347 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592348
2349 // Connect times, and SSL times should be replaced with request_start.
2350 EXPECT_EQ(load_timing_result.request_start,
2351 load_timing_result.connect_timing.connect_start);
2352 EXPECT_EQ(load_timing_result.request_start,
2353 load_timing_result.connect_timing.ssl_start);
2354 EXPECT_EQ(load_timing_result.request_start,
2355 load_timing_result.connect_timing.ssl_end);
2356 EXPECT_EQ(load_timing_result.request_start,
2357 load_timing_result.connect_timing.connect_end);
2358
2359 // Other times should have been left null.
2360 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2361}
2362
2363// Make sure that URLRequest correctly adjusts connect times when they're before
2364// |request_start|, due to reusing a connected socket in the case that there
2365// are also proxy times. The connected socket is not considered reused in this
2366// test (May be a preconnect).
2367//
2368// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502369TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592370 base::TimeTicks now = base::TimeTicks::Now();
2371 LoadTimingInfo job_load_timing =
2372 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2373 job_load_timing.connect_timing.connect_start =
2374 now - base::TimeDelta::FromDays(1);
2375 job_load_timing.connect_timing.connect_end =
2376 now - base::TimeDelta::FromDays(2);
2377
[email protected]2ca01e52013-10-31 22:05:192378 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502379 RunURLRequestInterceptorLoadTimingTest(
2380 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592381
2382 // Connect times should be replaced with proxy_resolve_end.
2383 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2384 load_timing_result.connect_timing.connect_start);
2385 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2386 load_timing_result.connect_timing.connect_end);
2387
2388 // Other times should have been left null.
2389 TestLoadTimingNotReusedWithProxy(load_timing_result,
2390 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2391}
2392
[email protected]316c1e5e2012-09-12 15:17:442393// Check that two different URL requests have different identifiers.
2394TEST_F(URLRequestTest, Identifiers) {
2395 TestDelegate d;
2396 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362397 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162398 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2399 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362400 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162401 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2402 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442403
mmenke19378d22014-09-09 04:12:592404 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442405}
2406
blundellb8163592f2015-12-16 14:22:422407#if defined(OS_IOS)
2408// TODO(droger): Check that a failure to connect to the proxy is reported to
2409// the network delegate. crbug.com/496743
2410#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2411#else
2412#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2413#endif
2414TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442415 MockHostResolver host_resolver;
2416 host_resolver.rules()->AddSimulatedFailure("*");
2417
[email protected]ceefd7fd2012-11-29 00:36:242418 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442419 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2420
2421 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362422 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162423 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2424 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192425 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442426
[email protected]f7022f32014-08-21 16:32:192427 req->Start();
Wez2a31b222018-06-07 22:07:152428 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442429
2430 // Check we see a failed request.
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:222431 // The proxy server should be set before failure.
2432 EXPECT_EQ(ProxyServer::FromPacString("PROXY myproxy:70"),
2433 req->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:502434 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442435
2436 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012437 EXPECT_THAT(network_delegate.last_error(),
2438 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442439 EXPECT_EQ(1, network_delegate.completed_requests());
2440}
2441
[email protected]cba24642014-08-15 20:49:592442// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442443// content is empty.
2444TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2445 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072446 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162447 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192448 req->Start();
Wez2a31b222018-06-07 22:07:152449 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442450 EXPECT_EQ("", d.data_received());
2451 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2452}
2453
[email protected]5033ab82013-03-22 20:17:462454// Make sure that SetPriority actually sets the URLRequest's priority
2455// correctly, both before and after start.
2456TEST_F(URLRequestTest, SetPriorityBasic) {
2457 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072458 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162459 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2460 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192461 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462462
[email protected]f7022f32014-08-21 16:32:192463 req->SetPriority(LOW);
2464 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462465
[email protected]f7022f32014-08-21 16:32:192466 req->Start();
2467 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462468
[email protected]f7022f32014-08-21 16:32:192469 req->SetPriority(MEDIUM);
2470 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462471}
2472
2473// Make sure that URLRequest calls SetPriority on a job before calling
2474// Start on it.
2475TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2476 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072477 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162478 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2479 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192480 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462481
mmenkeed0498b2015-12-08 23:20:422482 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362483 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422484 req.get(), &default_network_delegate_, &job_priority));
2485 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2486 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462487
[email protected]f7022f32014-08-21 16:32:192488 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462489
[email protected]f7022f32014-08-21 16:32:192490 req->Start();
mmenkeed0498b2015-12-08 23:20:422491 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462492}
2493
2494// Make sure that URLRequest passes on its priority updates to its
2495// job.
2496TEST_F(URLRequestTest, SetJobPriority) {
2497 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072498 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162499 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2500 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462501
mmenkeed0498b2015-12-08 23:20:422502 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362503 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422504 req.get(), &default_network_delegate_, &job_priority));
2505 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462506
[email protected]f7022f32014-08-21 16:32:192507 req->SetPriority(LOW);
2508 req->Start();
mmenkeed0498b2015-12-08 23:20:422509 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462510
[email protected]f7022f32014-08-21 16:32:192511 req->SetPriority(MEDIUM);
2512 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422513 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462514}
2515
[email protected]bb1c4662013-11-14 00:00:072516// Setting the IGNORE_LIMITS load flag should be okay if the priority
2517// is MAXIMUM_PRIORITY.
2518TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2519 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072520 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162521 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2522 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192523 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072524
mmenkeed0498b2015-12-08 23:20:422525 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362526 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422527 req.get(), &default_network_delegate_, &job_priority));
2528 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072529
[email protected]f7022f32014-08-21 16:32:192530 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2531 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072532
[email protected]f7022f32014-08-21 16:32:192533 req->SetPriority(MAXIMUM_PRIORITY);
2534 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072535
[email protected]f7022f32014-08-21 16:32:192536 req->Start();
2537 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422538 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072539}
2540
nick5d570de92015-05-04 20:16:162541namespace {
2542
2543// Less verbose way of running a simple testserver for the tests below.
David Benjamin42116f62017-11-20 21:45:392544class HttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442545 public:
David Benjamin42116f62017-11-20 21:45:392546 explicit HttpTestServer(const base::FilePath& document_root) {
tommycli59a63432015-11-06 00:10:552547 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272548 }
tommycli59a63432015-11-06 00:10:552549
David Benjamin42116f62017-11-20 21:45:392550 HttpTestServer() { AddDefaultHandlers(base::FilePath()); }
tommycli59a63432015-11-06 00:10:552551};
tommyclieae5f75f2015-11-05 19:07:272552
nick5d570de92015-05-04 20:16:162553} // namespace
2554
[email protected]f2f31b32013-01-16 23:24:092555TEST_F(URLRequestTest, DelayedCookieCallback) {
David Benjamin42116f62017-11-20 21:45:392556 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442557 ASSERT_TRUE(test_server.Start());
2558
2559 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362560 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502561 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442562
2563 // Set up a cookie.
2564 {
2565 TestNetworkDelegate network_delegate;
2566 context.set_network_delegate(&network_delegate);
2567 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362568 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552569 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162570 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192571 req->Start();
Wez2a31b222018-06-07 22:07:152572 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442573 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2574 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2575 EXPECT_EQ(1, network_delegate.set_cookie_count());
2576 }
2577
2578 // Verify that the cookie is set.
2579 {
2580 TestNetworkDelegate network_delegate;
2581 context.set_network_delegate(&network_delegate);
2582 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362583 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162584 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2585 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192586 req->Start();
Wez2a31b222018-06-07 22:07:152587 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442588
2589 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2590 != std::string::npos);
2591 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2592 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2593 }
2594}
2595
Aaron Tagliaboschi028009e2019-03-07 16:28:062596class FilteringTestLayeredNetworkDelegate : public LayeredNetworkDelegate {
2597 public:
2598 FilteringTestLayeredNetworkDelegate(
2599 std::unique_ptr<NetworkDelegate> network_delegate)
2600 : LayeredNetworkDelegate(std::move((network_delegate))),
2601 set_cookie_called_count_(0),
2602 blocked_set_cookie_count_(0) {}
2603 ~FilteringTestLayeredNetworkDelegate() override = default;
2604
2605 bool OnCanSetCookieInternal(const URLRequest& request,
2606 const net::CanonicalCookie& cookie,
2607 CookieOptions* options,
2608 bool allowed_from_caller) override {
2609 // Filter out cookies with the same name as |cookie_name_filter_| and
2610 // combine with |allowed_from_caller|.
2611 bool allowed =
2612 allowed_from_caller && !(cookie.Name() == cookie_name_filter_);
2613
2614 ++set_cookie_called_count_;
2615
2616 if (!allowed)
2617 ++blocked_set_cookie_count_;
2618
2619 return allowed;
2620 }
2621
2622 void SetCookieFilter(std::string filter) {
2623 cookie_name_filter_ = std::move(filter);
2624 }
2625
2626 int set_cookie_called_count() { return set_cookie_called_count_; }
2627
2628 int blocked_set_cookie_count() { return blocked_set_cookie_count_; }
2629
2630 void ResetSetCookieCalledCount() { set_cookie_called_count_ = 0; }
2631
2632 void ResetBlockedSetCookieCount() { blocked_set_cookie_count_ = 0; }
2633
2634 private:
2635 std::string cookie_name_filter_;
2636 int set_cookie_called_count_;
2637 int blocked_set_cookie_count_;
2638};
2639
2640TEST_F(URLRequestTest, DelayedCookieCallbackAsync) {
2641 HttpTestServer test_server;
2642 ASSERT_TRUE(test_server.Start());
2643
2644 TestURLRequestContext async_context;
2645 std::unique_ptr<DelayedCookieMonster> delayed_cm =
2646 std::make_unique<DelayedCookieMonster>();
2647 async_context.set_cookie_store(delayed_cm.get());
2648 FilteringTestLayeredNetworkDelegate async_filter_network_delegate(
2649 std::make_unique<TestNetworkDelegate>());
2650 async_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
2651 async_context.set_network_delegate(&async_filter_network_delegate);
2652 TestDelegate async_delegate;
2653
2654 TestURLRequestContext sync_context;
2655 std::unique_ptr<CookieMonster> cm =
Nick Harper57142b1c2019-03-14 21:03:592656 std::make_unique<CookieMonster>(nullptr, nullptr);
Aaron Tagliaboschi028009e2019-03-07 16:28:062657 sync_context.set_cookie_store(cm.get());
2658 FilteringTestLayeredNetworkDelegate sync_filter_network_delegate(
2659 std::make_unique<TestNetworkDelegate>());
2660 sync_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
2661 sync_context.set_network_delegate(&sync_filter_network_delegate);
2662 TestDelegate sync_delegate;
2663
2664 // Add a secure cookie so we can try to set an insecure cookie and have
2665 // SetCanonicalCookie (and therefore SetCookieWithOptions) fail.
2666 GURL::Replacements replace_scheme;
2667 replace_scheme.SetSchemeStr("https");
2668 GURL url = test_server.base_url().ReplaceComponents(replace_scheme);
2669
2670 delayed_cm->SetCookieWithOptionsAsync(url, "AlreadySetCookie=1;Secure",
2671 CookieOptions(),
2672 CookieStore::SetCookiesCallback());
2673 cm->SetCookieWithOptionsAsync(url, "AlreadySetCookie=1;Secure",
2674 CookieOptions(),
2675 CookieStore::SetCookiesCallback());
2676
2677 std::vector<std::string> cookie_lines(
2678 {// Fails on CanonicalCookie::Create for trying to create a secure cookie
2679 // on an insecure host.
2680 "CookieNotSet=1;Secure",
2681 // Fail in FilteringTestLayeredNetworkDelegate::CanGetCookie.
2682 "CookieBlockedOnCanGetCookie=1",
2683 // Fails in SetCanonicalCookie for trying to overwrite a secure cookie
2684 // with an insecure cookie.
2685 "AlreadySetCookie=1",
2686 // Succeeds and added cookie to store. Delayed (which makes the callback
2687 // run asynchronously) in DelayedCookieMonster.
2688 "CookieSet=1"});
2689
2690 for (auto first_cookie_line : cookie_lines) {
2691 for (auto second_cookie_line : cookie_lines) {
2692 // Run with the delayed cookie monster.
2693 std::unique_ptr<URLRequest> request = async_context.CreateRequest(
2694 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2695 second_cookie_line),
2696 DEFAULT_PRIORITY, &async_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2697
2698 request->Start();
2699 async_delegate.RunUntilComplete();
2700 EXPECT_THAT(async_delegate.request_status(), IsOk());
2701
2702 // Run with the regular cookie monster.
2703 request = sync_context.CreateRequest(
2704 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2705 second_cookie_line),
2706 DEFAULT_PRIORITY, &sync_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2707
2708 request->Start();
2709 sync_delegate.RunUntilComplete();
2710 EXPECT_THAT(sync_delegate.request_status(), IsOk());
2711
2712 int expected_set_cookie_count = 0;
2713 int expected_blocked_cookie_count = 0;
2714
2715 if (first_cookie_line != "CookieNotSet=1;Secure")
2716 ++expected_set_cookie_count;
2717 if (second_cookie_line != "CookieNotSet=1;Secure")
2718 ++expected_set_cookie_count;
2719
2720 if (first_cookie_line == "CookieBlockedOnCanGetCookie=1")
2721 ++expected_blocked_cookie_count;
2722 if (second_cookie_line == "CookieBlockedOnCanGetCookie=1")
2723 ++expected_blocked_cookie_count;
2724
2725 EXPECT_EQ(expected_set_cookie_count,
2726 async_filter_network_delegate.set_cookie_called_count());
2727 EXPECT_EQ(expected_blocked_cookie_count,
2728 async_filter_network_delegate.blocked_set_cookie_count());
2729
2730 EXPECT_EQ(expected_set_cookie_count,
2731 sync_filter_network_delegate.set_cookie_called_count());
2732 EXPECT_EQ(expected_blocked_cookie_count,
2733 sync_filter_network_delegate.blocked_set_cookie_count());
2734
2735 async_filter_network_delegate.ResetSetCookieCalledCount();
2736 async_filter_network_delegate.ResetBlockedSetCookieCount();
2737
2738 sync_filter_network_delegate.ResetSetCookieCalledCount();
2739 sync_filter_network_delegate.ResetBlockedSetCookieCount();
2740 }
2741 }
2742}
2743
[email protected]f2f31b32013-01-16 23:24:092744TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392745 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442746 ASSERT_TRUE(test_server.Start());
2747
2748 // Set up a cookie.
2749 {
2750 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072751 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442752 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072753 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552754 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162755 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192756 req->Start();
Wez2a31b222018-06-07 22:07:152757 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442758 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2759 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2760 }
2761
2762 // Verify that the cookie is set.
2763 {
2764 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072765 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442766 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072767 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162768 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2769 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192770 req->Start();
Wez2a31b222018-06-07 22:07:152771 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442772
2773 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2774 != std::string::npos);
2775 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2776 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2777 }
2778
2779 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2780 {
2781 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072782 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442783 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072784 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162785 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2786 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192787 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2788 req->Start();
Wez2a31b222018-06-07 22:07:152789 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442790
2791 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2792 == std::string::npos);
2793
2794 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2795 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2796 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2797 }
2798}
2799
2800TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392801 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442802 ASSERT_TRUE(test_server.Start());
2803
2804 // Set up a cookie.
2805 {
2806 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072807 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442808 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072809 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552810 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162811 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192812 req->Start();
Wez2a31b222018-06-07 22:07:152813 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442814
2815 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2816 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2817 EXPECT_EQ(1, network_delegate.set_cookie_count());
2818 }
2819
2820 // Try to set-up another cookie and update the previous cookie.
2821 {
2822 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072823 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442824 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072825 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552826 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162827 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192828 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2829 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442830
Wez2a31b222018-06-07 22:07:152831 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442832
2833 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2834 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2835 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2836 EXPECT_EQ(0, network_delegate.set_cookie_count());
2837 }
2838
2839 // Verify the cookies weren't saved or updated.
2840 {
2841 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072842 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442843 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072844 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162845 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2846 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192847 req->Start();
Wez2a31b222018-06-07 22:07:152848 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442849
2850 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2851 == std::string::npos);
2852 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2853 != std::string::npos);
2854
2855 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2856 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2857 EXPECT_EQ(0, network_delegate.set_cookie_count());
2858 }
2859}
2860
2861TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392862 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442863 ASSERT_TRUE(test_server.Start());
2864
2865 // Set up a cookie.
2866 {
2867 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072868 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442869 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072870 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552871 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162872 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192873 req->Start();
Wez2a31b222018-06-07 22:07:152874 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442875
2876 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2877 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2878 }
2879
2880 // Verify that the cookie is set.
2881 {
2882 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072883 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442884 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072885 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162886 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2887 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192888 req->Start();
Wez2a31b222018-06-07 22:07:152889 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442890
2891 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2892 != std::string::npos);
2893
2894 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2895 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182896 TestNetLogEntry::List entries;
2897 net_log_.GetEntries(&entries);
2898 for (const auto& entry : entries) {
2899 EXPECT_NE(entry.type,
2900 NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE);
2901 }
[email protected]316c1e5e2012-09-12 15:17:442902 }
2903
2904 // Verify that the cookie isn't sent.
2905 {
2906 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072907 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442908 TestDelegate d;
2909 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:072910 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162911 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2912 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192913 req->Start();
Wez2a31b222018-06-07 22:07:152914 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442915
2916 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2917 == std::string::npos);
2918
[email protected]22e045f2013-09-20 03:54:032919 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442920 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182921 TestNetLogEntry::List entries;
2922 net_log_.GetEntries(&entries);
2923 ExpectLogContainsSomewhereAfter(
2924 entries, 0, NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE,
2925 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442926 }
2927}
2928
marqf14fff8d2015-12-02 15:52:292929// TODO(crbug.com/564656) This test is flaky on iOS.
2930#if defined(OS_IOS)
2931#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2932#else
2933#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2934#endif
[email protected]316c1e5e2012-09-12 15:17:442935TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392936 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442937 ASSERT_TRUE(test_server.Start());
2938
2939 // Set up a cookie.
2940 {
2941 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072942 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442943 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072944 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552945 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162946 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192947 req->Start();
Wez2a31b222018-06-07 22:07:152948 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442949
2950 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2951 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182952 TestNetLogEntry::List entries;
2953 net_log_.GetEntries(&entries);
2954 for (const auto& entry : entries) {
2955 EXPECT_NE(entry.type,
2956 NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE);
2957 }
[email protected]316c1e5e2012-09-12 15:17:442958 }
2959
2960 // Try to set-up another cookie and update the previous cookie.
2961 {
2962 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072963 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442964 TestDelegate d;
2965 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:072966 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552967 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162968 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192969 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442970
Wez2a31b222018-06-07 22:07:152971 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442972
2973 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2974 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182975 TestNetLogEntry::List entries;
2976 net_log_.GetEntries(&entries);
2977 ExpectLogContainsSomewhereAfter(
2978 entries, 0, NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE,
2979 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442980 }
2981
2982 // Verify the cookies weren't saved or updated.
2983 {
2984 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072985 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442986 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072987 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162988 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2989 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192990 req->Start();
Wez2a31b222018-06-07 22:07:152991 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442992
2993 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2994 == std::string::npos);
2995 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2996 != std::string::npos);
2997
2998 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2999 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3000 }
3001}
3002
3003TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:393004 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443005 ASSERT_TRUE(test_server.Start());
3006
3007 // Set up an empty cookie.
3008 {
3009 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073010 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443011 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073012 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163013 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
3014 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193015 req->Start();
Wez2a31b222018-06-07 22:07:153016 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443017
3018 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3019 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3020 EXPECT_EQ(0, network_delegate.set_cookie_count());
3021 }
3022}
3023
3024TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393025 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443026 ASSERT_TRUE(test_server.Start());
3027
3028 // Set up a cookie.
3029 {
3030 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073031 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443032 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073033 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553034 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163035 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193036 req->Start();
Wez2a31b222018-06-07 22:07:153037 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443038
3039 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3040 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3041 }
3042
3043 // Verify that the cookie is set.
3044 {
3045 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073046 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443047 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073048 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163049 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3050 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193051 req->Start();
Wez2a31b222018-06-07 22:07:153052 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443053
3054 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
3055 != std::string::npos);
3056
3057 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3058 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3059 }
3060
3061 // Verify that the cookie isn't sent.
3062 {
3063 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073064 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443065 TestDelegate d;
3066 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:073067 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163068 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3069 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193070 req->Start();
Wez2a31b222018-06-07 22:07:153071 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443072
3073 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
3074 == std::string::npos);
3075
[email protected]22e045f2013-09-20 03:54:033076 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:443077 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3078 }
3079}
3080
3081TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393082 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443083 ASSERT_TRUE(test_server.Start());
3084
3085 // Set up a cookie.
3086 {
3087 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073088 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443089 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073090 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553091 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163092 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193093 req->Start();
Wez2a31b222018-06-07 22:07:153094 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443095
3096 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3097 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3098 }
3099
3100 // Try to set-up another cookie and update the previous cookie.
3101 {
3102 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073103 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443104 TestDelegate d;
3105 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:073106 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553107 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:163108 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193109 req->Start();
[email protected]316c1e5e2012-09-12 15:17:443110
Wez2a31b222018-06-07 22:07:153111 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443112
3113 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3114 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
3115 }
3116
3117 // Verify the cookies weren't saved or updated.
3118 {
3119 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073120 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443121 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073122 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163123 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3124 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193125 req->Start();
Wez2a31b222018-06-07 22:07:153126 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443127
3128 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
3129 == std::string::npos);
3130 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
3131 != std::string::npos);
3132
3133 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3134 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3135 }
3136}
3137
mkwstc5fa7762016-03-28 09:28:233138TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:393139 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:263140 ASSERT_TRUE(test_server.Start());
3141
mkwst202534e32016-01-15 16:07:153142 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073143 default_context().set_network_delegate(&network_delegate);
mkwst202534e32016-01-15 16:07:153144
mkwstf71d0bd2016-03-21 14:15:243145 const std::string kHost = "example.test";
3146 const std::string kSubHost = "subdomain.example.test";
3147 const std::string kCrossHost = "cross-origin.test";
3148
3149 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:263150 {
mkwst3f3daac2015-02-26 20:15:263151 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073152 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
mkwstf71d0bd2016-03-21 14:15:243153 test_server.GetURL(kHost,
3154 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3155 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:163156 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Maks Orlovich8a3e4132019-04-23 16:59:243157 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3158 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263159 req->Start();
Wez2a31b222018-06-07 22:07:153160 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263161 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3162 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:243163 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:263164 }
3165
mkwstf71d0bd2016-03-21 14:15:243166 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:263167 {
mkwst3f3daac2015-02-26 20:15:263168 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073169 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163170 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3171 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463172 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463173 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263174 req->Start();
Wez2a31b222018-06-07 22:07:153175 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263176
mkwstf71d0bd2016-03-21 14:15:243177 EXPECT_NE(std::string::npos,
3178 d.data_received().find("StrictSameSiteCookie=1"));
3179 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263180 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3181 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3182 }
3183
clamyfd58ca072016-12-21 17:18:323184 // Verify that both cookies are sent when the request has no initiator (can
3185 // happen for main frame browser-initiated navigations).
3186 {
3187 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073188 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163189 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3190 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463191 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:323192 req->Start();
Wez2a31b222018-06-07 22:07:153193 d.RunUntilComplete();
clamyfd58ca072016-12-21 17:18:323194
3195 EXPECT_NE(std::string::npos,
3196 d.data_received().find("StrictSameSiteCookie=1"));
3197 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3198 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3199 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3200 }
3201
mkwstf71d0bd2016-03-21 14:15:243202 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263203 {
mkwst3f3daac2015-02-26 20:15:263204 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073205 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163206 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3207 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463208 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463209 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153210 req->Start();
Wez2a31b222018-06-07 22:07:153211 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153212
mkwstf71d0bd2016-03-21 14:15:243213 EXPECT_NE(std::string::npos,
3214 d.data_received().find("StrictSameSiteCookie=1"));
3215 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153216 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3217 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3218 }
3219
mkwstf71d0bd2016-03-21 14:15:243220 // Verify that neither cookie is not sent for cross-site requests.
3221 {
3222 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073223 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163224 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3225 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463226 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463227 req->set_initiator(
3228 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243229 req->Start();
Wez2a31b222018-06-07 22:07:153230 d.RunUntilComplete();
mkwstf71d0bd2016-03-21 14:15:243231
3232 EXPECT_EQ(std::string::npos,
3233 d.data_received().find("StrictSameSiteCookie=1"));
3234 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3235 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3236 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3237 }
3238
3239 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153240 // method is "safe".
3241 {
3242 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073243 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163244 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3245 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463246 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463247 req->set_initiator(
3248 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243249 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153250 req->Start();
Wez2a31b222018-06-07 22:07:153251 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153252
mkwstf71d0bd2016-03-21 14:15:243253 EXPECT_EQ(std::string::npos,
3254 d.data_received().find("StrictSameSiteCookie=1"));
3255 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153256 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3257 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3258 }
3259
mkwstf71d0bd2016-03-21 14:15:243260 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153261 // method is unsafe (e.g. POST).
3262 {
3263 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073264 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163265 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3266 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463267 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463268 req->set_initiator(
3269 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153270 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263271 req->Start();
Wez2a31b222018-06-07 22:07:153272 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263273
mkwstf71d0bd2016-03-21 14:15:243274 EXPECT_EQ(std::string::npos,
3275 d.data_received().find("StrictSameSiteCookie=1"));
3276 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263277 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3278 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3279 }
3280}
3281
Maks Orlovich8a3e4132019-04-23 16:59:243282TEST_F(URLRequestTest, SettingSameSiteCookies) {
3283 HttpTestServer test_server;
3284 ASSERT_TRUE(test_server.Start());
3285
3286 TestNetworkDelegate network_delegate;
3287 default_context().set_network_delegate(&network_delegate);
3288
3289 const std::string kHost = "example.test";
3290 const std::string kSubHost = "subdomain.example.test";
3291 const std::string kCrossHost = "cross-origin.test";
3292
3293 int expected_cookies = 0;
3294
3295 {
3296 TestDelegate d;
3297 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3298 test_server.GetURL(kHost,
3299 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3300 "LaxSameSiteCookie=1;SameSite=Lax"),
3301 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3302 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3303 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
3304
3305 // 'SameSite' cookies are settable from strict same-site contexts
3306 // (same-origin site_for_cookies, same-origin initiator), so this request
3307 // should result in two cookies being created.
3308 expected_cookies += 2;
3309
3310 req->Start();
3311 d.RunUntilComplete();
3312 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3313 }
3314
3315 {
3316 TestDelegate d;
3317 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3318 test_server.GetURL(kHost,
3319 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3320 "LaxSameSiteCookie=1;SameSite=Lax"),
3321 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3322 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3323 req->set_initiator(
3324 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3325
3326 // 'SameSite' cookies are settable from lax same-site contexts (same-origin
3327 // site_for_cookies, cross-site initiator), so this request should result in
3328 // two cookies being created.
3329 expected_cookies += 2;
3330
3331 req->Start();
3332 d.RunUntilComplete();
3333 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3334 }
3335
3336 {
3337 TestDelegate d;
3338 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3339 test_server.GetURL(kHost,
3340 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3341 "LaxSameSiteCookie=1;SameSite=Lax"),
3342 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3343 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
3344 req->set_initiator(
3345 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3346
3347 // 'SameSite' cookies are settable from lax same-site contexts (same-site
3348 // site_for_cookies, cross-site initiator), so this request should result in
3349 // two cookies being created.
3350 expected_cookies += 2;
3351
3352 req->Start();
3353 d.RunUntilComplete();
3354 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3355 }
3356
3357 {
3358 TestDelegate d;
3359 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3360 test_server.GetURL(kHost,
3361 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3362 "LaxSameSiteCookie=1;SameSite=Lax"),
3363 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3364 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
3365
3366 // 'SameSite' cookies are settable from strict same-site contexts (same-site
3367 // site_for_cookies, no initiator), so this request should result in two
3368 // cookies being created.
3369 expected_cookies += 2;
3370
3371 req->Start();
3372 d.RunUntilComplete();
3373 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3374 }
3375
3376 {
3377 TestDelegate d;
3378 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3379 test_server.GetURL(kHost,
3380 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3381 "LaxSameSiteCookie=1;SameSite=Lax"),
3382 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3383 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
3384 req->set_initiator(
3385 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3386
3387 // 'SameSite' cookies are not settable from cross-site contexts, so this
3388 // should not result in any new cookies being created.
3389 expected_cookies += 0;
3390
3391 req->Start();
3392 d.RunUntilComplete();
3393 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3394 }
3395}
3396
estark557a5eb82015-12-01 22:57:103397// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363398TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553399 EmbeddedTestServer http_server;
3400 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363401 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553402 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3403 https_server.AddDefaultHandlers(
3404 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3405 ASSERT_TRUE(http_server.Start());
3406 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363407
estarkb15166b2015-12-18 16:56:383408 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363409 TestURLRequestContext context(true);
3410 context.set_network_delegate(&network_delegate);
3411 context.Init();
3412
estarkb15166b2015-12-18 16:56:383413 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363414 {
3415 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363416 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103417 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163418 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363419 req->Start();
Wez2a31b222018-06-07 22:07:153420 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363421 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3422 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3423 }
3424
3425 // Verify that the cookie is not set.
3426 {
3427 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363428 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163429 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3430 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363431 req->Start();
Wez2a31b222018-06-07 22:07:153432 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363433
jww79aceda2015-12-07 01:56:343434 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3435 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363436 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3437 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3438 }
3439}
3440
estarkb15166b2015-12-18 16:56:383441TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553442 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3443 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363444 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553445 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363446
3447 TestNetworkDelegate network_delegate;
3448 TestURLRequestContext context(true);
3449 context.set_network_delegate(&network_delegate);
3450 context.Init();
3451
estarkb15166b2015-12-18 16:56:383452 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363453 {
3454 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163455 std::unique_ptr<URLRequest> req(context.CreateRequest(
3456 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3457 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363458 req->Start();
Wez2a31b222018-06-07 22:07:153459 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583460 EXPECT_EQ(0, network_delegate.set_cookie_count());
estarkcd39c11f2015-10-19 19:46:363461 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3462 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3463 }
3464
3465 // Verify that the cookie is not set.
3466 {
3467 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363468 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163469 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3470 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363471 req->Start();
Wez2a31b222018-06-07 22:07:153472 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363473
jww79aceda2015-12-07 01:56:343474 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363475 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3476 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3477 }
3478}
3479
estarkb15166b2015-12-18 16:56:383480TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553481 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3482 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363483 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553484 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363485
estarkb15166b2015-12-18 16:56:383486 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363487 TestURLRequestContext context(true);
3488 context.set_network_delegate(&network_delegate);
3489 context.Init();
3490
estarkb15166b2015-12-18 16:56:383491 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363492 {
3493 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363494 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103495 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163496 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363497 req->Start();
Wez2a31b222018-06-07 22:07:153498 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363499 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3500 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3501 }
3502
3503 // Verify that the cookie is set.
3504 {
3505 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363506 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163507 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3508 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363509 req->Start();
Wez2a31b222018-06-07 22:07:153510 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363511
jww79aceda2015-12-07 01:56:343512 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3513 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3514 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3515 }
3516}
3517
3518// Tests that secure cookies can't be set on non-secure origins if strict secure
3519// cookies are enabled.
3520TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3521 EmbeddedTestServer http_server;
3522 http_server.AddDefaultHandlers(
3523 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3524 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3525 https_server.AddDefaultHandlers(
3526 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3527 ASSERT_TRUE(http_server.Start());
3528 ASSERT_TRUE(https_server.Start());
3529
Matt Menkebe9b6eb2018-10-18 12:11:443530 TestNetworkDelegate network_delegate;
jww79aceda2015-12-07 01:56:343531 TestURLRequestContext context(true);
3532 context.set_network_delegate(&network_delegate);
3533 context.Init();
3534
3535 // Try to set a Secure cookie, with experimental features enabled.
3536 {
3537 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363538 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343539 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163540 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343541 req->Start();
Wez2a31b222018-06-07 22:07:153542 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343543 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3544 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3545 }
3546
3547 // Verify that the cookie is not set.
3548 {
3549 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363550 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163551 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3552 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343553 req->Start();
Wez2a31b222018-06-07 22:07:153554 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343555
3556 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3557 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3558 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3559 }
3560}
3561
Thiemo Nagel0793b9c532018-04-18 16:57:583562// The parameter is true for same-site and false for cross-site requests.
3563class URLRequestTestParameterizedSameSite
3564 : public URLRequestTest,
3565 public ::testing::WithParamInterface<bool> {
3566 protected:
3567 URLRequestTestParameterizedSameSite() {
3568 auto params = std::make_unique<HttpNetworkSession::Params>();
3569 params->ignore_certificate_errors = true;
3570 context_.set_http_network_session_params(std::move(params));
3571 context_.set_network_delegate(&network_delegate_);
3572 https_server_.AddDefaultHandlers(
3573 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3574 EXPECT_TRUE(https_server_.Start());
3575 }
3576
3577 // To be called after configuration of |context_| has been finalized.
3578 void InitContext() { context_.Init(); }
3579
3580 const std::string kHost_ = "example.test";
3581 const std::string kCrossHost_ = "cross-site.test";
3582 TestURLRequestContext context_{true};
3583 TestNetworkDelegate network_delegate_;
3584 base::HistogramTester histograms_;
3585 EmbeddedTestServer https_server_{EmbeddedTestServer::TYPE_HTTPS};
3586};
3587
Victor Costan8fb98f6f2019-02-01 17:08:293588INSTANTIATE_TEST_SUITE_P(URLRequestTest,
3589 URLRequestTestParameterizedSameSite,
3590 ::testing::Bool());
Thiemo Nagel0793b9c532018-04-18 16:57:583591
3592TEST_P(URLRequestTestParameterizedSameSite, CookieAgeMetrics) {
3593 const bool same_site = GetParam();
3594 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3595 InitContext();
3596
Mike West86149882017-07-28 10:41:493597 EmbeddedTestServer http_server;
3598 http_server.AddDefaultHandlers(
3599 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
Thiemo Nagel23e0b322018-04-18 12:46:543600 ASSERT_TRUE(http_server.Start());
3601
Thiemo Nagel0793b9c532018-04-18 16:57:583602 // Set two test cookies.
Thiemo Nagel23e0b322018-04-18 12:46:543603 {
3604 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583605 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3606 http_server.GetURL(kHost_, "/set-cookie?cookie=value&cookie2=value2"),
Thiemo Nagel23e0b322018-04-18 12:46:543607 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3608 req->Start();
Wez2a31b222018-06-07 22:07:153609 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583610 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3611 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3612 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3613 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3614 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 0);
3615 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3616 0);
3617 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3618 0);
3619 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3620 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 0);
Thiemo Nagel23e0b322018-04-18 12:46:543621 }
3622
Thiemo Nagel0793b9c532018-04-18 16:57:583623 // Make a secure request.
Thiemo Nagel23e0b322018-04-18 12:46:543624 {
3625 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583626 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3627 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3628 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3629 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103630 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583631 url::Origin::Create(https_server_.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103632 req->Start();
Wez2a31b222018-06-07 22:07:153633 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583634 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3635 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3636 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3637 !same_site);
3638 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3639 same_site);
3640 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3641 0);
3642 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3643 0);
3644 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3645 same_site ? 0 : 2);
3646 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3647 same_site ? 2 : 0);
3648 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3649 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
Mohsen Izadiad6f7592018-04-18 15:57:103650 }
3651
Thiemo Nagel0793b9c532018-04-18 16:57:583652 // Make a non-secure request.
Mohsen Izadiad6f7592018-04-18 15:57:103653 {
3654 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583655 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3656 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
Mohsen Izadiad6f7592018-04-18 15:57:103657 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel0793b9c532018-04-18 16:57:583658 req->set_site_for_cookies(http_server.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103659 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583660 url::Origin::Create(http_server.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103661 req->Start();
Wez2a31b222018-06-07 22:07:153662 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583663 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest",
3664 !same_site);
3665 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest",
3666 same_site);
3667 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3668 !same_site);
3669 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3670 same_site);
3671 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3672 same_site ? 0 : 2);
3673 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3674 same_site ? 2 : 0);
3675 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3676 same_site ? 0 : 2);
3677 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3678 same_site ? 2 : 0);
3679 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3680 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
3681 }
3682}
3683
3684// Cookies with secure attribute (no HSTS) --> k1pSecureAttribute
3685TEST_P(URLRequestTestParameterizedSameSite,
3686 CookieNetworkSecurityMetricSecureAttribute) {
3687 const bool same_site = GetParam();
3688 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3689 InitContext();
3690
3691 // Set cookies.
3692 {
3693 TestDelegate d;
3694 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3695 https_server_.GetURL(kHost_,
3696 "/set-cookie?session-cookie=value;Secure&"
3697 "longlived-cookie=value;Secure;domain=" +
3698 kHost_ + ";Max-Age=360000"),
3699 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3700 req->Start();
Wez2a31b222018-06-07 22:07:153701 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583702 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3703 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3704 }
3705
3706 // Verify that the cookies fall into the correct metrics bucket.
3707 {
3708 TestDelegate d;
3709 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3710 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3711 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3712 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3713 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3714 req->Start();
Wez2a31b222018-06-07 22:07:153715 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583716 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3717 // Static cast of boolean required for MSVC 1911.
3718 histograms_.ExpectBucketCount(
3719 "Cookie.NetworkSecurity",
3720 static_cast<int>(CookieNetworkSecurity::k1pSecureAttribute) |
3721 static_cast<int>(!same_site),
3722 2);
3723 }
3724}
3725
3726// Short-lived host cookie --> k1pHSTSHostCookie
3727TEST_P(URLRequestTestParameterizedSameSite,
3728 CookieNetworkSecurityMetricShortlivedHostCookie) {
3729 const bool same_site = GetParam();
3730 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3731
3732 TransportSecurityState transport_security_state;
3733 transport_security_state.AddHSTS(
3734 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3735 false /* include_subdomains */);
3736 context_.set_transport_security_state(&transport_security_state);
3737 InitContext();
3738
3739 // Set cookie.
3740 {
3741 TestDelegate d;
3742 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3743 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;Max-Age=3600"),
3744 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3745 req->Start();
Wez2a31b222018-06-07 22:07:153746 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583747 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3748 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3749 }
3750
3751 // Verify that the cookie falls into the correct metrics bucket.
3752 {
3753 TestDelegate d;
3754 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3755 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3756 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3757 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3758 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3759 req->Start();
Wez2a31b222018-06-07 22:07:153760 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583761 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3762 // Static cast of boolean required for MSVC 1911.
3763 histograms_.ExpectBucketCount(
3764 "Cookie.NetworkSecurity",
3765 static_cast<int>(CookieNetworkSecurity::k1pHSTSHostCookie) |
3766 static_cast<int>(!same_site),
3767 1);
3768 }
3769}
3770
3771// Long-lived (either due to expiry or due to being a session cookie) host
3772// cookies --> k1pExpiringHSTSHostCookie
3773TEST_P(URLRequestTestParameterizedSameSite,
3774 CookieNetworkSecurityMetricLonglivedHostCookie) {
3775 const bool same_site = GetParam();
3776 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3777
3778 TransportSecurityState transport_security_state;
3779 transport_security_state.AddHSTS(
3780 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3781 false /* include_subdomains */);
3782 context_.set_transport_security_state(&transport_security_state);
3783 InitContext();
3784
3785 // Set cookies.
3786 {
3787 TestDelegate d;
3788 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3789 https_server_.GetURL(kHost_,
3790 "/set-cookie?session-cookie=value&"
3791 "longlived-cookie=value;Max-Age=360000"),
3792 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3793 req->Start();
Wez2a31b222018-06-07 22:07:153794 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583795 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3796 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3797 }
3798
3799 // Verify that the cookies fall into the correct metrics bucket.
3800 {
3801 TestDelegate d;
3802 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3803 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3804 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3805 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3806 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3807 req->Start();
Wez2a31b222018-06-07 22:07:153808 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583809 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3810 // Static cast of boolean required for MSVC 1911.
3811 histograms_.ExpectBucketCount(
3812 "Cookie.NetworkSecurity",
3813 static_cast<int>(CookieNetworkSecurity::k1pExpiringHSTSHostCookie) |
3814 static_cast<int>(!same_site),
3815 2);
3816 }
3817}
3818
3819// Domain cookie with HSTS subdomains with cookie expiry before HSTS expiry -->
3820// k1pHSTSSubdomainsIncluded
3821TEST_P(URLRequestTestParameterizedSameSite,
3822 CookieNetworkSecurityMetricShortlivedDomainCookie) {
3823 const bool same_site = GetParam();
3824 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3825
3826 TransportSecurityState transport_security_state;
3827 transport_security_state.AddHSTS(
3828 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3829 true /* include_subdomains */);
3830 context_.set_transport_security_state(&transport_security_state);
3831 InitContext();
3832
3833 // Set cookie.
3834 {
3835 TestDelegate d;
3836 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3837 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3838 kHost_ + ";Max-Age=3600"),
3839 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3840 req->Start();
Wez2a31b222018-06-07 22:07:153841 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583842 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3843 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3844 }
3845
3846 // Verify that the cookie falls into the correct metrics bucket.
3847 {
3848 TestDelegate d;
3849 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3850 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3851 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3852 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3853 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3854 req->Start();
Wez2a31b222018-06-07 22:07:153855 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583856 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3857 // Static cast of boolean required for MSVC 1911.
3858 histograms_.ExpectBucketCount(
3859 "Cookie.NetworkSecurity",
3860 static_cast<int>(CookieNetworkSecurity::k1pHSTSSubdomainsIncluded) |
3861 static_cast<int>(!same_site),
3862 1);
3863 }
3864}
3865
3866// Long-lived (either due to expiry or due to being a session cookie) domain
3867// cookies with HSTS subdomains --> k1pExpiringHSTSSubdomainsIncluded
3868TEST_P(URLRequestTestParameterizedSameSite,
3869 CookieNetworkSecurityMetricLonglivedDomainCookie) {
3870 const bool same_site = GetParam();
3871 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3872
3873 TransportSecurityState transport_security_state;
3874 transport_security_state.AddHSTS(
3875 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3876 true /* include_subdomains */);
3877 context_.set_transport_security_state(&transport_security_state);
3878 InitContext();
3879
3880 // Set cookies.
3881 {
3882 TestDelegate d;
3883 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3884 https_server_.GetURL(
3885 kHost_, "/set-cookie?session-cookie=value;domain=" + kHost_ + "&" +
3886 "longlived-cookie=value;domain=" + kHost_ +
3887 ";Max-Age=360000"),
3888 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3889 req->Start();
Wez2a31b222018-06-07 22:07:153890 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583891 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3892 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3893 }
3894
3895 // Verify that the cookies fall into the correct metrics bucket.
3896 {
3897 TestDelegate d;
3898 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3899 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3900 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3901 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3902 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3903 req->Start();
Wez2a31b222018-06-07 22:07:153904 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583905 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3906 // Static cast of boolean required for MSVC 1911.
3907 histograms_.ExpectBucketCount(
3908 "Cookie.NetworkSecurity",
3909 static_cast<int>(
3910 CookieNetworkSecurity::k1pExpiringHSTSSubdomainsIncluded) |
3911 static_cast<int>(!same_site),
3912 2);
3913 }
3914}
3915
3916// Domain cookie with HSTS subdomains not included --> k1pHSTSSpoofable
3917TEST_P(URLRequestTestParameterizedSameSite,
3918 CookieNetworkSecurityMetricSpoofableDomainCookie) {
3919 const bool same_site = GetParam();
3920 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3921
3922 TransportSecurityState transport_security_state;
3923 transport_security_state.AddHSTS(
3924 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3925 false /* include_subdomains */);
3926 context_.set_transport_security_state(&transport_security_state);
3927 InitContext();
3928
3929 // Set cookie.
3930 {
3931 TestDelegate d;
3932 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3933 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3934 kHost_ + ";Max-Age=3600"),
3935 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3936 req->Start();
Wez2a31b222018-06-07 22:07:153937 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583938 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3939 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3940 }
3941
3942 // Verify that the cookie falls into the correct metrics bucket.
3943 {
3944 TestDelegate d;
3945 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3946 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3947 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3948 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3949 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3950 req->Start();
Wez2a31b222018-06-07 22:07:153951 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583952 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3953 // Static cast of boolean required for MSVC 1911.
3954 histograms_.ExpectBucketCount(
3955 "Cookie.NetworkSecurity",
3956 static_cast<int>(CookieNetworkSecurity::k1pHSTSSpoofable) |
3957 static_cast<int>(!same_site),
3958 1);
3959 }
3960}
3961
3962// Cookie without HSTS --> k1p(Non)SecureConnection
3963TEST_P(URLRequestTestParameterizedSameSite, CookieNetworkSecurityMetricNoHSTS) {
3964 const bool same_site = GetParam();
3965 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3966 InitContext();
3967
3968 EmbeddedTestServer http_server;
3969 http_server.AddDefaultHandlers(
3970 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3971 ASSERT_TRUE(http_server.Start());
3972
3973 // Set cookies.
3974 {
3975 TestDelegate d;
3976 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3977 https_server_.GetURL(kHost_,
3978 "/set-cookie?cookie=value;domain=" + kHost_ +
3979 ";Max-Age=3600&host-cookie=value"),
3980 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3981 req->Start();
Wez2a31b222018-06-07 22:07:153982 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583983 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3984 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3985 }
3986
3987 // Verify that the cookie falls into the correct metrics bucket.
3988 {
3989 TestDelegate d;
3990 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3991 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3992 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3993 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3994 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3995 req->Start();
Wez2a31b222018-06-07 22:07:153996 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583997 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3998 // Static cast of boolean required for MSVC 1911.
3999 histograms_.ExpectBucketCount(
4000 "Cookie.NetworkSecurity",
4001 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
4002 static_cast<int>(!same_site),
4003 2);
4004 }
4005
4006 // Verify that the cookie falls into the correct metrics bucket.
4007 {
4008 TestDelegate d;
4009 std::unique_ptr<URLRequest> req(context_.CreateRequest(
4010 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4011 TRAFFIC_ANNOTATION_FOR_TESTS));
4012 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
4013 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
4014 req->Start();
Wez2a31b222018-06-07 22:07:154015 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:584016 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 4);
4017 // Static cast of boolean required for MSVC 1911.
4018 histograms_.ExpectBucketCount(
4019 "Cookie.NetworkSecurity",
4020 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
4021 static_cast<int>(!same_site),
4022 2);
4023 // Static cast of boolean required for MSVC 1911.
4024 histograms_.ExpectBucketCount(
4025 "Cookie.NetworkSecurity",
4026 static_cast<int>(CookieNetworkSecurity::k1pNonsecureConnection) |
4027 static_cast<int>(!same_site),
4028 2);
Mike West86149882017-07-28 10:41:494029 }
4030}
4031
mmenkefb18c772015-09-30 22:22:504032// Tests that a request is cancelled while entering suspend mode. Uses mocks
4033// rather than a spawned test server because the connection used to talk to
4034// the test server is affected by entering suspend mode on Android.
4035TEST_F(URLRequestTest, CancelOnSuspend) {
4036 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:364037 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:504038
4039 URLRequestFailedJob::AddUrlHandler();
4040
4041 TestDelegate d;
4042 // Request that just hangs.
4043 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
Ryan Sleevib8449e02018-07-15 04:31:074044 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164045 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mmenkefb18c772015-09-30 22:22:504046 r->Start();
4047
4048 power_monitor_source->Suspend();
4049 // Wait for the suspend notification to cause the request to fail.
Wez2a31b222018-06-07 22:07:154050 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:504051 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:504052 EXPECT_TRUE(d.request_failed());
4053 EXPECT_EQ(1, default_network_delegate_.completed_requests());
4054
4055 URLRequestFilter::GetInstance()->ClearHandlers();
4056
4057 // Shouldn't be needed, but just in case.
4058 power_monitor_source->Resume();
4059}
4060
[email protected]5095cd72012-11-01 10:29:164061// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
4062// value for the |fixed_date| argument given to the constructor.
4063class FixedDateNetworkDelegate : public TestNetworkDelegate {
4064 public:
4065 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
4066 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:274067 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:164068
[email protected]cba24642014-08-15 20:49:594069 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:204070 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:594071 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:204072 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:594073 const HttpResponseHeaders* original_response_headers,
4074 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134075 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:164076
4077 private:
4078 std::string fixed_date_;
4079
4080 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
4081};
4082
4083int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:594084 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:204085 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:594086 const HttpResponseHeaders* original_response_headers,
4087 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:164088 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:594089 HttpResponseHeaders* new_response_headers =
4090 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:164091
4092 new_response_headers->RemoveHeader("Date");
4093 new_response_headers->AddHeader("Date: " + fixed_date_);
4094
4095 *override_response_headers = new_response_headers;
David Benjamind1f287bf2018-06-12 01:57:204096 return TestNetworkDelegate::OnHeadersReceived(
4097 request, std::move(callback), original_response_headers,
4098 override_response_headers, allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:164099}
4100
4101// Test that cookie expiration times are adjusted for server/client clock
4102// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
4103// headers by defaulting to GMT. (crbug.com/135131)
4104TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:394105 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:164106 ASSERT_TRUE(test_server.Start());
4107
4108 // Set up an expired cookie.
4109 {
4110 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074111 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164112 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074113 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194114 test_server.GetURL(
tommycli59a63432015-11-06 00:10:554115 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:164116 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194117 req->Start();
Wez2a31b222018-06-07 22:07:154118 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164119 }
4120 // Verify that the cookie is not set.
4121 {
4122 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074123 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164124 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074125 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164126 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4127 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194128 req->Start();
Wez2a31b222018-06-07 22:07:154129 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164130
4131 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
4132 }
4133 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
4134 {
4135 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
Ryan Sleevib8449e02018-07-15 04:31:074136 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164137 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074138 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194139 test_server.GetURL(
tommycli59a63432015-11-06 00:10:554140 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:164141 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194142 req->Start();
Wez2a31b222018-06-07 22:07:154143 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164144 }
4145 // Verify that the cookie is set.
4146 {
4147 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074148 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164149 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074150 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164151 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4152 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194153 req->Start();
Wez2a31b222018-06-07 22:07:154154 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164155
4156 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
4157 }
4158}
4159
4160
[email protected]316c1e5e2012-09-12 15:17:444161// Check that it is impossible to change the referrer in the extra headers of
4162// an URLRequest.
4163TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:394164 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:444165 ASSERT_TRUE(test_server.Start());
4166
4167 // If extra headers contain referer and the request contains a referer,
4168 // only the latter shall be respected.
4169 {
4170 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074171 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164172 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4173 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194174 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:444175
4176 HttpRequestHeaders headers;
4177 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194178 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:444179
[email protected]f7022f32014-08-21 16:32:194180 req->Start();
Wez2a31b222018-06-07 22:07:154181 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444182
4183 EXPECT_EQ("http://foo.com/", d.data_received());
4184 }
4185
4186 // If extra headers contain a referer but the request does not, no referer
4187 // shall be sent in the header.
4188 {
4189 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074190 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164191 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4192 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:444193
4194 HttpRequestHeaders headers;
4195 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194196 req->SetExtraRequestHeaders(headers);
4197 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:444198
[email protected]f7022f32014-08-21 16:32:194199 req->Start();
Wez2a31b222018-06-07 22:07:154200 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444201
4202 EXPECT_EQ("None", d.data_received());
4203 }
4204}
4205
[email protected]b89290212009-08-14 22:37:354206class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:114207 public:
mmenke9f2ec60c2015-06-01 20:59:474208 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:114209
[email protected]b89290212009-08-14 22:37:354210 protected:
[email protected]21184962011-10-26 00:50:304211 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
4212 // |request_method| is the method to use for the initial request.
4213 // |redirect_method| is the method that is expected to be used for the second
4214 // request, after redirection.
4215 // If |include_data| is true, data is uploaded with the request. The
4216 // response body is expected to match it exactly, if and only if
4217 // |request_method| == |redirect_method|.
4218 void HTTPRedirectMethodTest(const GURL& redirect_url,
4219 const std::string& request_method,
4220 const std::string& redirect_method,
4221 bool include_data) {
4222 static const char kData[] = "hello world";
4223 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074224 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164225 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194226 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:304227 if (include_data) {
mmenkecbc2b712014-10-09 20:29:074228 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:304229 HttpRequestHeaders headers;
4230 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244231 base::NumberToString(base::size(kData) - 1));
svaldez5b3a8972015-10-09 23:23:544232 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:194233 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:304234 }
[email protected]f7022f32014-08-21 16:32:194235 req->Start();
Wez2a31b222018-06-07 22:07:154236 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194237 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:504238 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:304239 if (include_data) {
4240 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:544241 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4242 HttpRequestHeaders::kContentLength));
4243 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4244 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304245 EXPECT_EQ(kData, d.data_received());
4246 } else {
svaldez5b3a8972015-10-09 23:23:544247 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4248 HttpRequestHeaders::kContentLength));
4249 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4250 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304251 EXPECT_NE(kData, d.data_received());
4252 }
4253 }
4254 if (HasFailure())
4255 LOG(WARNING) << "Request method was: " << request_method;
4256 }
4257
Alex Clarke1e08882b32017-10-06 14:22:404258 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
4259 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:514260 // |request_method| is the method to use for the initial request.
4261 // |redirect_method| is the method that is expected to be used for the second
4262 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:404263 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:514264 // redirection. If empty, expects that there will be no Origin header.
4265 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
4266 const std::string& request_method,
4267 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:404268 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:514269 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074270 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164271 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:514272 req->set_method(request_method);
4273 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
4274 redirect_url.GetOrigin().spec(), false);
4275 req->Start();
4276
Wez2a31b222018-06-07 22:07:154277 d.RunUntilComplete();
jww5fe460ff2015-03-28 00:22:514278
4279 EXPECT_EQ(redirect_method, req->method());
4280 // Note that there is no check for request success here because, for
4281 // purposes of testing, the request very well may fail. For example, if the
4282 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
4283 // origin, there is not an HTTPS server in this unit test framework, so the
4284 // request would fail. However, that's fine, as long as the request headers
4285 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:404286 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:514287 EXPECT_FALSE(
4288 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
4289 } else {
4290 std::string origin_header;
4291 EXPECT_TRUE(req->extra_request_headers().GetHeader(
4292 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:404293 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:514294 }
4295 }
4296
[email protected]762d2db2010-01-11 19:03:014297 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:014298 const int kMsgSize = 20000; // multiple of 10
4299 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:484300 char* uploadBytes = new char[kMsgSize+1];
4301 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:014302 char marker = 'a';
4303 for (int idx = 0; idx < kMsgSize/10; idx++) {
4304 memcpy(ptr, "----------", 10);
4305 ptr += 10;
4306 if (idx % 100 == 0) {
4307 ptr--;
4308 *ptr++ = marker;
4309 if (++marker > 'z')
4310 marker = 'a';
4311 }
4312 }
4313 uploadBytes[kMsgSize] = '\0';
4314
[email protected]762d2db2010-01-11 19:03:014315 for (int i = 0; i < kIterations; ++i) {
4316 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074317 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164318 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
4319 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194320 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:014321
mmenkecbc2b712014-10-09 20:29:074322 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:014323
[email protected]f7022f32014-08-21 16:32:194324 r->Start();
4325 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:014326
Wez2a31b222018-06-07 22:07:154327 d.RunUntilComplete();
[email protected]762d2db2010-01-11 19:03:014328
maksim.sisovb53724b52016-09-16 05:30:504329 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
4330 << d.request_status();
[email protected]762d2db2010-01-11 19:03:014331
4332 EXPECT_FALSE(d.received_data_before_response());
4333 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:014334 }
4335 delete[] uploadBytes;
4336 }
4337
[email protected]ede03212012-09-07 12:52:264338 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:344339 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074340 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:554341 test_server_.GetURL("/set-many-cookies?" +
Raul Tambre8c1981d2019-02-08 02:22:264342 base::NumberToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:164343 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:344344
[email protected]f7022f32014-08-21 16:32:194345 r->Start();
4346 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:344347
Wez2a31b222018-06-07 22:07:154348 d.RunUntilComplete();
[email protected]263163f2012-06-14 22:40:344349
maksim.sisovb53724b52016-09-16 05:30:504350 if (d.request_status() != OK) {
4351 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
4352 return false;
4353 }
[email protected]263163f2012-06-14 22:40:344354
maksim.sisovb53724b52016-09-16 05:30:504355 return true;
[email protected]263163f2012-06-14 22:40:344356 }
4357
David Benjamin42116f62017-11-20 21:45:394358 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:504359
tommycli59a63432015-11-06 00:10:554360 private:
David Benjamin42116f62017-11-20 21:45:394361 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:354362};
4363
tommycli59a63432015-11-06 00:10:554364namespace {
4365
danakj8522a25b2016-04-16 00:17:364366std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:554367 const test_server::HttpRequest& request) {
4368 if (request.headers.find("Host") == request.headers.end() ||
4369 request.headers.at("Host") != "www.redirect.com" ||
4370 request.method != test_server::METHOD_CONNECT) {
4371 return nullptr;
4372 }
4373
danakj8522a25b2016-04-16 00:17:364374 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554375 new test_server::BasicHttpResponse);
4376 http_response->set_code(HTTP_FOUND);
4377 http_response->AddCustomHeader("Location",
4378 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:484379 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554380}
4381
nharperb7441ef2016-01-25 23:54:144382class TestSSLConfigService : public SSLConfigService {
4383 public:
Nick Harper2243e8002018-09-28 20:33:264384 TestSSLConfigService()
4385 : min_version_(kDefaultSSLVersionMin),
davidben095ebb52017-04-12 22:23:344386 max_version_(kDefaultSSLVersionMax) {}
Ryan Sleevib8449e02018-07-15 04:31:074387 ~TestSSLConfigService() override = default;
nharperb7441ef2016-01-25 23:54:144388
davidben095ebb52017-04-12 22:23:344389 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:144390 void set_min_version(uint16_t version) { min_version_ = version; }
4391
nharperb7441ef2016-01-25 23:54:144392 // SSLConfigService:
4393 void GetSSLConfig(SSLConfig* config) override {
4394 *config = SSLConfig();
davidben095ebb52017-04-12 22:23:344395 config->version_min = min_version_;
4396 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:144397 }
4398
Nick Harper89bc7212018-07-31 19:07:574399 bool CanShareConnectionWithClientCerts(
4400 const std::string& hostname) const override {
4401 return false;
4402 }
4403
nharperb7441ef2016-01-25 23:54:144404 private:
nharperb7441ef2016-01-25 23:54:144405 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:344406 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:144407};
4408
Nick Harper89bc7212018-07-31 19:07:574409} // namespace
4410
nharperb7441ef2016-01-25 23:54:144411// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114412// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:554413// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:114414// follow.
[email protected]f2f31b32013-01-16 23:24:094415TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:554416 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124417 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:554418 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114419
[email protected]ceefd7fd2012-11-29 00:36:244420 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044421 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554422 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504423
[email protected]d1ec59082009-02-11 02:48:154424 TestDelegate d;
4425 {
danakj8522a25b2016-04-16 00:17:364426 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164427 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4428 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194429 r->Start();
4430 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:154431
Wez2a31b222018-06-07 22:07:154432 d.RunUntilComplete();
[email protected]d1ec59082009-02-11 02:48:154433
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:224434 // The proxy server should be set before failure.
4435 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4436 http_test_server()->host_port_pair()),
4437 r->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:504438 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084439 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:154440 // We should not have followed the redirect.
4441 EXPECT_EQ(0, d.received_redirect_count());
4442 }
4443}
4444
[email protected]8202d0c2011-02-23 08:31:144445// This is the same as the previous test, but checks that the network delegate
4446// registers the error.
[email protected]c044616e2013-02-20 02:01:264447TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554448 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144449
[email protected]ceefd7fd2012-11-29 00:36:244450 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044451 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554452 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504453
[email protected]8202d0c2011-02-23 08:31:144454 TestDelegate d;
4455 {
danakj8522a25b2016-04-16 00:17:364456 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164457 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4458 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194459 r->Start();
4460 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144461
Wez2a31b222018-06-07 22:07:154462 d.RunUntilComplete();
[email protected]8202d0c2011-02-23 08:31:144463
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:224464 // The proxy server should be set before failure.
4465 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4466 http_test_server()->host_port_pair()),
4467 r->proxy_server());
[email protected]8202d0c2011-02-23 08:31:144468 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504469 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144470 // We should not have followed the redirect.
4471 EXPECT_EQ(0, d.received_redirect_count());
4472
4473 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014474 EXPECT_THAT(network_delegate.last_error(),
4475 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144476 }
4477}
4478
[email protected]dc5a5cf2012-09-26 02:49:304479// Tests that we can block and asynchronously return OK in various stages.
4480TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4481 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4482 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4483 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4484 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4485 };
Avi Drissman4365a4782018-12-28 19:26:244486 static const size_t blocking_stages_length = base::size(blocking_stages);
[email protected]dc5a5cf2012-09-26 02:49:304487
tommycli59a63432015-11-06 00:10:554488 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304489
4490 TestDelegate d;
4491 BlockingNetworkDelegate network_delegate(
4492 BlockingNetworkDelegate::USER_CALLBACK);
4493 network_delegate.set_block_on(
4494 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4495 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4496 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4497
4498 TestURLRequestContext context(true);
4499 context.set_network_delegate(&network_delegate);
4500 context.Init();
4501
4502 {
danakj8522a25b2016-04-16 00:17:364503 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164504 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4505 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304506
[email protected]f7022f32014-08-21 16:32:194507 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304508 for (size_t i = 0; i < blocking_stages_length; ++i) {
Wez2a31b222018-06-07 22:07:154509 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304510 EXPECT_EQ(blocking_stages[i],
4511 network_delegate.stage_blocked_for_callback());
4512 network_delegate.DoCallback(OK);
4513 }
Wez2a31b222018-06-07 22:07:154514 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194515 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504516 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304517 EXPECT_EQ(1, network_delegate.created_requests());
4518 EXPECT_EQ(0, network_delegate.destroyed_requests());
4519 }
4520 EXPECT_EQ(1, network_delegate.destroyed_requests());
4521}
4522
[email protected]4c76d7c2011-04-15 19:14:124523// Tests that the network delegate can block and cancel a request.
4524TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554525 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124526
4527 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304528 BlockingNetworkDelegate network_delegate(
4529 BlockingNetworkDelegate::AUTO_CALLBACK);
4530 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4531 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124532
[email protected]d5a4dd62012-05-23 01:41:044533 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554534 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504535
[email protected]4c76d7c2011-04-15 19:14:124536 {
rhalavatib7bd7c792017-04-27 05:25:164537 std::unique_ptr<URLRequest> r(
4538 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4539 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124540
[email protected]f7022f32014-08-21 16:32:194541 r->Start();
Wez2a31b222018-06-07 22:07:154542 d.RunUntilComplete();
[email protected]4c76d7c2011-04-15 19:14:124543
[email protected]d8fc4722014-06-13 13:17:154544 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474545 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504546 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124547 EXPECT_EQ(1, network_delegate.created_requests());
4548 EXPECT_EQ(0, network_delegate.destroyed_requests());
4549 }
4550 EXPECT_EQ(1, network_delegate.destroyed_requests());
4551}
4552
[email protected]b4438d32012-09-27 06:15:304553// Helper function for NetworkDelegateCancelRequestAsynchronously and
4554// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4555// delegate operating in |block_mode| and a request for |url|. It blocks the
4556// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4557void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4558 BlockingNetworkDelegate::Stage stage,
4559 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364560 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304561 BlockingNetworkDelegate network_delegate(block_mode);
4562 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4563 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364564
[email protected]b4438d32012-09-27 06:15:304565 TestURLRequestContext context(true);
4566 context.set_network_delegate(&network_delegate);
4567 context.Init();
[email protected]3cd384c602011-08-31 16:12:364568
4569 {
rhalavatib7bd7c792017-04-27 05:25:164570 std::unique_ptr<URLRequest> r(context.CreateRequest(
4571 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364572
[email protected]f7022f32014-08-21 16:32:194573 r->Start();
Wez2a31b222018-06-07 22:07:154574 d.RunUntilComplete();
[email protected]3cd384c602011-08-31 16:12:364575
[email protected]d8fc4722014-06-13 13:17:154576 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474577 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4578 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4579 EXPECT_FALSE(r->proxy_server().is_valid());
4580 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4581 EXPECT_TRUE(r->proxy_server().is_direct());
4582 } else {
4583 NOTREACHED();
4584 }
maksim.sisovb53724b52016-09-16 05:30:504585 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364586 EXPECT_EQ(1, network_delegate.created_requests());
4587 EXPECT_EQ(0, network_delegate.destroyed_requests());
4588 }
4589 EXPECT_EQ(1, network_delegate.destroyed_requests());
4590}
4591
[email protected]b4438d32012-09-27 06:15:304592// The following 3 tests check that the network delegate can cancel a request
4593// synchronously in various stages of the request.
4594TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554595 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304596 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4597 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554598 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304599}
4600
4601TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554602 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304603 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4604 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554605 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304606}
4607
4608TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554609 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304610 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4611 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554612 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304613}
4614
4615// The following 3 tests check that the network delegate can cancel a request
4616// asynchronously in various stages of the request.
4617TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554618 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304619 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4620 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554621 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304622}
4623
4624TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554625 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304626 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4627 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554628 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304629}
4630
4631TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554632 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304633 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4634 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554635 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304636}
4637
[email protected]4c76d7c2011-04-15 19:14:124638// Tests that the network delegate can block and redirect a request to a new
4639// URL.
4640TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554641 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124642
4643 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304644 BlockingNetworkDelegate network_delegate(
4645 BlockingNetworkDelegate::AUTO_CALLBACK);
4646 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
Eric Romanda790f92018-11-07 19:17:154647 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]4c76d7c2011-04-15 19:14:124648 network_delegate.set_redirect_url(redirect_url);
4649
[email protected]d5a4dd62012-05-23 01:41:044650 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554651 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504652
[email protected]4c76d7c2011-04-15 19:14:124653 {
Eric Romanda790f92018-11-07 19:17:154654 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164655 std::unique_ptr<URLRequest> r(context.CreateRequest(
4656 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124657
[email protected]6be6fa92014-08-06 23:44:564658 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194659 r->Start();
Wez0e717112018-06-18 23:09:224660 d.RunUntilRedirect();
[email protected]4c76d7c2011-04-15 19:14:124661
[email protected]6be6fa92014-08-06 23:44:564662 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194663 EXPECT_EQ(307, r->GetResponseCode());
4664 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564665 std::string location;
Raul Tambre94493c652019-03-11 17:18:354666 ASSERT_TRUE(
4667 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564668 EXPECT_EQ(redirect_url, GURL(location));
4669
4670 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354671 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4672 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154673 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:504674 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474675 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4676 http_test_server()->host_port_pair()),
4677 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094678 // before_send_headers_with_proxy_count only increments for headers sent
4679 // through an untunneled proxy.
4680 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554681 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4682 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274683
maksim.sisovb53724b52016-09-16 05:30:504684 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194685 EXPECT_EQ(redirect_url, r->url());
4686 EXPECT_EQ(original_url, r->original_url());
4687 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124688 EXPECT_EQ(1, network_delegate.created_requests());
4689 EXPECT_EQ(0, network_delegate.destroyed_requests());
4690 }
4691 EXPECT_EQ(1, network_delegate.destroyed_requests());
4692}
4693
[email protected]b813ed72012-04-05 08:21:364694// Tests that the network delegate can block and redirect a request to a new
4695// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4696TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554697 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364698
4699 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304700 BlockingNetworkDelegate network_delegate(
4701 BlockingNetworkDelegate::SYNCHRONOUS);
Eric Romanda790f92018-11-07 19:17:154702 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]b813ed72012-04-05 08:21:364703 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364704
[email protected]d5a4dd62012-05-23 01:41:044705 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554706 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364707
4708 {
Eric Romanda790f92018-11-07 19:17:154709 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164710 std::unique_ptr<URLRequest> r(context.CreateRequest(
4711 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364712
[email protected]6be6fa92014-08-06 23:44:564713 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194714 r->Start();
Wez0e717112018-06-18 23:09:224715 d.RunUntilRedirect();
[email protected]b813ed72012-04-05 08:21:364716
[email protected]6be6fa92014-08-06 23:44:564717 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194718 EXPECT_EQ(307, r->GetResponseCode());
4719 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564720 std::string location;
Raul Tambre94493c652019-03-11 17:18:354721 ASSERT_TRUE(
4722 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564723 EXPECT_EQ(redirect_url, GURL(location));
4724
4725 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354726 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4727 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154728 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564729
maksim.sisovb53724b52016-09-16 05:30:504730 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474731 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4732 http_test_server()->host_port_pair()),
4733 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094734 // before_send_headers_with_proxy_count only increments for headers sent
4735 // through an untunneled proxy.
4736 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554737 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4738 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504739 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194740 EXPECT_EQ(redirect_url, r->url());
4741 EXPECT_EQ(original_url, r->original_url());
4742 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364743 EXPECT_EQ(1, network_delegate.created_requests());
4744 EXPECT_EQ(0, network_delegate.destroyed_requests());
4745 }
4746 EXPECT_EQ(1, network_delegate.destroyed_requests());
4747}
4748
[email protected]3c5ca8c2011-09-29 01:14:514749// Tests that redirects caused by the network delegate preserve POST data.
4750TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554751 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514752
4753 const char kData[] = "hello world";
4754
4755 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304756 BlockingNetworkDelegate network_delegate(
4757 BlockingNetworkDelegate::AUTO_CALLBACK);
4758 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554759 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514760 network_delegate.set_redirect_url(redirect_url);
4761
[email protected]ef2bf422012-05-11 03:27:094762 TestURLRequestContext context(true);
4763 context.set_network_delegate(&network_delegate);
4764 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514765
4766 {
tommycli59a63432015-11-06 00:10:554767 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164768 std::unique_ptr<URLRequest> r(context.CreateRequest(
4769 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194770 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074771 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514772 HttpRequestHeaders headers;
4773 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244774 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194775 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564776
4777 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194778 r->Start();
Wez0e717112018-06-18 23:09:224779 d.RunUntilRedirect();
[email protected]3c5ca8c2011-09-29 01:14:514780
[email protected]6be6fa92014-08-06 23:44:564781 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194782 EXPECT_EQ(307, r->GetResponseCode());
4783 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564784 std::string location;
Raul Tambre94493c652019-03-11 17:18:354785 ASSERT_TRUE(
4786 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564787 EXPECT_EQ(redirect_url, GURL(location));
4788
4789 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354790 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4791 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154792 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564793
maksim.sisovb53724b52016-09-16 05:30:504794 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194795 EXPECT_EQ(redirect_url, r->url());
4796 EXPECT_EQ(original_url, r->original_url());
4797 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514798 EXPECT_EQ(1, network_delegate.created_requests());
4799 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194800 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514801 EXPECT_EQ(kData, d.data_received());
4802 }
4803 EXPECT_EQ(1, network_delegate.destroyed_requests());
4804}
4805
[email protected]5f714132014-03-26 10:41:164806// Tests that the network delegate can block and redirect a request to a new
4807// URL during OnHeadersReceived.
4808TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554809 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164810
4811 TestDelegate d;
4812 BlockingNetworkDelegate network_delegate(
4813 BlockingNetworkDelegate::AUTO_CALLBACK);
4814 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
Eric Romanda790f92018-11-07 19:17:154815 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]5f714132014-03-26 10:41:164816 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4817
4818 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554819 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164820
4821 {
Eric Romanda790f92018-11-07 19:17:154822 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164823 std::unique_ptr<URLRequest> r(context.CreateRequest(
4824 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164825
[email protected]f7022f32014-08-21 16:32:194826 r->Start();
Wez2a31b222018-06-07 22:07:154827 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:164828
maksim.sisovb53724b52016-09-16 05:30:504829 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474830 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4831 http_test_server()->host_port_pair()),
4832 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094833 // before_send_headers_with_proxy_count only increments for headers sent
4834 // through an untunneled proxy.
4835 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554836 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4837 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194838
maksim.sisovb53724b52016-09-16 05:30:504839 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194840 EXPECT_EQ(redirect_url, r->url());
4841 EXPECT_EQ(original_url, r->original_url());
4842 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164843 EXPECT_EQ(2, network_delegate.created_requests());
4844 EXPECT_EQ(0, network_delegate.destroyed_requests());
4845 }
4846 EXPECT_EQ(1, network_delegate.destroyed_requests());
4847}
4848
[email protected]c2911d72011-10-03 22:16:364849// Tests that the network delegate can synchronously complete OnAuthRequired
4850// by taking no action. This indicates that the NetworkDelegate does not want to
4851// handle the challenge, and is passing the buck along to the
4852// URLRequest::Delegate.
4853TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554854 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364855
4856 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304857 BlockingNetworkDelegate network_delegate(
4858 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364859
[email protected]ef2bf422012-05-11 03:27:094860 TestURLRequestContext context(true);
4861 context.set_network_delegate(&network_delegate);
4862 context.Init();
[email protected]c2911d72011-10-03 22:16:364863
[email protected]f3cf9802011-10-28 18:44:584864 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364865
4866 {
tommycli59a63432015-11-06 00:10:554867 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164868 std::unique_ptr<URLRequest> r(context.CreateRequest(
4869 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194870 r->Start();
[email protected]79e1fd62013-06-20 06:50:044871
Wez2a31b222018-06-07 22:07:154872 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044873
maksim.sisovb53724b52016-09-16 05:30:504874 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194875 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044876 EXPECT_TRUE(d.auth_required_called());
4877 EXPECT_EQ(1, network_delegate.created_requests());
4878 EXPECT_EQ(0, network_delegate.destroyed_requests());
4879 }
4880 EXPECT_EQ(1, network_delegate.destroyed_requests());
4881}
4882
4883TEST_F(URLRequestTestHTTP,
4884 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554885 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044886
4887 TestDelegate d;
4888 BlockingNetworkDelegate network_delegate(
4889 BlockingNetworkDelegate::SYNCHRONOUS);
4890
4891 TestURLRequestContext context(true);
4892 context.set_network_delegate(&network_delegate);
4893 context.Init();
4894
4895 d.set_credentials(AuthCredentials(kUser, kSecret));
4896
4897 {
tommycli59a63432015-11-06 00:10:554898 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164899 std::unique_ptr<URLRequest> r(context.CreateRequest(
4900 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194901 r->Start();
[email protected]79e1fd62013-06-20 06:50:044902
Wez2a31b222018-06-07 22:07:154903 d.RunUntilComplete();
shivanisha8061c4202017-06-13 23:35:524904
[email protected]79e1fd62013-06-20 06:50:044905 {
4906 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194907 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524908 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044909 }
4910
maksim.sisovb53724b52016-09-16 05:30:504911 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194912 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364913 EXPECT_TRUE(d.auth_required_called());
4914 EXPECT_EQ(1, network_delegate.created_requests());
4915 EXPECT_EQ(0, network_delegate.destroyed_requests());
4916 }
4917 EXPECT_EQ(1, network_delegate.destroyed_requests());
4918}
4919
4920// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404921// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364922TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554923 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364924
4925 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304926 BlockingNetworkDelegate network_delegate(
4927 BlockingNetworkDelegate::SYNCHRONOUS);
4928 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364929 network_delegate.set_auth_retval(
4930 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4931
[email protected]f3cf9802011-10-28 18:44:584932 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364933
[email protected]ef2bf422012-05-11 03:27:094934 TestURLRequestContext context(true);
4935 context.set_network_delegate(&network_delegate);
4936 context.Init();
[email protected]c2911d72011-10-03 22:16:364937
4938 {
tommycli59a63432015-11-06 00:10:554939 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164940 std::unique_ptr<URLRequest> r(context.CreateRequest(
4941 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194942 r->Start();
Wez2a31b222018-06-07 22:07:154943 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364944
maksim.sisovb53724b52016-09-16 05:30:504945 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194946 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364947 EXPECT_FALSE(d.auth_required_called());
4948 EXPECT_EQ(1, network_delegate.created_requests());
4949 EXPECT_EQ(0, network_delegate.destroyed_requests());
4950 }
4951 EXPECT_EQ(1, network_delegate.destroyed_requests());
4952}
4953
[email protected]79e1fd62013-06-20 06:50:044954// Same as above, but also tests that GetFullRequestHeaders returns the proper
4955// headers (for the first or second request) when called at the proper times.
4956TEST_F(URLRequestTestHTTP,
4957 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554958 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044959
4960 TestDelegate d;
4961 BlockingNetworkDelegate network_delegate(
4962 BlockingNetworkDelegate::SYNCHRONOUS);
4963 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4964 network_delegate.set_auth_retval(
4965 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4966
4967 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4968
4969 TestURLRequestContext context(true);
4970 context.set_network_delegate(&network_delegate);
4971 context.Init();
4972
4973 {
tommycli59a63432015-11-06 00:10:554974 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164975 std::unique_ptr<URLRequest> r(context.CreateRequest(
4976 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194977 r->Start();
Wez2a31b222018-06-07 22:07:154978 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044979
maksim.sisovb53724b52016-09-16 05:30:504980 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194981 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044982 EXPECT_FALSE(d.auth_required_called());
4983 EXPECT_EQ(1, network_delegate.created_requests());
4984 EXPECT_EQ(0, network_delegate.destroyed_requests());
4985
4986 {
4987 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194988 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044989 EXPECT_TRUE(headers.HasHeader("Authorization"));
4990 }
4991 }
4992 EXPECT_EQ(1, network_delegate.destroyed_requests());
4993}
4994
[email protected]c2911d72011-10-03 22:16:364995// Tests that the network delegate can synchronously complete OnAuthRequired
4996// by cancelling authentication.
4997TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554998 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364999
5000 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305001 BlockingNetworkDelegate network_delegate(
5002 BlockingNetworkDelegate::SYNCHRONOUS);
5003 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365004 network_delegate.set_auth_retval(
5005 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
5006
[email protected]ef2bf422012-05-11 03:27:095007 TestURLRequestContext context(true);
5008 context.set_network_delegate(&network_delegate);
5009 context.Init();
[email protected]c2911d72011-10-03 22:16:365010
5011 {
tommycli59a63432015-11-06 00:10:555012 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165013 std::unique_ptr<URLRequest> r(context.CreateRequest(
5014 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195015 r->Start();
Wez2a31b222018-06-07 22:07:155016 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365017
maksim.sisovb53724b52016-09-16 05:30:505018 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195019 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365020 EXPECT_FALSE(d.auth_required_called());
5021 EXPECT_EQ(1, network_delegate.created_requests());
5022 EXPECT_EQ(0, network_delegate.destroyed_requests());
5023 }
5024 EXPECT_EQ(1, network_delegate.destroyed_requests());
5025}
5026
5027// Tests that the network delegate can asynchronously complete OnAuthRequired
5028// by taking no action. This indicates that the NetworkDelegate does not want
5029// to handle the challenge, and is passing the buck along to the
5030// URLRequest::Delegate.
5031TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:555032 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365033
5034 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305035 BlockingNetworkDelegate network_delegate(
5036 BlockingNetworkDelegate::AUTO_CALLBACK);
5037 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365038
[email protected]ef2bf422012-05-11 03:27:095039 TestURLRequestContext context(true);
5040 context.set_network_delegate(&network_delegate);
5041 context.Init();
[email protected]c2911d72011-10-03 22:16:365042
[email protected]f3cf9802011-10-28 18:44:585043 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:365044
5045 {
tommycli59a63432015-11-06 00:10:555046 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165047 std::unique_ptr<URLRequest> r(context.CreateRequest(
5048 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195049 r->Start();
Wez2a31b222018-06-07 22:07:155050 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365051
maksim.sisovb53724b52016-09-16 05:30:505052 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195053 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365054 EXPECT_TRUE(d.auth_required_called());
5055 EXPECT_EQ(1, network_delegate.created_requests());
5056 EXPECT_EQ(0, network_delegate.destroyed_requests());
5057 }
5058 EXPECT_EQ(1, network_delegate.destroyed_requests());
5059}
5060
5061// Tests that the network delegate can asynchronously complete OnAuthRequired
5062// by setting credentials.
5063TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:555064 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365065
5066 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305067 BlockingNetworkDelegate network_delegate(
5068 BlockingNetworkDelegate::AUTO_CALLBACK);
5069 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365070 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365071 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5072
[email protected]f3cf9802011-10-28 18:44:585073 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:365074 network_delegate.set_auth_credentials(auth_credentials);
5075
[email protected]ef2bf422012-05-11 03:27:095076 TestURLRequestContext context(true);
5077 context.set_network_delegate(&network_delegate);
5078 context.Init();
[email protected]c2911d72011-10-03 22:16:365079
5080 {
tommycli59a63432015-11-06 00:10:555081 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165082 std::unique_ptr<URLRequest> r(context.CreateRequest(
5083 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195084 r->Start();
Wez2a31b222018-06-07 22:07:155085 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365086
maksim.sisovb53724b52016-09-16 05:30:505087 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195088 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365089 EXPECT_FALSE(d.auth_required_called());
5090 EXPECT_EQ(1, network_delegate.created_requests());
5091 EXPECT_EQ(0, network_delegate.destroyed_requests());
5092 }
5093 EXPECT_EQ(1, network_delegate.destroyed_requests());
5094}
5095
5096// Tests that the network delegate can asynchronously complete OnAuthRequired
5097// by cancelling authentication.
5098TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:555099 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365100
5101 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305102 BlockingNetworkDelegate network_delegate(
5103 BlockingNetworkDelegate::AUTO_CALLBACK);
5104 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365105 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365106 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
5107
[email protected]ef2bf422012-05-11 03:27:095108 TestURLRequestContext context(true);
5109 context.set_network_delegate(&network_delegate);
5110 context.Init();
[email protected]c2911d72011-10-03 22:16:365111
5112 {
tommycli59a63432015-11-06 00:10:555113 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165114 std::unique_ptr<URLRequest> r(context.CreateRequest(
5115 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195116 r->Start();
Wez2a31b222018-06-07 22:07:155117 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365118
maksim.sisovb53724b52016-09-16 05:30:505119 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195120 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365121 EXPECT_FALSE(d.auth_required_called());
5122 EXPECT_EQ(1, network_delegate.created_requests());
5123 EXPECT_EQ(0, network_delegate.destroyed_requests());
5124 }
5125 EXPECT_EQ(1, network_delegate.destroyed_requests());
5126}
5127
David Benjamin0bda12f2018-02-07 19:58:455128// Tests that NetworkDelegate header overrides from the 401 response do not
5129// affect the 200 response. This is a regression test for
5130// https://crbug.com/801237.
5131TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
5132 ASSERT_TRUE(http_test_server()->Start());
5133
5134 TestDelegate d;
5135 d.set_credentials(AuthCredentials(kUser, kSecret));
5136 default_network_delegate_.set_add_header_to_first_response(true);
5137
5138 {
5139 GURL url(http_test_server()->GetURL("/auth-basic"));
Ryan Sleevib8449e02018-07-15 04:31:075140 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455141 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5142 r->Start();
5143
Wez2a31b222018-06-07 22:07:155144 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455145
5146 EXPECT_EQ(OK, d.request_status());
5147 EXPECT_EQ(200, r->GetResponseCode());
5148 EXPECT_TRUE(d.auth_required_called());
5149 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
5150 }
5151
5152 {
5153 GURL url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075154 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455155 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5156 r->Start();
5157
Wez2a31b222018-06-07 22:07:155158 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455159
5160 // Check that set_add_header_to_first_response normally adds a header.
5161 EXPECT_EQ(OK, d.request_status());
5162 EXPECT_EQ(200, r->GetResponseCode());
5163 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
5164 }
5165}
5166
[email protected]9045b8822012-01-13 20:35:355167// Tests that we can handle when a network request was canceled while we were
5168// waiting for the network delegate.
5169// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
5170TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:555171 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355172
5173 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305174 BlockingNetworkDelegate network_delegate(
5175 BlockingNetworkDelegate::USER_CALLBACK);
5176 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:355177
[email protected]ef2bf422012-05-11 03:27:095178 TestURLRequestContext context(true);
5179 context.set_network_delegate(&network_delegate);
5180 context.Init();
[email protected]9045b8822012-01-13 20:35:355181
5182 {
rhalavatib7bd7c792017-04-27 05:25:165183 std::unique_ptr<URLRequest> r(
5184 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5185 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355186
[email protected]f7022f32014-08-21 16:32:195187 r->Start();
Wez2a31b222018-06-07 22:07:155188 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305189 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
5190 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355191 EXPECT_EQ(0, network_delegate.completed_requests());
5192 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195193 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355194 // Ensure that network delegate is notified.
5195 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505196 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355197 EXPECT_EQ(1, network_delegate.created_requests());
5198 EXPECT_EQ(0, network_delegate.destroyed_requests());
5199 }
5200 EXPECT_EQ(1, network_delegate.destroyed_requests());
5201}
5202
5203// Tests that we can handle when a network request was canceled while we were
5204// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:005205// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
5206// callback.
[email protected]9045b8822012-01-13 20:35:355207TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:555208 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355209
5210 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305211 BlockingNetworkDelegate network_delegate(
5212 BlockingNetworkDelegate::USER_CALLBACK);
5213 network_delegate.set_block_on(
5214 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:355215
[email protected]ef2bf422012-05-11 03:27:095216 TestURLRequestContext context(true);
5217 context.set_network_delegate(&network_delegate);
5218 context.Init();
[email protected]9045b8822012-01-13 20:35:355219
5220 {
rhalavatib7bd7c792017-04-27 05:25:165221 std::unique_ptr<URLRequest> r(
5222 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5223 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355224
[email protected]f7022f32014-08-21 16:32:195225 r->Start();
Wez2a31b222018-06-07 22:07:155226 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305227 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
5228 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355229 EXPECT_EQ(0, network_delegate.completed_requests());
5230 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195231 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355232 // Ensure that network delegate is notified.
5233 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505234 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355235 EXPECT_EQ(1, network_delegate.created_requests());
5236 EXPECT_EQ(0, network_delegate.destroyed_requests());
5237 }
5238 EXPECT_EQ(1, network_delegate.destroyed_requests());
5239}
5240
5241// Tests that we can handle when a network request was canceled while we were
5242// waiting for the network delegate.
5243// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
5244TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:555245 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355246
5247 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305248 BlockingNetworkDelegate network_delegate(
5249 BlockingNetworkDelegate::USER_CALLBACK);
5250 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:355251
[email protected]ef2bf422012-05-11 03:27:095252 TestURLRequestContext context(true);
5253 context.set_network_delegate(&network_delegate);
5254 context.Init();
[email protected]9045b8822012-01-13 20:35:355255
5256 {
rhalavatib7bd7c792017-04-27 05:25:165257 std::unique_ptr<URLRequest> r(
5258 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5259 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355260
[email protected]f7022f32014-08-21 16:32:195261 r->Start();
Wez2a31b222018-06-07 22:07:155262 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305263 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
5264 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355265 EXPECT_EQ(0, network_delegate.completed_requests());
5266 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195267 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355268 // Ensure that network delegate is notified.
5269 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505270 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355271 EXPECT_EQ(1, network_delegate.created_requests());
5272 EXPECT_EQ(0, network_delegate.destroyed_requests());
5273 }
5274 EXPECT_EQ(1, network_delegate.destroyed_requests());
5275}
5276
5277// Tests that we can handle when a network request was canceled while we were
5278// waiting for the network delegate.
5279// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:025280TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:555281 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355282
5283 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305284 BlockingNetworkDelegate network_delegate(
5285 BlockingNetworkDelegate::USER_CALLBACK);
5286 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:355287
[email protected]ef2bf422012-05-11 03:27:095288 TestURLRequestContext context(true);
5289 context.set_network_delegate(&network_delegate);
5290 context.Init();
[email protected]9045b8822012-01-13 20:35:355291
5292 {
danakj8522a25b2016-04-16 00:17:365293 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165294 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
5295 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355296
[email protected]f7022f32014-08-21 16:32:195297 r->Start();
Wez2a31b222018-06-07 22:07:155298 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305299 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
5300 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355301 EXPECT_EQ(0, network_delegate.completed_requests());
5302 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195303 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355304 // Ensure that network delegate is notified.
5305 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505306 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355307 EXPECT_EQ(1, network_delegate.created_requests());
5308 EXPECT_EQ(0, network_delegate.destroyed_requests());
5309 }
5310 EXPECT_EQ(1, network_delegate.destroyed_requests());
5311}
5312
tommycli59a63432015-11-06 00:10:555313namespace {
5314
danakj8522a25b2016-04-16 00:17:365315std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:555316 const test_server::HttpRequest& request) {
5317 if (request.headers.find("Host") == request.headers.end() ||
5318 request.headers.at("Host") != "www.server-auth.com" ||
5319 request.method != test_server::METHOD_CONNECT) {
5320 return nullptr;
5321 }
5322
danakj8522a25b2016-04-16 00:17:365323 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:555324 new test_server::BasicHttpResponse);
5325 http_response->set_code(HTTP_UNAUTHORIZED);
5326 http_response->AddCustomHeader("WWW-Authenticate",
5327 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:485328 return std::move(http_response);
tommycli59a63432015-11-06 00:10:555329}
5330
5331} // namespace
5332
5333// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:115334// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:555335// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:355336TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:555337 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:125338 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:555339 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115340
[email protected]ceefd7fd2012-11-29 00:36:245341 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:045342 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:555343 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:505344
[email protected]dc651782009-02-14 01:45:085345 TestDelegate d;
5346 {
danakj8522a25b2016-04-16 00:17:365347 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165348 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
5349 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:085350
[email protected]f7022f32014-08-21 16:32:195351 r->Start();
5352 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:085353
Wez2a31b222018-06-07 22:07:155354 d.RunUntilComplete();
[email protected]dc651782009-02-14 01:45:085355
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:225356 // The proxy server should be set before failure.
5357 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
5358 http_test_server()->host_port_pair()),
5359 r->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:505360 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:085361 }
5362}
5363
[email protected]b89290212009-08-14 22:37:355364TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:555365 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115366
initial.commit586acc5fe2008-07-26 22:42:525367 TestDelegate d;
5368 {
Ryan Sleevib8449e02018-07-15 04:31:075369 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165370 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5371 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525372
[email protected]f7022f32014-08-21 16:32:195373 r->Start();
5374 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525375
Wez2a31b222018-06-07 22:07:155376 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525377
5378 EXPECT_EQ(1, d.response_started_count());
5379 EXPECT_FALSE(d.received_data_before_response());
5380 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555381 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375382 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555383 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375384 r->GetResponseRemoteEndpoint().port());
[email protected]c31a54592009-09-04 02:36:165385
[email protected]9e743cd2010-03-16 07:03:535386 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:525387 }
initial.commit586acc5fe2008-07-26 22:42:525388}
5389
[email protected]263163f2012-06-14 22:40:345390// This test has the server send a large number of cookies to the client.
5391// To ensure that no number of cookies causes a crash, a galloping binary
5392// search is used to estimate that maximum number of cookies that are accepted
5393// by the browser. Beyond the maximum number, the request will fail with
5394// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:315395#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:305396// http://crbug.com/177916
5397#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
5398#else
5399#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
5400#endif // defined(OS_WIN)
5401TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:555402 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:345403
5404 int lower_bound = 0;
5405 int upper_bound = 1;
5406
5407 // Double the number of cookies until the response header limits are
5408 // exceeded.
5409 while (DoManyCookiesRequest(upper_bound)) {
5410 lower_bound = upper_bound;
5411 upper_bound *= 2;
5412 ASSERT_LT(upper_bound, 1000000);
5413 }
5414
pkasting6b68a162014-12-01 22:10:295415 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:345416 if (tolerance < 2)
5417 tolerance = 2;
5418
5419 // Perform a binary search to find the highest possible number of cookies,
5420 // within the desired tolerance.
5421 while (upper_bound - lower_bound >= tolerance) {
5422 int num_cookies = (lower_bound + upper_bound) / 2;
5423
5424 if (DoManyCookiesRequest(num_cookies))
5425 lower_bound = num_cookies;
5426 else
5427 upper_bound = num_cookies;
5428 }
5429 // Success: the test did not crash.
5430}
5431
[email protected]b89290212009-08-14 22:37:355432TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:555433 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115434
initial.commit586acc5fe2008-07-26 22:42:525435 TestDelegate d;
5436 {
Ryan Sleevib8449e02018-07-15 04:31:075437 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165438 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5439 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525440
[email protected]f7022f32014-08-21 16:32:195441 r->Start();
5442 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525443
Wez2a31b222018-06-07 22:07:155444 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525445
5446 EXPECT_EQ(1, d.response_started_count());
5447 EXPECT_FALSE(d.received_data_before_response());
5448 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555449 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375450 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555451 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375452 r->GetResponseRemoteEndpoint().port());
initial.commit586acc5fe2008-07-26 22:42:525453 }
[email protected]5d7b373e2009-09-02 07:19:035454}
5455
[email protected]79e1fd62013-06-20 06:50:045456TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555457 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045458
5459 TestDelegate d;
5460 {
tommycli59a63432015-11-06 00:10:555461 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075462 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165463 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045464
5465 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195466 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045467
[email protected]f7022f32014-08-21 16:32:195468 r->Start();
5469 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045470
Wez2a31b222018-06-07 22:07:155471 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:045472
5473 EXPECT_EQ(1, d.response_started_count());
5474 EXPECT_FALSE(d.received_data_before_response());
5475 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555476 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375477 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555478 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375479 r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:045480
5481 EXPECT_TRUE(d.have_full_request_headers());
5482 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5483 }
5484}
5485
[email protected]58e32bb2013-01-21 18:23:255486TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555487 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255488
5489 TestDelegate d;
5490 {
Ryan Sleevib8449e02018-07-15 04:31:075491 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165492 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5493 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255494
[email protected]f7022f32014-08-21 16:32:195495 r->Start();
5496 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255497
Wez2a31b222018-06-07 22:07:155498 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255499
5500 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195501 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255502 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5503
5504 EXPECT_EQ(1, d.response_started_count());
5505 EXPECT_FALSE(d.received_data_before_response());
5506 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555507 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375508 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555509 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375510 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:255511 }
5512}
5513
tommycli59a63432015-11-06 00:10:555514// TODO(svaldez): Update tests to use EmbeddedTestServer.
5515#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395516TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555517 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555518 base::FilePath(kTestFilePath));
5519
5520 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395521
5522 // Parameter that specifies the Content-Length field in the response:
5523 // C - Compressed length.
5524 // U - Uncompressed length.
5525 // L - Large length (larger than both C & U).
5526 // M - Medium length (between C & U).
5527 // S - Small length (smaller than both C & U).
5528 const char test_parameters[] = "CULMS";
Avi Drissman4365a4782018-12-28 19:26:245529 const int num_tests = base::size(test_parameters) - 1; // Skip NULL.
[email protected]aad63572011-05-24 20:14:395530 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445531 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395532 // S has too little data, but we seem to accept it.
5533 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375534 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395535
xunjielifb4da222016-07-14 18:38:595536 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:195537 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
xunjielifb4da222016-07-14 18:38:595538 file_path = file_path.Append(kTestFilePath);
5539 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5540 std::string expected_content;
5541 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5542
5543 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395544 TestDelegate d;
5545 {
tommycli59a63432015-11-06 00:10:555546 std::string test_file = base::StringPrintf(
5547 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395548
[email protected]ceefd7fd2012-11-29 00:36:245549 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095550 TestURLRequestContext context(true);
5551 context.set_network_delegate(&network_delegate);
5552 context.Init();
[email protected]87a09a92011-07-14 15:50:505553
rhalavatib7bd7c792017-04-27 05:25:165554 std::unique_ptr<URLRequest> r(
5555 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5556 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195557 r->Start();
5558 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395559
Wez2a31b222018-06-07 22:07:155560 d.RunUntilComplete();
[email protected]aad63572011-05-24 20:14:395561
5562 EXPECT_EQ(1, d.response_started_count());
5563 EXPECT_FALSE(d.received_data_before_response());
5564 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505565 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395566 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505567 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5568 << "\"";
xunjielifb4da222016-07-14 18:38:595569 if (test_parameters[i] == 'S') {
5570 // When content length is smaller than both compressed length and
5571 // uncompressed length, HttpStreamParser might not read the full
5572 // response body.
5573 continue;
5574 }
5575 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395576 } else {
maksim.sisovb53724b52016-09-16 05:30:505577 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395578 << " Parameter = \"" << test_file << "\"";
5579 }
5580 }
5581 }
5582}
tommycli59a63432015-11-06 00:10:555583#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395584
[email protected]58e32bb2013-01-21 18:23:255585TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555586 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255587
tommycli59a63432015-11-06 00:10:555588 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455589 GURL original_url =
tommycli59a63432015-11-06 00:10:555590 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255591 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075592 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165593 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195594 req->Start();
Wez2a31b222018-06-07 22:07:155595 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255596
5597 EXPECT_EQ(1, d.response_started_count());
5598 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195599 EXPECT_EQ(destination_url, req->url());
5600 EXPECT_EQ(original_url, req->original_url());
5601 ASSERT_EQ(2U, req->url_chain().size());
5602 EXPECT_EQ(original_url, req->url_chain()[0]);
5603 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255604
5605 LoadTimingInfo load_timing_info_before_redirect;
5606 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5607 &load_timing_info_before_redirect));
5608 TestLoadTimingNotReused(load_timing_info_before_redirect,
5609 CONNECT_TIMING_HAS_DNS_TIMES);
5610
5611 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195612 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255613 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5614
5615 // Check that a new socket was used on redirect, since the server does not
5616 // supposed keep-alive sockets, and that the times before the redirect are
5617 // before the ones recorded for the second request.
5618 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5619 load_timing_info.socket_log_id);
5620 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5621 load_timing_info.connect_timing.connect_start);
5622}
5623
[email protected]8f1ac082011-04-19 21:14:135624TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555625 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135626
tommycli59a63432015-11-06 00:10:555627 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455628 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555629 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5630 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5631 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135632 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075633 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165634 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195635 req->Start();
Wez2a31b222018-06-07 22:07:155636 d.RunUntilComplete();
[email protected]8f1ac082011-04-19 21:14:135637
5638 EXPECT_EQ(1, d.response_started_count());
5639 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195640 EXPECT_EQ(destination_url, req->url());
5641 EXPECT_EQ(original_url, req->original_url());
5642 ASSERT_EQ(3U, req->url_chain().size());
5643 EXPECT_EQ(original_url, req->url_chain()[0]);
5644 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5645 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135646}
5647
David Benjamina7fde612019-03-15 14:20:585648// This is a regression test for https://crbug.com/942073.
5649TEST_F(URLRequestTestHTTP, RedirectEscaping) {
5650 ASSERT_TRUE(http_test_server()->Start());
5651
5652 // Assemble the destination URL as a string so it is not escaped by GURL.
5653 GURL destination_base = http_test_server()->GetURL("/defaultresponse");
5654 // Add a URL fragment of U+2603 unescaped, U+2603 escaped, and then a UTF-8
5655 // encoding error.
5656 std::string destination_url =
5657 destination_base.spec() + "#\xE2\x98\x83_%E2%98%83_\xE0\xE0";
5658 // Redirect resolution should percent-escape bytes and preserve the UTF-8
5659 // error at the end.
5660 std::string destination_escaped =
5661 destination_base.spec() + "#%E2%98%83_%E2%98%83_%E0%E0";
5662 GURL original_url = http_test_server()->GetURL(
5663 "/server-redirect?" + EscapeQueryParamValue(destination_url, false));
5664 TestDelegate d;
5665 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
5666 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5667 req->Start();
5668 d.RunUntilComplete();
5669
5670 EXPECT_EQ(1, d.response_started_count());
5671 EXPECT_EQ(1, d.received_redirect_count());
5672 EXPECT_EQ(destination_escaped, req->url().spec());
5673 EXPECT_EQ(original_url, req->original_url());
5674 ASSERT_EQ(2U, req->url_chain().size());
5675 EXPECT_EQ(original_url, req->url_chain()[0]);
5676 EXPECT_EQ(destination_escaped, req->url_chain()[1].spec());
5677}
5678
[email protected]abe1c4a2013-10-25 19:28:515679// First and second pieces of information logged by delegates to URLRequests.
5680const char kFirstDelegateInfo[] = "Wonderful delegate";
5681const char kSecondDelegateInfo[] = "Exciting delegate";
5682
5683// Logs delegate information to a URLRequest. The first string is logged
5684// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5685// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5686// another asynchronous call is used to clear the delegate information
5687// before calling a callback. The object then deletes itself.
5688class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5689 public:
David Benjamind1f287bf2018-06-12 01:57:205690 using Callback = base::OnceCallback<void()>;
[email protected]abe1c4a2013-10-25 19:28:515691
5692 // Each time delegate information is added to the URLRequest, the resulting
5693 // load state is checked. The expected load state after each request is
5694 // passed in as an argument.
5695 static void Run(URLRequest* url_request,
5696 LoadState expected_first_load_state,
5697 LoadState expected_second_load_state,
5698 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205699 Callback callback) {
tzik38f920a2018-08-01 04:41:205700 // base::MakeRefCounted<AsyncDelegateLogger> is unavailable here, since the
5701 // constructor of AsyncDelegateLogger is private.
5702 auto logger = base::WrapRefCounted(new AsyncDelegateLogger(
David Benjamind1f287bf2018-06-12 01:57:205703 url_request, expected_first_load_state, expected_second_load_state,
tzik38f920a2018-08-01 04:41:205704 expected_third_load_state, std::move(callback)));
[email protected]abe1c4a2013-10-25 19:28:515705 logger->Start();
5706 }
5707
5708 // Checks that the log entries, starting with log_position, contain the
5709 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5710 // recorded. Returns the index of entry after the expected number of
5711 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465712 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515713 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515714 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5715 if (log_position + 3 >= entries.size()) {
5716 ADD_FAILURE() << "Not enough log entries";
5717 return entries.size();
5718 }
5719 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005720 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5721 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075722 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515723 &delegate_info));
5724 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5725
5726 ++log_position;
mikecirone8b85c432016-09-08 19:11:005727 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5728 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515729
5730 ++log_position;
mikecirone8b85c432016-09-08 19:11:005731 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5732 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075733 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515734 &delegate_info));
5735 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5736
5737 ++log_position;
mikecirone8b85c432016-09-08 19:11:005738 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5739 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515740
5741 return log_position + 1;
5742 }
5743
5744 private:
5745 friend class base::RefCounted<AsyncDelegateLogger>;
5746
5747 AsyncDelegateLogger(URLRequest* url_request,
5748 LoadState expected_first_load_state,
5749 LoadState expected_second_load_state,
5750 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205751 Callback callback)
[email protected]abe1c4a2013-10-25 19:28:515752 : url_request_(url_request),
5753 expected_first_load_state_(expected_first_load_state),
5754 expected_second_load_state_(expected_second_load_state),
5755 expected_third_load_state_(expected_third_load_state),
David Benjamind1f287bf2018-06-12 01:57:205756 callback_(std::move(callback)) {}
[email protected]abe1c4a2013-10-25 19:28:515757
Chris Watkins7a41d3552017-12-01 02:13:275758 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515759
5760 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535761 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515762 LoadStateWithParam load_state = url_request_->GetLoadState();
5763 EXPECT_EQ(expected_first_load_state_, load_state.state);
5764 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455765 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155766 FROM_HERE,
5767 base::BindOnce(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515768 }
5769
5770 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535771 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515772 LoadStateWithParam load_state = url_request_->GetLoadState();
5773 EXPECT_EQ(expected_second_load_state_, load_state.state);
5774 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5775 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5776 } else {
5777 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5778 }
skyostil4891b25b2015-06-11 11:43:455779 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155780 FROM_HERE, base::BindOnce(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515781 }
5782
5783 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535784 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515785 LoadStateWithParam load_state = url_request_->GetLoadState();
5786 EXPECT_EQ(expected_third_load_state_, load_state.state);
5787 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085788 EXPECT_EQ(base::string16(), load_state.param);
David Benjamind1f287bf2018-06-12 01:57:205789 std::move(callback_).Run();
[email protected]abe1c4a2013-10-25 19:28:515790 }
5791
5792 URLRequest* url_request_;
5793 const int expected_first_load_state_;
5794 const int expected_second_load_state_;
5795 const int expected_third_load_state_;
David Benjamind1f287bf2018-06-12 01:57:205796 Callback callback_;
[email protected]abe1c4a2013-10-25 19:28:515797
5798 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5799};
5800
5801// NetworkDelegate that logs delegate information before a request is started,
5802// before headers are sent, when headers are read, and when auth information
5803// is requested. Uses AsyncDelegateLogger.
5804class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5805 public:
Chris Watkins7a41d3552017-12-01 02:13:275806 AsyncLoggingNetworkDelegate() = default;
5807 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515808
5809 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205810 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205811 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:205812 GURL* new_url) override {
David Benjamind1f287bf2018-06-12 01:57:205813 // TestNetworkDelegate always completes synchronously.
5814 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
5815 request, base::NullCallback(), new_url));
5816 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515817 }
5818
ryansturm2343cb62016-06-15 01:09:005819 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205820 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:005821 HttpRequestHeaders* headers) override {
David Benjamind1f287bf2018-06-12 01:57:205822 // TestNetworkDelegate always completes synchronously.
5823 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
5824 request, base::NullCallback(), headers));
5825 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515826 }
5827
dchengb03027d2014-10-21 12:00:205828 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515829 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205830 CompletionOnceCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515831 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165832 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135833 GURL* allowed_unsafe_redirect_url) override {
David Benjamind1f287bf2018-06-12 01:57:205834 // TestNetworkDelegate always completes synchronously.
5835 CHECK_NE(ERR_IO_PENDING,
5836 TestNetworkDelegate::OnHeadersReceived(
5837 request, base::NullCallback(), original_response_headers,
5838 override_response_headers, allowed_unsafe_redirect_url));
5839 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515840 }
5841
dchengb03027d2014-10-21 12:00:205842 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515843 URLRequest* request,
5844 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:205845 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:135846 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515847 AsyncDelegateLogger::Run(
David Benjamind1f287bf2018-06-12 01:57:205848 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5849 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5850 base::BindOnce(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5851 std::move(callback), credentials));
[email protected]abe1c4a2013-10-25 19:28:515852 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5853 }
5854
5855 private:
David Benjamind1f287bf2018-06-12 01:57:205856 static int RunCallbackAsynchronously(URLRequest* request,
5857 CompletionOnceCallback callback) {
5858 AsyncDelegateLogger::Run(request, LOAD_STATE_WAITING_FOR_DELEGATE,
5859 LOAD_STATE_WAITING_FOR_DELEGATE,
5860 LOAD_STATE_WAITING_FOR_DELEGATE,
5861 base::BindOnce(std::move(callback), OK));
[email protected]abe1c4a2013-10-25 19:28:515862 return ERR_IO_PENDING;
5863 }
5864
David Benjamind1f287bf2018-06-12 01:57:205865 static void SetAuthAndResume(AuthCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515866 AuthCredentials* credentials) {
5867 *credentials = AuthCredentials(kUser, kSecret);
David Benjamind1f287bf2018-06-12 01:57:205868 std::move(callback).Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
[email protected]abe1c4a2013-10-25 19:28:515869 }
5870
5871 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5872};
5873
5874// URLRequest::Delegate that logs delegate information when the headers
5875// are received, when each read completes, and during redirects. Uses
5876// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5877//
5878// Inherits from TestDelegate to reuse the TestDelegate code to handle
5879// advancing to the next step in most cases, as well as cancellation.
5880class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5881 public:
5882 enum CancelStage {
5883 NO_CANCEL = 0,
5884 CANCEL_ON_RECEIVED_REDIRECT,
5885 CANCEL_ON_RESPONSE_STARTED,
5886 CANCEL_ON_READ_COMPLETED
5887 };
5888
5889 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5890 : cancel_stage_(cancel_stage) {
5891 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5892 set_cancel_in_received_redirect(true);
5893 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5894 set_cancel_in_response_started(true);
5895 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5896 set_cancel_in_received_data(true);
5897 }
Chris Watkins7a41d3552017-12-01 02:13:275898 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515899
5900 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205901 void OnReceivedRedirect(URLRequest* request,
5902 const RedirectInfo& redirect_info,
5903 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515904 *defer_redirect = true;
5905 AsyncDelegateLogger::Run(
5906 request,
5907 LOAD_STATE_WAITING_FOR_DELEGATE,
5908 LOAD_STATE_WAITING_FOR_DELEGATE,
5909 LOAD_STATE_WAITING_FOR_DELEGATE,
5910 base::Bind(
5911 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595912 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515913 }
5914
maksim.sisov0f4aa142016-09-05 05:55:285915 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515916 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285917 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5918 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5919 base::Bind(
5920 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5921 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515922 }
5923
dchengb03027d2014-10-21 12:00:205924 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515925 AsyncDelegateLogger::Run(
5926 request,
5927 LOAD_STATE_IDLE,
5928 LOAD_STATE_IDLE,
5929 LOAD_STATE_IDLE,
5930 base::Bind(
5931 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5932 base::Unretained(this), request, bytes_read));
5933 }
5934
5935 private:
5936 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595937 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515938 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595939 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515940 // FollowDeferredRedirect should not be called after cancellation.
5941 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5942 return;
Arthur Sonzognib8465ff72019-01-04 18:44:355943 if (!defer_redirect) {
5944 request->FollowDeferredRedirect(base::nullopt /* removed_headers */,
5945 base::nullopt /* modified_headers */);
5946 }
[email protected]abe1c4a2013-10-25 19:28:515947 }
5948
maksim.sisov0f4aa142016-09-05 05:55:285949 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515950 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285951 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515952 }
5953
5954 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5955 // The parent class continues the request.
5956 TestDelegate::OnReadCompleted(request, bytes_read);
5957 }
5958
5959 const CancelStage cancel_stage_;
5960
5961 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5962};
5963
5964// Tests handling of delegate info before a request starts.
5965TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555966 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515967
5968 TestDelegate request_delegate;
5969 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:355970 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:515971 context.set_net_log(&net_log_);
5972 context.Init();
5973
5974 {
rhalavatib7bd7c792017-04-27 05:25:165975 std::unique_ptr<URLRequest> r(context.CreateRequest(
5976 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5977 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195978 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515979 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085980 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515981
5982 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195983 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515984 LOAD_STATE_WAITING_FOR_DELEGATE,
5985 LOAD_STATE_WAITING_FOR_DELEGATE,
5986 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195987 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515988
Wez2a31b222018-06-07 22:07:155989 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515990
[email protected]f7022f32014-08-21 16:32:195991 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505992 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515993 }
5994
mmenke43758e62015-05-04 21:09:465995 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515996 net_log_.GetEntries(&entries);
5997 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005998 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515999
6000 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
6001
6002 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:006003 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6004 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516005}
6006
6007// Tests handling of delegate info from a network delegate.
6008TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:556009 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516010
6011 TestDelegate request_delegate;
6012 AsyncLoggingNetworkDelegate network_delegate;
6013 TestURLRequestContext context(true);
6014 context.set_network_delegate(&network_delegate);
6015 context.set_net_log(&net_log_);
6016 context.Init();
6017
6018 {
rhalavatib7bd7c792017-04-27 05:25:166019 std::unique_ptr<URLRequest> r(context.CreateRequest(
6020 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
6021 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196022 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516023 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086024 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516025
[email protected]f7022f32014-08-21 16:32:196026 r->Start();
Wez2a31b222018-06-07 22:07:156027 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516028
[email protected]f7022f32014-08-21 16:32:196029 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506030 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516031 EXPECT_EQ(1, network_delegate.created_requests());
6032 EXPECT_EQ(0, network_delegate.destroyed_requests());
6033 }
6034 EXPECT_EQ(1, network_delegate.destroyed_requests());
6035
6036 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466037 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516038 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:156039 static const NetLogEventType kExpectedEvents[] = {
6040 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6041 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6042 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6043 };
6044 for (NetLogEventType event : kExpectedEvents) {
6045 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516046 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156047 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516048
6049 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6050 log_position + 1);
6051
6052 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156053 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006054 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516055 }
6056
mikecirone8b85c432016-09-08 19:11:006057 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6058 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516059}
6060
6061// Tests handling of delegate info from a network delegate in the case of an
6062// HTTP redirect.
6063TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:556064 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516065
6066 TestDelegate request_delegate;
6067 AsyncLoggingNetworkDelegate network_delegate;
6068 TestURLRequestContext context(true);
6069 context.set_network_delegate(&network_delegate);
6070 context.set_net_log(&net_log_);
6071 context.Init();
6072
6073 {
danakj8522a25b2016-04-16 00:17:366074 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556075 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166076 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196077 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516078 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086079 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516080
[email protected]f7022f32014-08-21 16:32:196081 r->Start();
Wez2a31b222018-06-07 22:07:156082 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516083
[email protected]f7022f32014-08-21 16:32:196084 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506085 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516086 EXPECT_EQ(2, network_delegate.created_requests());
6087 EXPECT_EQ(0, network_delegate.destroyed_requests());
6088 }
6089 EXPECT_EQ(1, network_delegate.destroyed_requests());
6090
6091 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466092 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516093 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:156094 static const NetLogEventType kExpectedEvents[] = {
6095 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6096 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6097 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6098 };
6099 for (NetLogEventType event : kExpectedEvents) {
6100 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516101 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156102 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516103
David Benjamin9776ca22018-06-13 00:00:156104 log_position =
6105 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516106
6107 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156108 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006109 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516110 }
6111
6112 // The URLRequest::Delegate then gets informed about the redirect.
6113 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156114 entries, log_position + 1,
6115 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
mikecirone8b85c432016-09-08 19:11:006116 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516117
6118 // The NetworkDelegate logged information in the same three events as before.
David Benjamin9776ca22018-06-13 00:00:156119 for (NetLogEventType event : kExpectedEvents) {
6120 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516121 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156122 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516123
6124 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6125 log_position + 1);
6126
6127 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156128 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006129 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516130 }
6131
mikecirone8b85c432016-09-08 19:11:006132 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6133 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516134}
6135
6136// Tests handling of delegate info from a network delegate in the case of HTTP
6137// AUTH.
6138TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:556139 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516140
6141 TestDelegate request_delegate;
6142 AsyncLoggingNetworkDelegate network_delegate;
6143 TestURLRequestContext context(true);
6144 context.set_network_delegate(&network_delegate);
6145 context.set_net_log(&net_log_);
6146 context.Init();
6147
6148 {
rhalavatib7bd7c792017-04-27 05:25:166149 std::unique_ptr<URLRequest> r(context.CreateRequest(
6150 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
6151 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196152 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516153 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086154 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516155
[email protected]f7022f32014-08-21 16:32:196156 r->Start();
Wez2a31b222018-06-07 22:07:156157 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516158
[email protected]f7022f32014-08-21 16:32:196159 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506160 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516161 EXPECT_EQ(1, network_delegate.created_requests());
6162 EXPECT_EQ(0, network_delegate.destroyed_requests());
6163 }
6164 EXPECT_EQ(1, network_delegate.destroyed_requests());
6165
6166 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466167 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516168 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:156169 static const NetLogEventType kExpectedEvents[] = {
6170 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6171 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6172 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6173 NetLogEventType::NETWORK_DELEGATE_AUTH_REQUIRED,
6174 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6175 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6176 };
6177 for (NetLogEventType event : kExpectedEvents) {
6178 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516179 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156180 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516181
David Benjamin9776ca22018-06-13 00:00:156182 log_position =
6183 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516184
6185 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156186 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006187 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516188 }
6189
mikecirone8b85c432016-09-08 19:11:006190 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6191 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516192}
6193
tommycli59a63432015-11-06 00:10:556194// TODO(svaldez): Update tests to use EmbeddedTestServer.
6195#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516196// Tests handling of delegate info from a URLRequest::Delegate.
6197TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:556198 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:556199 base::FilePath(kTestFilePath));
6200
6201 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:516202
6203 AsyncLoggingUrlRequestDelegate request_delegate(
6204 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6205 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356206 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516207 context.set_net_log(&net_log_);
6208 context.Init();
6209
6210 {
6211 // A chunked response with delays between chunks is used to make sure that
6212 // attempts by the URLRequest delegate to log information while reading the
6213 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:486214 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:516215 // that it occurs.
danakj8522a25b2016-04-16 00:17:366216 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556217 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166218 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196219 LoadStateWithParam load_state = r->GetLoadState();
6220 r->Start();
Wez2a31b222018-06-07 22:07:156221 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516222
[email protected]f7022f32014-08-21 16:32:196223 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506224 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516225 }
6226
mmenke43758e62015-05-04 21:09:466227 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516228 net_log_.GetEntries(&entries);
6229
[email protected]1826a402014-01-08 15:40:486230 size_t log_position = 0;
6231
[email protected]abe1c4a2013-10-25 19:28:516232 // The delegate info should only have been logged on header complete. Other
6233 // times it should silently be ignored.
David Benjamin9776ca22018-06-13 00:00:156234 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
6235 entries, 0, NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST));
mikecirone8b85c432016-09-08 19:11:006236 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156237 entries, log_position + 1,
6238 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
mikecirone8b85c432016-09-08 19:11:006239 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516240
David Benjamin9776ca22018-06-13 00:00:156241 log_position =
6242 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516243
6244 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156245 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6246 entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006247 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516248
mikecirone8b85c432016-09-08 19:11:006249 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6250 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516251 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
David Benjamin9776ca22018-06-13 00:00:156252 entries, log_position + 1,
6253 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED));
[email protected]abe1c4a2013-10-25 19:28:516254}
tommycli59a63432015-11-06 00:10:556255#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516256
6257// Tests handling of delegate info from a URLRequest::Delegate in the case of
6258// an HTTP redirect.
6259TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:556260 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516261
6262 AsyncLoggingUrlRequestDelegate request_delegate(
6263 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6264 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356265 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516266 context.set_net_log(&net_log_);
6267 context.Init();
6268
6269 {
danakj8522a25b2016-04-16 00:17:366270 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556271 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166272 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196273 LoadStateWithParam load_state = r->GetLoadState();
6274 r->Start();
Wez2a31b222018-06-07 22:07:156275 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516276
[email protected]f7022f32014-08-21 16:32:196277 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506278 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516279 }
6280
mmenke43758e62015-05-04 21:09:466281 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516282 net_log_.GetEntries(&entries);
6283
6284 // Delegate info should only have been logged in OnReceivedRedirect and
6285 // OnResponseStarted.
6286 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156287 static const NetLogEventType kExpectedEvents[] = {
6288 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6289 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6290 };
6291 for (NetLogEventType event : kExpectedEvents) {
6292 SCOPED_TRACE(NetLog::EventTypeToString(event));
6293 log_position = ExpectLogContainsSomewhereAfter(entries, log_position, event,
6294 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516295
David Benjamin9776ca22018-06-13 00:00:156296 log_position =
6297 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516298
6299 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156300 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006301 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516302 }
6303
mikecirone8b85c432016-09-08 19:11:006304 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6305 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516306}
6307
6308// Tests handling of delegate info from a URLRequest::Delegate in the case of
6309// an HTTP redirect, with cancellation at various points.
6310TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:556311 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516312
6313 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
6314 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
6315 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
6316 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
6317 };
6318
David Benjamin9776ca22018-06-13 00:00:156319 for (auto cancel_stage : kCancelStages) {
6320 AsyncLoggingUrlRequestDelegate request_delegate(cancel_stage);
vishal.b62985ca92015-04-17 08:45:516321 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046322 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356323 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516324 context.set_net_log(&net_log);
6325 context.Init();
6326
6327 {
danakj8522a25b2016-04-16 00:17:366328 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556329 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166330 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196331 LoadStateWithParam load_state = r->GetLoadState();
6332 r->Start();
Wez2a31b222018-06-07 22:07:156333 request_delegate.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506334 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
Wez2a31b222018-06-07 22:07:156335
6336 // Spin the message loop to run AsyncDelegateLogger task(s) posted after
6337 // the |request_delegate| completion task.
6338 base::RunLoop().RunUntilIdle();
[email protected]abe1c4a2013-10-25 19:28:516339 }
6340
mmenke43758e62015-05-04 21:09:466341 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516342 net_log.GetEntries(&entries);
6343
6344 // Delegate info is always logged in both OnReceivedRedirect and
6345 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6346 // OnResponseStarted delegate call is after cancellation, but logging is
6347 // still currently supported in that call.
6348 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156349 static const NetLogEventType kExpectedEvents[] = {
6350 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6351 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6352 };
6353 for (NetLogEventType event : kExpectedEvents) {
6354 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516355 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156356 entries, log_position, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516357
David Benjamin9776ca22018-06-13 00:00:156358 log_position =
6359 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516360
6361 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156362 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006363 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516364 }
6365
mikecirone8b85c432016-09-08 19:11:006366 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6367 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516368 }
6369}
6370
[email protected]847c0fa92012-11-06 16:37:426371namespace {
6372
6373const char kExtraHeader[] = "Allow-Snafu";
6374const char kExtraValue[] = "fubar";
6375
6376class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206377 void OnReceivedRedirect(URLRequest* request,
6378 const RedirectInfo& redirect_info,
6379 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596380 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426381 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6382 }
6383};
6384
6385} // namespace
6386
6387TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556388 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426389
tommycli59a63432015-11-06 00:10:556390 GURL destination_url =
6391 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6392 GURL original_url =
6393 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426394 RedirectWithAdditionalHeadersDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076395 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166396 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196397 req->Start();
Wez2a31b222018-06-07 22:07:156398 d.RunUntilComplete();
[email protected]847c0fa92012-11-06 16:37:426399
6400 std::string value;
[email protected]f7022f32014-08-21 16:32:196401 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426402 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6403 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196404 EXPECT_FALSE(req->is_pending());
6405 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426406 EXPECT_EQ(kExtraValue, d.data_received());
6407}
6408
[email protected]251a1b92012-11-13 11:01:096409namespace {
6410
6411const char kExtraHeaderToRemove[] = "To-Be-Removed";
6412
6413class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206414 void OnReceivedRedirect(URLRequest* request,
6415 const RedirectInfo& redirect_info,
6416 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596417 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096418 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6419 }
6420};
6421
6422} // namespace
6423
6424TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556425 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096426
tommycli59a63432015-11-06 00:10:556427 GURL destination_url = http_test_server()->GetURL(
6428 "/echoheader?" + std::string(kExtraHeaderToRemove));
6429 GURL original_url =
6430 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096431 RedirectWithHeaderRemovalDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076432 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166433 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196434 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6435 req->Start();
Wez2a31b222018-06-07 22:07:156436 d.RunUntilComplete();
[email protected]251a1b92012-11-13 11:01:096437
6438 std::string value;
[email protected]f7022f32014-08-21 16:32:196439 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096440 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196441 EXPECT_FALSE(req->is_pending());
6442 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096443 EXPECT_EQ("None", d.data_received());
6444}
6445
mmenke94f1bd92016-12-07 21:13:056446TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446447 TestDelegate d;
6448 {
Ryan Sleevib8449e02018-07-15 04:31:076449 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166450 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6451 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446452
[email protected]f7022f32014-08-21 16:32:196453 r->Start();
6454 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446455
[email protected]f7022f32014-08-21 16:32:196456 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446457
Wez2a31b222018-06-07 22:07:156458 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446459
6460 // We expect to receive OnResponseStarted even though the request has been
6461 // cancelled.
6462 EXPECT_EQ(1, d.response_started_count());
6463 EXPECT_EQ(0, d.bytes_received());
6464 EXPECT_FALSE(d.received_data_before_response());
6465 }
6466}
6467
mmenke94f1bd92016-12-07 21:13:056468TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556469 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446470
6471 TestDelegate d;
6472 {
Ryan Sleevib8449e02018-07-15 04:31:076473 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166474 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6475 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446476
6477 d.set_cancel_in_response_started(true);
6478
[email protected]f7022f32014-08-21 16:32:196479 r->Start();
6480 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446481
Wez2a31b222018-06-07 22:07:156482 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446483
6484 EXPECT_EQ(1, d.response_started_count());
6485 EXPECT_EQ(0, d.bytes_received());
6486 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506487 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446488 }
6489}
6490
mmenke94f1bd92016-12-07 21:13:056491TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556492 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446493
6494 TestDelegate d;
6495 {
Ryan Sleevib8449e02018-07-15 04:31:076496 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166497 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6498 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056499
6500 d.set_cancel_in_received_data(true);
6501
6502 r->Start();
6503 EXPECT_TRUE(r->is_pending());
6504
Wez2a31b222018-06-07 22:07:156505 d.RunUntilComplete();
mmenke94f1bd92016-12-07 21:13:056506
6507 EXPECT_EQ(1, d.response_started_count());
6508 EXPECT_NE(0, d.received_bytes_count());
6509 EXPECT_FALSE(d.received_data_before_response());
6510 EXPECT_EQ(ERR_ABORTED, d.request_status());
6511 }
6512}
6513
6514TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6515 ASSERT_TRUE(http_test_server()->Start());
6516
6517 TestDelegate d;
6518 {
6519 // This returns an empty response (With headers).
Ryan Sleevib8449e02018-07-15 04:31:076520 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166521 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6522 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446523
6524 d.set_cancel_in_received_data(true);
6525
[email protected]f7022f32014-08-21 16:32:196526 r->Start();
6527 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446528
Wez2a31b222018-06-07 22:07:156529 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446530
6531 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056532 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446533 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506534 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446535 }
6536}
6537
mmenke94f1bd92016-12-07 21:13:056538TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556539 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446540
6541 TestDelegate d;
6542 {
Ryan Sleevib8449e02018-07-15 04:31:076543 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166544 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6545 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446546
[email protected]f7022f32014-08-21 16:32:196547 r->Start();
6548 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446549
6550 // The request will be implicitly canceled when it is destroyed. The
6551 // test delegate must not post a quit message when this happens because
6552 // this test doesn't actually have a message loop. The quit message would
6553 // get put on this thread's message queue and the next test would exit
6554 // early, causing problems.
Wez0e717112018-06-18 23:09:226555 d.set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:446556 }
6557 // expect things to just cleanup properly.
6558
kimwjdalsl2bb4ff02015-12-16 22:06:026559 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446560 // message loop
6561 EXPECT_FALSE(d.received_data_before_response());
6562 EXPECT_EQ(0, d.bytes_received());
6563}
6564
mmenke94f1bd92016-12-07 21:13:056565TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556566 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446567
6568 // populate cache
6569 {
6570 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076571 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166572 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6573 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196574 r->Start();
Wez2a31b222018-06-07 22:07:156575 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506576 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446577 }
6578
6579 // cancel read from cache (see bug 990242)
6580 {
6581 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076582 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166583 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6584 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196585 r->Start();
6586 r->Cancel();
Wez2a31b222018-06-07 22:07:156587 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446588
maksim.sisovb53724b52016-09-16 05:30:506589 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446590 EXPECT_EQ(1, d.response_started_count());
6591 EXPECT_EQ(0, d.bytes_received());
6592 EXPECT_FALSE(d.received_data_before_response());
6593 }
6594}
6595
6596TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556597 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446598 HTTPUploadDataOperationTest("POST");
6599}
6600
6601TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556602 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446603 HTTPUploadDataOperationTest("PUT");
6604}
6605
6606TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556607 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446608
6609 TestDelegate d;
6610 {
Ryan Sleevib8449e02018-07-15 04:31:076611 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166612 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6613 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196614 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446615
[email protected]f7022f32014-08-21 16:32:196616 r->Start();
6617 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446618
Wez2a31b222018-06-07 22:07:156619 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446620
maksim.sisovb53724b52016-09-16 05:30:506621 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6622 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446623
6624 EXPECT_FALSE(d.received_data_before_response());
6625 EXPECT_TRUE(d.data_received().empty());
6626 }
6627}
6628
6629TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556630 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446631
6632 TestDelegate d;
6633 {
Ryan Sleevib8449e02018-07-15 04:31:076634 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166635 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6636 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196637 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446638
[email protected]6cdfd7f2013-02-08 20:40:156639 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196640 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026641 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446642
danakj8522a25b2016-04-16 00:17:366643 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446644
[email protected]6cdfd7f2013-02-08 20:40:156645 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196646 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476647 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446648 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196649 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146650 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076651 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046652 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6653 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446654
[email protected]f7022f32014-08-21 16:32:196655 r->Start();
6656 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446657
Wez2a31b222018-06-07 22:07:156658 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446659
avibf0746c2015-12-09 19:53:146660 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296661 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6662 ASSERT_LE(size64, std::numeric_limits<int>::max());
6663 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366664 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446665
[email protected]7600d0b2013-12-08 21:43:306666 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446667
maksim.sisovb53724b52016-09-16 05:30:506668 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6669 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446670
6671 EXPECT_FALSE(d.received_data_before_response());
6672
[email protected]329b68b2012-11-14 17:54:276673 EXPECT_EQ(size, d.bytes_received());
6674 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446675 }
6676}
6677
[email protected]999dd8c2013-11-12 06:45:546678TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556679 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546680
6681 TestDelegate d;
6682 {
Ryan Sleevib8449e02018-07-15 04:31:076683 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166684 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6685 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196686 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546687
danakj8522a25b2016-04-16 00:17:366688 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546689
Jeremy Roman0579ed62017-08-29 15:56:196690 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456691 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546692 base::FilePath(FILE_PATH_LITERAL(
6693 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076694 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046695 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6696 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546697
[email protected]f7022f32014-08-21 16:32:196698 r->Start();
6699 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546700
Wez2a31b222018-06-07 22:07:156701 d.RunUntilComplete();
[email protected]999dd8c2013-11-12 06:45:546702
[email protected]999dd8c2013-11-12 06:45:546703 EXPECT_TRUE(d.request_failed());
6704 EXPECT_FALSE(d.received_data_before_response());
6705 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506706 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546707 }
6708}
6709
mmenke56b0cbb912016-03-28 21:34:536710namespace {
6711
6712// Adds a standard set of data to an upload for chunked upload integration
6713// tests.
6714void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6715 writer->AppendData("a", 1, false);
6716 writer->AppendData("bcd", 3, false);
6717 writer->AppendData("this is a longer chunk than before.", 35, false);
6718 writer->AppendData("\r\n\r\n", 4, false);
6719 writer->AppendData("0", 1, false);
6720 writer->AppendData("2323", 4, true);
6721}
6722
6723// Checks that the upload data added in AddChunksToUpload() was echoed back from
6724// the server.
6725void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6726 // This should match the chunks sent by AddChunksToUpload().
6727 const std::string expected_data =
6728 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6729
maksim.sisovb53724b52016-09-16 05:30:506730 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6731 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536732
6733 EXPECT_FALSE(d->received_data_before_response());
6734
6735 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6736 EXPECT_EQ(expected_data, d->data_received());
6737}
6738
6739} // namespace
6740
[email protected]316c1e5e2012-09-12 15:17:446741TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556742 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446743
6744 TestDelegate d;
6745 {
Ryan Sleevib8449e02018-07-15 04:31:076746 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166747 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6748 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366749 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536750 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366751 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536752 upload_data_stream->CreateWriter();
6753 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196754 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536755 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196756 r->Start();
6757 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446758
Wez2a31b222018-06-07 22:07:156759 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446760
[email protected]f7022f32014-08-21 16:32:196761 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446762 }
6763}
6764
[email protected]329b68b2012-11-14 17:54:276765TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556766 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276767
6768 TestDelegate d;
6769 {
Ryan Sleevib8449e02018-07-15 04:31:076770 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166771 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6772 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366773 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536774 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366775 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536776 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046777 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196778 r->set_method("POST");
6779 r->Start();
6780 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536781 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156782 d.RunUntilComplete();
[email protected]329b68b2012-11-14 17:54:276783
[email protected]f7022f32014-08-21 16:32:196784 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276785 }
6786}
6787
Asanka Herathf05753e2018-08-16 17:38:206788TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556789 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446790
6791 TestDelegate d;
6792 {
Ryan Sleevib8449e02018-07-15 04:31:076793 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166794 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6795 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366796 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536797 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366798 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536799 upload_data_stream->CreateWriter();
6800 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196801 r->set_method("POST");
6802 r->Start();
6803 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446804
Asanka Herathf05753e2018-08-16 17:38:206805 // Pump messages until we start sending headers..
[email protected]255620da2013-08-19 13:14:296806 base::RunLoop().RunUntilIdle();
Asanka Herathf05753e2018-08-16 17:38:206807
6808 // And now wait for completion.
6809 base::RunLoop run_loop;
6810 d.set_on_complete(run_loop.QuitClosure());
mmenke56b0cbb912016-03-28 21:34:536811 AddDataToUpload(writer.get());
Asanka Herathf05753e2018-08-16 17:38:206812 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:446813
[email protected]f7022f32014-08-21 16:32:196814 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446815 }
6816}
6817
6818TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556819 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446820
6821 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076822 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166823 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6824 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196825 req->Start();
Wez2a31b222018-06-07 22:07:156826 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446827
[email protected]f7022f32014-08-21 16:32:196828 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446829
6830 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196831 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446832
6833 std::string header;
6834 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6835 EXPECT_EQ("private", header);
6836
6837 header.clear();
6838 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6839 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6840
6841 // The response has two "X-Multiple-Entries" headers.
6842 // This verfies our output has them concatenated together.
6843 header.clear();
6844 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6845 EXPECT_EQ("a, b", header);
6846}
6847
tommycli59a63432015-11-06 00:10:556848// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6849// security state. (see http://crbug.com/550977).
6850#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466851TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556852 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6853 https_test_server.SetSSLConfig(
6854 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6855 https_test_server.ServeFilesFromSourceDirectory(
6856 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466857 ASSERT_TRUE(https_test_server.Start());
6858
tommycli59a63432015-11-06 00:10:556859 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466860 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076861 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166862 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6863 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196864 request->Start();
Wez2a31b222018-06-07 22:07:156865 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466866
6867 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076868 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406869 TransportSecurityState::STSState sts_state;
6870 TransportSecurityState::PKPState pkp_state;
6871 EXPECT_TRUE(
6872 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6873 EXPECT_FALSE(
6874 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6875 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6876 sts_state.upgrade_mode);
6877 EXPECT_TRUE(sts_state.include_subdomains);
6878 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036879#if defined(OS_ANDROID)
6880 // Android's CertVerifyProc does not (yet) handle pins.
6881#else
martijnc0d6b622015-06-30 19:14:406882 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036883#endif
[email protected]37fd55fb2013-06-29 13:13:276884}
6885
estarka5da76702015-04-09 04:00:166886TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556887 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6888 https_test_server.ServeFilesFromSourceDirectory(
6889 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166890 ASSERT_TRUE(https_test_server.Start());
6891 // Make sure this test fails if the test server is changed to not
6892 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556893 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6894 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166895
6896 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076897 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166898 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6899 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166900 request->Start();
Wez2a31b222018-06-07 22:07:156901 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:166902 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076903 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406904 TransportSecurityState::STSState sts_state;
6905 EXPECT_FALSE(
6906 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166907}
6908
estark06e0dac2015-08-07 21:56:016909namespace {
Martijn Croonenb1383da2017-10-11 11:56:356910const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
Matt Mueller230996f12018-10-22 19:39:446911const char kPKPReportUri[] = "http://report-uri.preloaded.test/pkp";
6912const char kPKPHost[] = "with-report-uri-pkp.preloaded.test";
estark06e0dac2015-08-07 21:56:016913} // namespace
6914
Matt Mueller230996f12018-10-22 19:39:446915// Tests that reports get sent on PKP violations when a report-uri is set.
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516916TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
Matt Mueller230996f12018-10-22 19:39:446917 GURL report_uri(kPKPReportUri);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516918 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6919 https_test_server.SetSSLConfig(
6920 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6921 https_test_server.ServeFilesFromSourceDirectory(
6922 base::FilePath(kTestFilePath));
6923 ASSERT_TRUE(https_test_server.Start());
6924
Matt Mueller230996f12018-10-22 19:39:446925 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016926
6927 // Set up a pin for |test_server_hostname|.
6928 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446929 security_state.EnableStaticPinsForTesting();
6930 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016931
6932 MockCertificateReportSender mock_report_sender;
6933 security_state.SetReportSender(&mock_report_sender);
6934
6935 // Set up a MockCertVerifier to trigger a violation of the previously
6936 // set pin.
6937 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6938 ASSERT_TRUE(cert);
6939
6940 MockCertVerifier cert_verifier;
6941 CertVerifyResult verify_result;
6942 verify_result.verified_cert = cert;
6943 verify_result.is_issued_by_known_root = true;
6944 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446945 ASSERT_TRUE(
6946 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016947 verify_result.public_key_hashes.push_back(hash3);
6948 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6949
6950 TestNetworkDelegate network_delegate;
6951 TestURLRequestContext context(true);
6952 context.set_transport_security_state(&security_state);
6953 context.set_network_delegate(&network_delegate);
6954 context.set_cert_verifier(&cert_verifier);
6955 context.Init();
6956
6957 // Now send a request to trigger the violation.
6958 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366959 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446960 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166961 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016962 violating_request->Start();
Wez2a31b222018-06-07 22:07:156963 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016964
6965 // Check that a report was sent.
6966 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6967 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446968 EXPECT_EQ("application/json; charset=utf-8",
6969 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366970 std::unique_ptr<base::Value> value(
Lei Zhanga8b4c5fb2019-02-16 03:02:036971 base::JSONReader::ReadDeprecated(mock_report_sender.latest_report()));
estark06e0dac2015-08-07 21:56:016972 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086973 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016974 base::DictionaryValue* report_dict;
6975 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6976 std::string report_hostname;
6977 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6978 EXPECT_EQ(test_server_hostname, report_hostname);
6979}
6980
Matt Mueller230996f12018-10-22 19:39:446981// Tests that reports do not get sent on requests to static pkp hosts that
6982// don't have pin violations.
6983TEST_F(URLRequestTestHTTP, ProcessPKPWithNoViolation) {
tommycli59a63432015-11-06 00:10:556984 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6985 https_test_server.SetSSLConfig(
6986 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6987 https_test_server.ServeFilesFromSourceDirectory(
6988 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016989 ASSERT_TRUE(https_test_server.Start());
6990
Matt Mueller230996f12018-10-22 19:39:446991 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016992
6993 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446994 security_state.EnableStaticPinsForTesting();
6995 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016996 MockCertificateReportSender mock_report_sender;
6997 security_state.SetReportSender(&mock_report_sender);
6998
Matt Mueller230996f12018-10-22 19:39:446999 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7000 ASSERT_TRUE(cert);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:517001 MockCertVerifier mock_cert_verifier;
Matt Mueller230996f12018-10-22 19:39:447002 CertVerifyResult verify_result;
7003 verify_result.verified_cert = cert;
7004 verify_result.is_issued_by_known_root = true;
7005 HashValue hash;
7006 // The expected value of GoodPin1 used by |test_default::kHSTSSource|.
7007 ASSERT_TRUE(
7008 hash.FromString("sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY="));
7009 verify_result.public_key_hashes.push_back(hash);
7010 mock_cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7011
7012 TestNetworkDelegate network_delegate;
estark06e0dac2015-08-07 21:56:017013 TestURLRequestContext context(true);
7014 context.set_transport_security_state(&security_state);
7015 context.set_network_delegate(&network_delegate);
7016 context.set_cert_verifier(&mock_cert_verifier);
estark06e0dac2015-08-07 21:56:017017 context.Init();
7018
7019 // Now send a request that does not trigger the violation.
7020 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367021 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:447022 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:167023 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:017024 request->Start();
Wez2a31b222018-06-07 22:07:157025 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:017026
Matt Mueller230996f12018-10-22 19:39:447027 // Check that the request succeeded, a report was not sent and the pkp was
7028 // not bypassed.
7029 EXPECT_EQ(OK, d.request_status());
estark06e0dac2015-08-07 21:56:017030 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
7031 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
Matt Mueller230996f12018-10-22 19:39:447032 TransportSecurityState::STSState sts_state;
martijnc0d6b622015-06-30 19:14:407033 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:447034 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
7035 &sts_state, &pkp_state));
7036 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
7037 EXPECT_FALSE(request->ssl_info().pkp_bypassed);
estarka5da76702015-04-09 04:00:167038}
7039
dadriandf302c42016-06-10 18:48:597040TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
7041 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7042 https_test_server.SetSSLConfig(
7043 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7044 https_test_server.ServeFilesFromSourceDirectory(
7045 base::FilePath(kTestFilePath));
7046 ASSERT_TRUE(https_test_server.Start());
7047
7048 // Set up a MockCertVerifier to be a local root that violates the pin
7049 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7050 ASSERT_TRUE(cert);
7051
7052 MockCertVerifier cert_verifier;
7053 CertVerifyResult verify_result;
7054 verify_result.verified_cert = cert;
7055 verify_result.is_issued_by_known_root = false;
7056 HashValue hash;
7057 ASSERT_TRUE(
7058 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
7059 verify_result.public_key_hashes.push_back(hash);
7060 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
dadriandf302c42016-06-10 18:48:597061
Matt Mueller230996f12018-10-22 19:39:447062 std::string test_server_hostname = kPKPHost;
dadriandf302c42016-06-10 18:48:597063
Matt Mueller230996f12018-10-22 19:39:447064 // Set up PKP
dadriandf302c42016-06-10 18:48:597065 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:447066 security_state.EnableStaticPinsForTesting();
7067 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7068 MockCertificateReportSender mock_report_sender;
7069 security_state.SetReportSender(&mock_report_sender);
dadriandf302c42016-06-10 18:48:597070
7071 TestNetworkDelegate network_delegate;
7072 TestURLRequestContext context(true);
7073 context.set_transport_security_state(&security_state);
7074 context.set_network_delegate(&network_delegate);
7075 context.set_cert_verifier(&cert_verifier);
7076 context.Init();
7077
7078 TestDelegate d;
7079 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:447080 https_test_server.GetURL(test_server_hostname, "/simple.html"),
7081 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:597082 request->Start();
Wez2a31b222018-06-07 22:07:157083 d.RunUntilComplete();
dadriandf302c42016-06-10 18:48:597084
Matt Mueller230996f12018-10-22 19:39:447085 // Check that the request succeeded, a report was not sent and the PKP was
7086 // bypassed.
7087 EXPECT_EQ(OK, d.request_status());
7088 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
7089 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
7090 TransportSecurityState::STSState sts_state;
dadriandf302c42016-06-10 18:48:597091 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:447092 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
7093 &sts_state, &pkp_state));
7094 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
dadriandf302c42016-06-10 18:48:597095 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
7096}
7097
[email protected]242d8562012-10-30 21:20:467098TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:557099 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7100 https_test_server.SetSSLConfig(
7101 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7102 https_test_server.ServeFilesFromSourceDirectory(
7103 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:467104 ASSERT_TRUE(https_test_server.Start());
7105
tommycli59a63432015-11-06 00:10:557106 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167107
[email protected]242d8562012-10-30 21:20:467108 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077109 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557110 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167111 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197112 request->Start();
Wez2a31b222018-06-07 22:07:157113 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:467114
7115 // We should have set parameters from the first header, not the second.
7116 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:077117 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:407118 TransportSecurityState::STSState sts_state;
7119 EXPECT_TRUE(
7120 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7121 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7122 sts_state.upgrade_mode);
7123 EXPECT_FALSE(sts_state.include_subdomains);
7124 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:467125}
7126
estark1614475f2016-03-10 03:46:477127// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
7128// called.
7129class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
7130 public:
7131 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:277132 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:477133
7134 void OnExpectCTFailed(const HostPortPair& host_port_pair,
7135 const GURL& report_uri,
estarkae028b462017-06-20 23:25:017136 base::Time expiration,
estarkbf1b52962017-05-05 17:05:257137 const X509Certificate* validated_certificate_chain,
7138 const X509Certificate* served_certificate_chain,
7139 const SignedCertificateTimestampAndStatusList&
7140 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:477141 num_failures_++;
7142 }
7143
7144 uint32_t num_failures() { return num_failures_; }
7145
7146 private:
7147 uint32_t num_failures_;
7148};
7149
Emily Stark627238f2017-11-29 03:29:547150// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:477151// for every certificate.
7152class MockCTPolicyEnforcer : public CTPolicyEnforcer {
7153 public:
7154 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:547155 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:277156 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:477157
Emily Stark627238f2017-11-29 03:29:547158 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:477159 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:237160 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:207161 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:477162 return default_result_;
7163 }
7164
Emily Stark627238f2017-11-29 03:29:547165 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:477166 default_result_ = default_result;
7167 }
7168
7169 private:
Emily Stark627238f2017-11-29 03:29:547170 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:477171};
7172
Emily Stark4cfecf072017-08-08 01:05:517173// Tests that Expect CT headers for the preload list are processed correctly.
7174TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:357175 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7176
estark1614475f2016-03-10 03:46:477177 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7178 https_test_server.SetSSLConfig(
7179 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7180 https_test_server.ServeFilesFromSourceDirectory(
7181 base::FilePath(kTestFilePath));
7182 ASSERT_TRUE(https_test_server.Start());
7183
7184 MockExpectCTReporter reporter;
7185 TransportSecurityState transport_security_state;
7186 transport_security_state.enable_static_expect_ct_ = true;
7187 transport_security_state.SetExpectCTReporter(&reporter);
7188
7189 // Set up a MockCertVerifier to accept the certificate that the server sends.
7190 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7191 ASSERT_TRUE(cert);
7192 MockCertVerifier cert_verifier;
7193 CertVerifyResult verify_result;
7194 verify_result.verified_cert = cert;
7195 verify_result.is_issued_by_known_root = true;
7196 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7197
rsleevi22cae1672016-12-28 01:53:367198 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
7199 // CT violation.
7200 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:477201 MockCTPolicyEnforcer ct_policy_enforcer;
7202 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547203 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:477204
7205 TestNetworkDelegate network_delegate;
7206 // Use a MockHostResolver (which by default maps all hosts to
7207 // 127.0.0.1) so that the request can be sent to a site on the Expect
7208 // CT preload list.
7209 MockHostResolver host_resolver;
7210 TestURLRequestContext context(true);
7211 context.set_host_resolver(&host_resolver);
7212 context.set_transport_security_state(&transport_security_state);
7213 context.set_network_delegate(&network_delegate);
7214 context.set_cert_verifier(&cert_verifier);
7215 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:467216 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:477217 context.Init();
7218
7219 // Now send a request to trigger the violation.
7220 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:517221 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:477222 GURL::Replacements replace_host;
7223 replace_host.SetHostStr(kExpectCTStaticHostname);
7224 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:167225 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
7226 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:477227 violating_request->Start();
Wez2a31b222018-06-07 22:07:157228 d.RunUntilComplete();
estark1614475f2016-03-10 03:46:477229
7230 EXPECT_EQ(1u, reporter.num_failures());
7231}
Emily Stark4cfecf072017-08-08 01:05:517232
7233// Tests that Expect CT HTTP headers are processed correctly.
7234TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
7235 base::test::ScopedFeatureList feature_list;
7236 feature_list.InitAndEnableFeature(
7237 TransportSecurityState::kDynamicExpectCTFeature);
7238
7239 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7240 https_test_server.SetSSLConfig(
7241 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7242 https_test_server.ServeFilesFromSourceDirectory(
7243 base::FilePath(kTestFilePath));
7244 ASSERT_TRUE(https_test_server.Start());
7245
7246 MockExpectCTReporter reporter;
7247 TransportSecurityState transport_security_state;
7248 transport_security_state.SetExpectCTReporter(&reporter);
7249
7250 // Set up a MockCertVerifier to accept the certificate that the server sends.
7251 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7252 ASSERT_TRUE(cert);
7253 MockCertVerifier cert_verifier;
7254 CertVerifyResult verify_result;
7255 verify_result.verified_cert = cert;
7256 verify_result.is_issued_by_known_root = true;
7257 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7258
7259 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7260 // compliance.
7261 DoNothingCTVerifier ct_verifier;
7262 MockCTPolicyEnforcer ct_policy_enforcer;
7263 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547264 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517265
7266 TestNetworkDelegate network_delegate;
7267 // Use a MockHostResolver (which by default maps all hosts to
7268 // 127.0.0.1).
7269 MockHostResolver host_resolver;
7270 TestURLRequestContext context(true);
7271 context.set_host_resolver(&host_resolver);
7272 context.set_transport_security_state(&transport_security_state);
7273 context.set_network_delegate(&network_delegate);
7274 context.set_cert_verifier(&cert_verifier);
7275 context.set_cert_transparency_verifier(&ct_verifier);
7276 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7277 context.Init();
7278
7279 // Now send a request to trigger the header processing.
7280 TestDelegate d;
7281 GURL url = https_test_server.GetURL("/expect-ct-header.html");
7282 std::unique_ptr<URLRequest> request(context.CreateRequest(
7283 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7284 request->Start();
Wez2a31b222018-06-07 22:07:157285 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517286
7287 TransportSecurityState::ExpectCTState state;
7288 ASSERT_TRUE(
7289 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7290 EXPECT_TRUE(state.enforce);
7291 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7292}
7293
7294// Tests that if multiple Expect CT HTTP headers are sent, they are all
7295// processed.
7296TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
7297 base::test::ScopedFeatureList feature_list;
7298 feature_list.InitAndEnableFeature(
7299 TransportSecurityState::kDynamicExpectCTFeature);
7300
7301 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7302 https_test_server.SetSSLConfig(
7303 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7304 https_test_server.ServeFilesFromSourceDirectory(
7305 base::FilePath(kTestFilePath));
7306 ASSERT_TRUE(https_test_server.Start());
7307
7308 MockExpectCTReporter reporter;
7309 TransportSecurityState transport_security_state;
7310 transport_security_state.SetExpectCTReporter(&reporter);
7311
7312 // Set up a MockCertVerifier to accept the certificate that the server sends.
7313 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7314 ASSERT_TRUE(cert);
7315 MockCertVerifier cert_verifier;
7316 CertVerifyResult verify_result;
7317 verify_result.verified_cert = cert;
7318 verify_result.is_issued_by_known_root = true;
7319 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7320
7321 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7322 // compliance.
7323 DoNothingCTVerifier ct_verifier;
7324 MockCTPolicyEnforcer ct_policy_enforcer;
7325 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547326 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517327
7328 TestNetworkDelegate network_delegate;
7329 // Use a MockHostResolver (which by default maps all hosts to
7330 // 127.0.0.1).
7331 MockHostResolver host_resolver;
7332 TestURLRequestContext context(true);
7333 context.set_host_resolver(&host_resolver);
7334 context.set_transport_security_state(&transport_security_state);
7335 context.set_network_delegate(&network_delegate);
7336 context.set_cert_verifier(&cert_verifier);
7337 context.set_cert_transparency_verifier(&ct_verifier);
7338 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7339 context.Init();
7340
7341 // Now send a request to trigger the header processing.
7342 TestDelegate d;
7343 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7344 std::unique_ptr<URLRequest> request(context.CreateRequest(
7345 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7346 request->Start();
Wez2a31b222018-06-07 22:07:157347 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517348
7349 TransportSecurityState::ExpectCTState state;
7350 ASSERT_TRUE(
7351 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7352 EXPECT_TRUE(state.enforce);
7353 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7354}
7355
mmenkefd9d15c2017-06-29 13:45:547356#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477357
Lily Chenfec60d92019-01-24 01:16:427358#if BUILDFLAG(ENABLE_REPORTING)
7359
Lily Chend3930e72019-03-01 19:31:117360TEST_F(URLRequestTestHTTP, NetworkErrorLogging_DontReportIfNetworkNotAccessed) {
7361 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7362 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7363 ASSERT_TRUE(https_test_server.Start());
7364 GURL request_url = https_test_server.GetURL("/cachetime");
7365
7366 TestNetworkErrorLoggingService nel_service;
7367 TestURLRequestContext context(true);
7368 context.set_network_error_logging_service(&nel_service);
7369 context.Init();
7370
7371 // Populate the cache.
7372 TestDelegate d;
7373 std::unique_ptr<URLRequest> request(context.CreateRequest(
7374 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7375 request->Start();
7376 d.RunUntilComplete();
7377
7378 ASSERT_EQ(1u, nel_service.errors().size());
7379 const TestNetworkErrorLoggingService::RequestDetails& error =
7380 nel_service.errors()[0];
7381 EXPECT_EQ(request_url, error.uri);
7382 EXPECT_EQ(200, error.status_code);
7383 EXPECT_EQ(OK, error.type);
7384
7385 request = context.CreateRequest(request_url, DEFAULT_PRIORITY, &d,
7386 TRAFFIC_ANNOTATION_FOR_TESTS);
7387 request->Start();
7388 d.RunUntilComplete();
7389
7390 EXPECT_FALSE(request->response_info().network_accessed);
7391 EXPECT_TRUE(request->response_info().was_cached);
7392 // No additional NEL report was generated.
7393 EXPECT_EQ(1u, nel_service.errors().size());
7394}
7395
Lily Chenfec60d92019-01-24 01:16:427396TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicSuccess) {
7397 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7398 https_test_server.ServeFilesFromSourceDirectory(
7399 base::FilePath(kTestFilePath));
7400 ASSERT_TRUE(https_test_server.Start());
7401 GURL request_url = https_test_server.GetURL("/simple.html");
7402
7403 TestNetworkErrorLoggingService nel_service;
7404 TestURLRequestContext context(true);
7405 context.set_network_error_logging_service(&nel_service);
7406 context.Init();
7407
7408 TestDelegate d;
7409 std::unique_ptr<URLRequest> request(context.CreateRequest(
7410 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7411 request->Start();
7412 d.RunUntilComplete();
7413
7414 ASSERT_EQ(1u, nel_service.errors().size());
7415 const TestNetworkErrorLoggingService::RequestDetails& error =
7416 nel_service.errors()[0];
7417 EXPECT_EQ(request_url, error.uri);
7418 EXPECT_EQ(200, error.status_code);
7419 EXPECT_EQ(OK, error.type);
7420}
7421
7422TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicError) {
7423 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7424 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7425 ASSERT_TRUE(https_test_server.Start());
7426 GURL request_url = https_test_server.GetURL("/close-socket");
7427
7428 TestNetworkErrorLoggingService nel_service;
7429 TestURLRequestContext context(true);
7430 context.set_network_error_logging_service(&nel_service);
7431 context.Init();
7432
7433 TestDelegate d;
7434 std::unique_ptr<URLRequest> request(context.CreateRequest(
7435 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7436 request->Start();
7437 d.RunUntilComplete();
7438
7439 ASSERT_EQ(1u, nel_service.errors().size());
7440 const TestNetworkErrorLoggingService::RequestDetails& error =
7441 nel_service.errors()[0];
7442 EXPECT_EQ(request_url, error.uri);
7443 EXPECT_EQ(0, error.status_code);
7444 EXPECT_EQ(ERR_EMPTY_RESPONSE, error.type);
7445}
7446
7447TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Redirect) {
7448 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7449 https_test_server.ServeFilesFromSourceDirectory(
7450 base::FilePath(kTestFilePath));
7451 ASSERT_TRUE(https_test_server.Start());
7452 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7453 GURL redirect_url = https_test_server.GetURL("/with-headers.html");
7454
7455 TestNetworkErrorLoggingService nel_service;
7456 TestURLRequestContext context(true);
7457 context.set_network_error_logging_service(&nel_service);
7458 context.Init();
7459
7460 TestDelegate d;
7461 std::unique_ptr<URLRequest> request(context.CreateRequest(
7462 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7463 request->Start();
7464 d.RunUntilComplete();
7465
7466 ASSERT_EQ(2u, nel_service.errors().size());
7467 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7468 nel_service.errors()[0];
7469 EXPECT_EQ(request_url, error1.uri);
7470 EXPECT_EQ(302, error1.status_code);
7471 EXPECT_EQ(OK, error1.type);
7472 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7473 nel_service.errors()[1];
7474 EXPECT_EQ(redirect_url, error2.uri);
7475 EXPECT_EQ(200, error2.status_code);
7476 EXPECT_EQ(OK, error2.type);
7477}
7478
Lily Chend3930e72019-03-01 19:31:117479TEST_F(URLRequestTestHTTP, NetworkErrorLogging_RedirectWithoutLocationHeader) {
7480 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7481 https_test_server.ServeFilesFromSourceDirectory(
7482 base::FilePath(kTestFilePath));
7483 ASSERT_TRUE(https_test_server.Start());
7484 GURL request_url = https_test_server.GetURL("/308-without-location-header");
7485
7486 TestNetworkErrorLoggingService nel_service;
7487 TestURLRequestContext context(true);
7488 context.set_network_error_logging_service(&nel_service);
7489 context.Init();
7490
7491 TestDelegate d;
7492 std::unique_ptr<URLRequest> request(context.CreateRequest(
7493 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7494 request->Start();
7495 d.RunUntilComplete();
7496
7497 ASSERT_EQ(1u, nel_service.errors().size());
7498 const TestNetworkErrorLoggingService::RequestDetails& error =
7499 nel_service.errors()[0];
7500 EXPECT_EQ(request_url, error.uri);
7501 EXPECT_EQ(308, error.status_code);
7502 // The body of the response was successfully read.
7503 EXPECT_EQ(OK, error.type);
7504}
7505
Lily Chenfec60d92019-01-24 01:16:427506TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Auth) {
7507 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7508 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7509 ASSERT_TRUE(https_test_server.Start());
7510 GURL request_url = https_test_server.GetURL("/auth-basic");
7511
7512 TestNetworkErrorLoggingService nel_service;
7513 TestURLRequestContext context(true);
7514 context.set_network_error_logging_service(&nel_service);
7515 context.Init();
7516
7517 TestDelegate d;
7518 d.set_credentials(AuthCredentials(kUser, kSecret));
7519 std::unique_ptr<URLRequest> request(context.CreateRequest(
7520 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7521 request->Start();
7522 d.RunUntilComplete();
7523
7524 ASSERT_EQ(2u, nel_service.errors().size());
7525 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7526 nel_service.errors()[0];
7527 EXPECT_EQ(request_url, error1.uri);
7528 EXPECT_EQ(401, error1.status_code);
7529 EXPECT_EQ(OK, error1.type);
7530 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7531 nel_service.errors()[1];
7532 EXPECT_EQ(request_url, error2.uri);
7533 EXPECT_EQ(200, error2.status_code);
7534 EXPECT_EQ(OK, error2.type);
7535}
7536
Lily Chend3930e72019-03-01 19:31:117537TEST_F(URLRequestTestHTTP, NetworkErrorLogging_304Response) {
7538 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7539 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7540 ASSERT_TRUE(https_test_server.Start());
7541 GURL request_url = https_test_server.GetURL("/auth-basic");
7542
7543 TestNetworkErrorLoggingService nel_service;
7544 TestURLRequestContext context(true);
7545 context.set_network_error_logging_service(&nel_service);
7546 context.Init();
7547
7548 // populate the cache
7549 {
7550 TestDelegate d;
7551 d.set_credentials(AuthCredentials(kUser, kSecret));
7552 std::unique_ptr<URLRequest> r(context.CreateRequest(
7553 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7554 r->Start();
7555 d.RunUntilComplete();
7556 }
7557 ASSERT_EQ(2u, nel_service.errors().size());
7558 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7559 nel_service.errors()[0];
7560 EXPECT_EQ(request_url, error1.uri);
7561 EXPECT_EQ(401, error1.status_code);
7562 EXPECT_EQ(OK, error1.type);
7563 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7564 nel_service.errors()[1];
7565 EXPECT_EQ(request_url, error2.uri);
7566 EXPECT_EQ(200, error2.status_code);
7567 EXPECT_EQ(OK, error2.type);
7568
7569 // repeat request with end-to-end validation. since auth-basic results in a
7570 // cachable page, we expect this test to result in a 304. in which case, the
7571 // response should be fetched from the cache.
7572 {
7573 TestDelegate d;
7574 d.set_credentials(AuthCredentials(kUser, kSecret));
7575 std::unique_ptr<URLRequest> r(context.CreateRequest(
7576 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7577 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7578 r->Start();
7579 d.RunUntilComplete();
7580
7581 // Should be the same cached document.
7582 EXPECT_TRUE(r->was_cached());
7583 }
7584 ASSERT_EQ(3u, nel_service.errors().size());
7585 const TestNetworkErrorLoggingService::RequestDetails& error3 =
7586 nel_service.errors()[2];
7587 EXPECT_EQ(request_url, error3.uri);
7588 EXPECT_EQ(304, error3.status_code);
7589 EXPECT_EQ(OK, error3.type);
7590}
7591
7592TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelInResponseStarted) {
Lily Chenfec60d92019-01-24 01:16:427593 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7594 https_test_server.ServeFilesFromSourceDirectory(
7595 base::FilePath(kTestFilePath));
7596 ASSERT_TRUE(https_test_server.Start());
7597 GURL request_url = https_test_server.GetURL("/simple.html");
7598
7599 TestNetworkErrorLoggingService nel_service;
7600 TestURLRequestContext context(true);
7601 context.set_network_error_logging_service(&nel_service);
7602 context.Init();
7603
7604 TestDelegate d;
7605 d.set_cancel_in_response_started(true);
7606 std::unique_ptr<URLRequest> request(context.CreateRequest(
7607 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7608 request->Start();
7609 d.RunUntilComplete();
7610
7611 ASSERT_EQ(1u, nel_service.errors().size());
7612 const TestNetworkErrorLoggingService::RequestDetails& error =
7613 nel_service.errors()[0];
7614 EXPECT_EQ(request_url, error.uri);
7615 EXPECT_EQ(200, error.status_code);
Lily Chend3930e72019-03-01 19:31:117616 // Headers were received and the body should have been read but was not.
7617 EXPECT_EQ(ERR_ABORTED, error.type);
7618}
7619
7620TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelOnDataReceived) {
7621 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7622 https_test_server.ServeFilesFromSourceDirectory(
7623 base::FilePath(kTestFilePath));
7624 ASSERT_TRUE(https_test_server.Start());
7625 GURL request_url = https_test_server.GetURL("/simple.html");
7626
7627 TestNetworkErrorLoggingService nel_service;
7628 TestURLRequestContext context(true);
7629 context.set_network_error_logging_service(&nel_service);
7630 context.Init();
7631
7632 TestDelegate d;
7633 d.set_cancel_in_received_data(true);
7634 std::unique_ptr<URLRequest> request(context.CreateRequest(
7635 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7636 request->Start();
7637 d.RunUntilComplete();
7638
7639 ASSERT_EQ(1u, nel_service.errors().size());
7640 const TestNetworkErrorLoggingService::RequestDetails& error =
7641 nel_service.errors()[0];
7642 EXPECT_EQ(request_url, error.uri);
7643 EXPECT_EQ(200, error.status_code);
7644 // Data was received but the body was not completely read.
7645 EXPECT_EQ(ERR_ABORTED, error.type);
7646}
7647
7648TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelRedirect) {
7649 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7650 https_test_server.ServeFilesFromSourceDirectory(
7651 base::FilePath(kTestFilePath));
7652 ASSERT_TRUE(https_test_server.Start());
7653 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7654
7655 TestNetworkErrorLoggingService nel_service;
7656 TestURLRequestContext context(true);
7657 context.set_network_error_logging_service(&nel_service);
7658 context.Init();
7659
7660 TestDelegate d;
7661 d.set_cancel_in_received_redirect(true);
7662 std::unique_ptr<URLRequest> request(context.CreateRequest(
7663 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7664 request->Start();
7665 d.RunUntilComplete();
7666
7667 ASSERT_EQ(1u, nel_service.errors().size());
7668 const TestNetworkErrorLoggingService::RequestDetails& error =
7669 nel_service.errors()[0];
7670 EXPECT_EQ(request_url, error.uri);
7671 EXPECT_EQ(302, error.status_code);
7672 // A valid HTTP response was received, even though the request was cancelled.
Lily Chenfec60d92019-01-24 01:16:427673 EXPECT_EQ(OK, error.type);
7674}
7675
7676#endif // BUILDFLAG(ENABLE_REPORTING)
7677
[email protected]316c1e5e2012-09-12 15:17:447678TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557679 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447680
7681 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077682 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557683 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167684 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197685 req->Start();
Wez2a31b222018-06-07 22:07:157686 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447687
7688 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197689 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447690 EXPECT_EQ("text/html", mime_type);
7691
7692 std::string charset;
[email protected]f7022f32014-08-21 16:32:197693 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447694 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197695 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447696}
7697
[email protected]02494ec2014-05-07 15:05:297698TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347699 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347700 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347701 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027702 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347703
7704 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507705 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347706}
7707
brettwa1228ebb2016-10-28 03:51:347708#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297709TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7710 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7711 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457712 FileProtocolHandler file_protocol_handler(
7713 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297714 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7715
7716 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507717 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297718}
7719
[email protected]588614c22013-08-16 00:09:027720TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557721 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447722
7723 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077724 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557725 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167726 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197727 req->Start();
Wez2a31b222018-06-07 22:07:157728 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447729
maksim.sisovb53724b52016-09-16 05:30:507730 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307731
7732 // The redirect should have been rejected before reporting it to the caller.
7733 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447734}
brettwa1228ebb2016-10-28 03:51:347735#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447736
[email protected]588614c22013-08-16 00:09:027737TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557738 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027739
7740 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077741 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557742 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167743 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197744 req->Start();
Wez2a31b222018-06-07 22:07:157745 d.RunUntilComplete();
[email protected]588614c22013-08-16 00:09:027746
maksim.sisovb53724b52016-09-16 05:30:507747 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307748
7749 // The redirect should have been rejected before reporting it to the
7750 // caller. See https://crbug.com/723796
7751 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027752}
7753
davidbend894710b2017-06-06 19:28:307754// Test that redirects to invalid URLs are rejected. See
7755// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447756TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557757 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447758
7759 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077760 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557761 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167762 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197763 req->Start();
Wez2a31b222018-06-07 22:07:157764 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447765
davidbend894710b2017-06-06 19:28:307766 EXPECT_EQ(1, d.response_started_count());
7767 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7768
7769 // The redirect should have been rejected before reporting it to the caller.
7770 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447771}
7772
[email protected]e50efea2014-03-24 18:41:007773// Make sure redirects are cached, despite not reading their bodies.
7774TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557775 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007776 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557777 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007778
7779 {
7780 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077781 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167782 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197783 req->Start();
Wez2a31b222018-06-07 22:07:157784 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507785 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007786 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557787 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007788 }
7789
7790 {
7791 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077792 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167793 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197794 req->Start();
Wez0e717112018-06-18 23:09:227795 d.RunUntilRedirect();
[email protected]e50efea2014-03-24 18:41:007796
7797 EXPECT_EQ(1, d.received_redirect_count());
7798 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197799 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007800
Arthur Sonzognib8465ff72019-01-04 18:44:357801 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7802 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157803 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007804 EXPECT_EQ(1, d.received_redirect_count());
7805 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507806 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557807 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007808 }
7809}
7810
7811// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7812// when the headers are read, since the body won't have been read.
7813TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557814 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007815 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557816 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007817
7818 {
7819 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557820 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007821 default_network_delegate_.set_redirect_on_headers_received_url(
7822 redirect_to_url);
7823
7824 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077825 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167826 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197827 req->Start();
Wez2a31b222018-06-07 22:07:157828 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507829 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007830 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197831 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007832 }
7833
7834 {
7835 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077836 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167837 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197838 req->Start();
Wez2a31b222018-06-07 22:07:157839 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007840
maksim.sisovb53724b52016-09-16 05:30:507841 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197842 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007843 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197844 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007845 }
7846}
7847
[email protected]5f714132014-03-26 10:41:167848// Tests that redirection to an unsafe URL is allowed when it has been marked as
7849// safe.
7850TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557851 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167852
7853 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7854 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7855 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7856
7857 TestDelegate d;
7858 {
Ryan Sleevib8449e02018-07-15 04:31:077859 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167860 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7861 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167862
[email protected]f7022f32014-08-21 16:32:197863 r->Start();
Wez2a31b222018-06-07 22:07:157864 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167865
maksim.sisovb53724b52016-09-16 05:30:507866 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197867 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197868 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167869 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7870 }
7871}
7872
7873// Tests that a redirect to a different unsafe URL is blocked, even after adding
7874// some other URL to the whitelist.
7875TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557876 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167877
7878 GURL unsafe_url("data:text/html,something");
7879 GURL different_unsafe_url("data:text/html,something-else");
7880 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7881 default_network_delegate_.set_allowed_unsafe_redirect_url(
7882 different_unsafe_url);
7883
7884 TestDelegate d;
7885 {
Ryan Sleevib8449e02018-07-15 04:31:077886 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167887 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7888 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167889
[email protected]f7022f32014-08-21 16:32:197890 r->Start();
Wez2a31b222018-06-07 22:07:157891 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167892
maksim.sisovb53724b52016-09-16 05:30:507893 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307894
7895 // The redirect should have been rejected before reporting it to the caller.
7896 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167897 }
7898}
7899
[email protected]5f714132014-03-26 10:41:167900// Redirects from an URL with fragment to an unsafe URL with fragment should
7901// be allowed, and the reference fragment of the target URL should be preserved.
7902TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557903 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167904
tommycli59a63432015-11-06 00:10:557905 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167906 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7907 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7908
7909 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7910 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7911
7912 TestDelegate d;
7913 {
Ryan Sleevib8449e02018-07-15 04:31:077914 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167915 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167916
[email protected]f7022f32014-08-21 16:32:197917 r->Start();
Wez2a31b222018-06-07 22:07:157918 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167919
[email protected]f7022f32014-08-21 16:32:197920 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507921 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197922 EXPECT_EQ(original_url, r->original_url());
7923 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167924 }
7925}
7926
7927// When a delegate has specified a safe redirect URL, but it does not match the
7928// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147929TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557930 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167931
tommycli59a63432015-11-06 00:10:557932 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167933 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557934 GURL redirect_url(http_test_server()->GetURL("/target"));
7935 GURL expected_redirect_url(
7936 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167937
7938 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7939 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7940
7941 TestDelegate d;
7942 {
Ryan Sleevib8449e02018-07-15 04:31:077943 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167944 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167945
[email protected]f7022f32014-08-21 16:32:197946 r->Start();
Wez2a31b222018-06-07 22:07:157947 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167948
[email protected]f7022f32014-08-21 16:32:197949 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507950 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197951 EXPECT_EQ(original_url, r->original_url());
7952 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167953 }
7954}
7955
[email protected]f878230e2014-04-03 15:36:147956// When a delegate has specified a safe redirect URL, assume that the redirect
7957// URL should not be changed. In particular, the reference fragment should not
7958// be modified.
7959TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557960 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147961
tommycli59a63432015-11-06 00:10:557962 GURL original_url(
7963 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147964 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7965
7966 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7967 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7968
7969 TestDelegate d;
7970 {
Ryan Sleevib8449e02018-07-15 04:31:077971 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167972 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147973
[email protected]f7022f32014-08-21 16:32:197974 r->Start();
Wez2a31b222018-06-07 22:07:157975 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147976
[email protected]f7022f32014-08-21 16:32:197977 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507978 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197979 EXPECT_EQ(original_url, r->original_url());
7980 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147981 }
7982}
7983
7984// When a URLRequestRedirectJob is created, the redirection must be followed and
7985// the reference fragment of the target URL must not be modified.
7986TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557987 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147988
tommycli59a63432015-11-06 00:10:557989 GURL original_url(
7990 http_test_server()->GetURL("/original#should-not-be-appended"));
7991 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147992
7993 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077994 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167995 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147996
danakj8522a25b2016-04-16 00:17:367997 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197998 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427999 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8000 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:148001
[email protected]f7022f32014-08-21 16:32:198002 r->Start();
Wez2a31b222018-06-07 22:07:158003 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148004
maksim.sisovb53724b52016-09-16 05:30:508005 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198006 EXPECT_EQ(original_url, r->original_url());
8007 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:148008}
8009
lizeb5120f6dc2016-02-19 09:29:448010TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
8011 ASSERT_TRUE(http_test_server()->Start());
8012
8013 const std::string referrer("foobar://totally.legit.referrer");
8014 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078015 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168016 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8017 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:448018 req->SetReferrer(referrer);
8019 req->Start();
Wez2a31b222018-06-07 22:07:158020 d.RunUntilComplete();
lizeb5120f6dc2016-02-19 09:29:448021
8022 EXPECT_EQ(std::string("None"), d.data_received());
8023}
8024
[email protected]316c1e5e2012-09-12 15:17:448025TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:558026 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448027
8028 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078029 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168030 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8031 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198032 req->SetReferrer("http://user:[email protected]/");
8033 req->Start();
Wez2a31b222018-06-07 22:07:158034 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448035
8036 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
8037}
8038
[email protected]99ecf6e2013-04-10 22:46:138039TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:558040 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138041
8042 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078043 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168044 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8045 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198046 req->SetReferrer("http://foo.com/test#fragment");
8047 req->Start();
Wez2a31b222018-06-07 22:07:158048 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138049
8050 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
8051}
8052
8053TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:558054 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138055
8056 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078057 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168058 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8059 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198060 req->SetReferrer("http://foo.com/test#fragment");
8061 req->SetReferrer("");
8062 req->Start();
Wez2a31b222018-06-07 22:07:158063 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138064
8065 EXPECT_EQ(std::string("None"), d.data_received());
8066}
8067
Mike Westfbd44112019-05-08 18:23:378068TEST_F(URLRequestTestHTTP, CapRefererDisabled) {
8069 ASSERT_TRUE(http_test_server()->Start());
8070
8071 // Create a string, and pad it out to ~10k with a very exciting path.
8072 std::string long_referer_header = "http://foo.com/";
8073 long_referer_header.resize(10000, 'a');
8074
8075 // If the feature isn't enabled, a long `referer` will remain long.
8076 TestDelegate d;
8077 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8078 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8079 TRAFFIC_ANNOTATION_FOR_TESTS));
8080 req->SetReferrer(long_referer_header);
8081 req->Start();
8082 d.RunUntilComplete();
8083
8084 EXPECT_EQ(long_referer_header, d.data_received());
8085}
8086
8087TEST_F(URLRequestTestHTTP, CapRefererHeaderLengthEnabled) {
8088 ASSERT_TRUE(http_test_server()->Start());
8089
8090 // Create a string, and pad it out to ~10k with a very exciting path.
8091 std::string long_referer_header = "http://foo.com/";
8092 long_referer_header.resize(10000, 'a');
8093
8094 // If the feature is enabled without params, a `referer` longer than 4096
8095 // bytes will be shortened.
8096 {
8097 TestDelegate d;
8098 base::test::ScopedFeatureList feature_list;
8099 feature_list.InitAndEnableFeature(features::kCapRefererHeaderLength);
8100
8101 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8102 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8103 TRAFFIC_ANNOTATION_FOR_TESTS));
8104 req->SetReferrer(long_referer_header);
8105 req->Start();
8106 d.RunUntilComplete();
8107
8108 EXPECT_EQ("http://foo.com/", d.data_received());
8109 }
8110
8111 // If the feature is enabled with params, they will govern the shortening
8112 // behavior as expected. The following three tests verify behavior for a
8113 // param larger than the referrer length, exactly the same as the string
8114 // length, and shorter than the string length.
8115 {
8116 TestDelegate d;
8117 std::map<std::string, std::string> params;
8118 params["MaxRefererHeaderLength"] =
8119 base::NumberToString(long_referer_header.length() + 1);
8120
8121 base::test::ScopedFeatureList feature_list;
8122 feature_list.InitAndEnableFeatureWithParameters(
8123 features::kCapRefererHeaderLength, params);
8124
8125 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8126 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8127 TRAFFIC_ANNOTATION_FOR_TESTS));
8128 req->SetReferrer(long_referer_header);
8129 req->Start();
8130 d.RunUntilComplete();
8131
8132 EXPECT_EQ(long_referer_header, d.data_received());
8133 }
8134
8135 {
8136 TestDelegate d;
8137 std::map<std::string, std::string> params;
8138 params["MaxRefererHeaderLength"] =
8139 base::NumberToString(long_referer_header.length());
8140
8141 base::test::ScopedFeatureList feature_list;
8142 feature_list.InitAndEnableFeatureWithParameters(
8143 features::kCapRefererHeaderLength, params);
8144
8145 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8146 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8147 TRAFFIC_ANNOTATION_FOR_TESTS));
8148 req->SetReferrer(long_referer_header);
8149 req->Start();
8150 d.RunUntilComplete();
8151
8152 EXPECT_EQ(long_referer_header, d.data_received());
8153 }
8154
8155 {
8156 TestDelegate d;
8157 std::map<std::string, std::string> params;
8158 params["MaxRefererHeaderLength"] =
8159 base::NumberToString(long_referer_header.length() - 1);
8160
8161 base::test::ScopedFeatureList feature_list;
8162 feature_list.InitAndEnableFeatureWithParameters(
8163 features::kCapRefererHeaderLength, params);
8164
8165 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8166 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8167 TRAFFIC_ANNOTATION_FOR_TESTS));
8168 req->SetReferrer(long_referer_header);
8169 req->Start();
8170 d.RunUntilComplete();
8171
8172 EXPECT_EQ("http://foo.com/", d.data_received());
8173 }
8174}
8175
[email protected]316c1e5e2012-09-12 15:17:448176TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:558177 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448178
8179 TestDelegate d;
8180 {
8181 d.set_cancel_in_received_redirect(true);
Ryan Sleevib8449e02018-07-15 04:31:078182 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168183 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8184 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198185 req->Start();
Wez2a31b222018-06-07 22:07:158186 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448187
8188 EXPECT_EQ(1, d.response_started_count());
8189 EXPECT_EQ(0, d.bytes_received());
8190 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508191 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448192 }
8193}
8194
8195TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:558196 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448197
8198 TestDelegate d;
8199 {
tommycli59a63432015-11-06 00:10:558200 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078201 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168202 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048203
[email protected]f7022f32014-08-21 16:32:198204 req->Start();
Wez0e717112018-06-18 23:09:228205 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:448206
8207 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:238208 EXPECT_TRUE(d.have_full_request_headers());
8209 CheckFullRequestHeaders(d.full_request_headers(), test_url);
8210 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:448211
Arthur Sonzognib8465ff72019-01-04 18:44:358212 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8213 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:158214 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448215
8216 EXPECT_EQ(1, d.response_started_count());
8217 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508218 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448219
[email protected]6cdfd7f2013-02-08 20:40:158220 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198221 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478222 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:448223 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8224
8225 std::string contents;
[email protected]82f84b92013-08-30 18:23:508226 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:448227 EXPECT_EQ(contents, d.data_received());
8228 }
8229}
8230
[email protected]79e1fd62013-06-20 06:50:048231TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:558232 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:048233
8234 TestDelegate d;
8235 {
tommycli59a63432015-11-06 00:10:558236 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078237 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168238 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048239
8240 EXPECT_FALSE(d.have_full_request_headers());
8241
[email protected]f7022f32014-08-21 16:32:198242 req->Start();
Wez0e717112018-06-18 23:09:228243 d.RunUntilRedirect();
[email protected]79e1fd62013-06-20 06:50:048244
8245 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:048246
Arthur Sonzognib8465ff72019-01-04 18:44:358247 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8248 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:158249 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:048250
tommycli59a63432015-11-06 00:10:558251 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:048252 EXPECT_EQ(1, d.response_started_count());
8253 EXPECT_TRUE(d.have_full_request_headers());
8254 CheckFullRequestHeaders(d.full_request_headers(), target_url);
8255 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508256 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:048257
8258 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198259 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478260 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:048261 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8262
8263 std::string contents;
[email protected]82f84b92013-08-30 18:23:508264 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:048265 EXPECT_EQ(contents, d.data_received());
8266 }
8267}
8268
Arthur Sonzognib8465ff72019-01-04 18:44:358269TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedHeaders) {
Chong Zhang7607f1f2018-06-01 20:52:208270 ASSERT_TRUE(http_test_server()->Start());
8271
8272 TestDelegate d;
8273 {
Chong Zhang7607f1f2018-06-01 20:52:208274 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078275 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Chong Zhang7607f1f2018-06-01 20:52:208276 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8277
8278 // Set initial headers for the request.
8279 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8280 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8281
8282 req->Start();
Wez0e717112018-06-18 23:09:228283 d.RunUntilRedirect();
Chong Zhang7607f1f2018-06-01 20:52:208284
8285 // Initial request should only have initial headers.
8286 EXPECT_EQ(1, d.received_redirect_count());
8287 EXPECT_TRUE(d.have_full_request_headers());
8288 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8289 std::string sent_value;
8290 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8291 EXPECT_EQ("Value1", sent_value);
8292 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8293 EXPECT_EQ("Value2", sent_value);
8294 EXPECT_FALSE(sent_headers1.GetHeader("Header3", &sent_value));
8295 d.ClearFullRequestHeaders();
8296
8297 // Overwrite Header2 and add Header3.
Arthur Sonzognib8465ff72019-01-04 18:44:358298 net::HttpRequestHeaders modified_headers;
8299 modified_headers.SetHeader("Header2", "");
8300 modified_headers.SetHeader("Header3", "Value3");
Chong Zhang7607f1f2018-06-01 20:52:208301
Arthur Sonzognib8465ff72019-01-04 18:44:358302 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8303 modified_headers);
Wez2a31b222018-06-07 22:07:158304 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:208305
8306 EXPECT_EQ(1, d.response_started_count());
8307 EXPECT_FALSE(d.received_data_before_response());
8308 EXPECT_EQ(OK, d.request_status());
8309
8310 // Redirected request should also have modified headers.
8311 EXPECT_TRUE(d.have_full_request_headers());
8312 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8313 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8314 EXPECT_EQ("Value1", sent_value);
8315 EXPECT_TRUE(sent_headers2.GetHeader("Header2", &sent_value));
8316 EXPECT_EQ("", sent_value);
8317 EXPECT_TRUE(sent_headers2.GetHeader("Header3", &sent_value));
8318 EXPECT_EQ("Value3", sent_value);
8319 }
8320}
8321
Arthur Sonzognib8465ff72019-01-04 18:44:358322TEST_F(URLRequestTestHTTP, DeferredRedirect_RemovedHeaders) {
8323 ASSERT_TRUE(http_test_server()->Start());
8324
8325 TestDelegate d;
8326 {
8327 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
8328 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8329 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8330
8331 // Set initial headers for the request.
8332 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8333 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8334
8335 req->Start();
8336 d.RunUntilRedirect();
8337
8338 // Initial request should have initial headers.
8339 EXPECT_EQ(1, d.received_redirect_count());
8340 EXPECT_TRUE(d.have_full_request_headers());
8341 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8342 std::string sent_value;
8343 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8344 EXPECT_EQ("Value1", sent_value);
8345 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8346 EXPECT_EQ("Value2", sent_value);
8347 d.ClearFullRequestHeaders();
8348
8349 // Keep Header1 and remove Header2.
8350 std::vector<std::string> removed_headers({"Header2"});
8351 req->FollowDeferredRedirect(removed_headers,
8352 base::nullopt /* modified_headers */);
8353 d.RunUntilComplete();
8354
8355 EXPECT_EQ(1, d.response_started_count());
8356 EXPECT_FALSE(d.received_data_before_response());
8357 EXPECT_EQ(OK, d.request_status());
8358
8359 // Redirected request should also have
8360 EXPECT_TRUE(d.have_full_request_headers());
8361 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8362 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8363 EXPECT_EQ("Value1", sent_value);
8364 EXPECT_FALSE(sent_headers2.GetHeader("Header2", &sent_value));
8365 }
8366}
8367
[email protected]316c1e5e2012-09-12 15:17:448368TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:558369 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448370
8371 TestDelegate d;
8372 {
Ryan Sleevib8449e02018-07-15 04:31:078373 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168374 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8375 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198376 req->Start();
Wez0e717112018-06-18 23:09:228377 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:448378
8379 EXPECT_EQ(1, d.received_redirect_count());
8380
[email protected]f7022f32014-08-21 16:32:198381 req->Cancel();
Wez2a31b222018-06-07 22:07:158382 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448383
8384 EXPECT_EQ(1, d.response_started_count());
8385 EXPECT_EQ(0, d.bytes_received());
8386 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508387 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448388 }
8389}
8390
8391TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:558392 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448393
[email protected]3b23a222013-05-15 21:33:258394 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:448395 {
8396 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078397 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558398 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168399 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448400 HttpRequestHeaders headers;
8401 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198402 req->SetExtraRequestHeaders(headers);
8403 req->Start();
Wez2a31b222018-06-07 22:07:158404 d.RunUntilComplete();
[email protected]3b23a222013-05-15 21:33:258405
8406 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198407 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258408 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448409 }
8410
[email protected]3b23a222013-05-15 21:33:258411 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:448412 {
8413 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078414 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558415 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168416 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448417 HttpRequestHeaders headers;
8418 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198419 req->SetExtraRequestHeaders(headers);
8420 req->Start();
Wez2a31b222018-06-07 22:07:158421 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448422
[email protected]f7022f32014-08-21 16:32:198423 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258424
8425 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198426 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258427 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:448428 }
8429
[email protected]3b23a222013-05-15 21:33:258430 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:448431 {
8432 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078433 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558434 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168435 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448436 HttpRequestHeaders headers;
8437 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:198438 req->SetExtraRequestHeaders(headers);
8439 req->Start();
Wez2a31b222018-06-07 22:07:158440 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448441
[email protected]f7022f32014-08-21 16:32:198442 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258443
8444 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198445 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258446 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448447 }
8448}
8449
8450TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:558451 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448452
8453 // populate the cache
8454 {
8455 TestDelegate d;
8456 d.set_credentials(AuthCredentials(kUser, kSecret));
8457
Ryan Sleevib8449e02018-07-15 04:31:078458 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168459 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8460 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198461 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448462
Wez2a31b222018-06-07 22:07:158463 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448464
8465 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8466 }
8467
8468 // repeat request with end-to-end validation. since auth-basic results in a
8469 // cachable page, we expect this test to result in a 304. in which case, the
8470 // response should be fetched from the cache.
8471 {
8472 TestDelegate d;
8473 d.set_credentials(AuthCredentials(kUser, kSecret));
8474
Ryan Sleevib8449e02018-07-15 04:31:078475 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168476 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8477 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198478 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8479 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448480
Wez2a31b222018-06-07 22:07:158481 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448482
8483 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8484
8485 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198486 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:448487 }
8488}
8489
8490// Check that Set-Cookie headers in 401 responses are respected.
8491// http://crbug.com/6450
8492TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:558493 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448494
8495 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:558496 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:448497
8498 // Request a page that will give a 401 containing a Set-Cookie header.
8499 // Verify that when the transaction is restarted, it includes the new cookie.
8500 {
[email protected]ceefd7fd2012-11-29 00:36:248501 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448502 TestURLRequestContext context(true);
8503 context.set_network_delegate(&network_delegate);
8504 context.Init();
8505
8506 TestDelegate d;
8507 d.set_credentials(AuthCredentials(kUser, kSecret));
8508
danakj8522a25b2016-04-16 00:17:368509 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:168510 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
8511 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198512 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448513
Wez2a31b222018-06-07 22:07:158514 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448515
8516 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8517
8518 // Make sure we sent the cookie in the restarted transaction.
8519 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8520 != std::string::npos);
8521 }
8522
8523 // Same test as above, except this time the restart is initiated earlier
8524 // (without user intervention since identity is embedded in the URL).
8525 {
[email protected]ceefd7fd2012-11-29 00:36:248526 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448527 TestURLRequestContext context(true);
8528 context.set_network_delegate(&network_delegate);
8529 context.Init();
8530
8531 TestDelegate d;
8532
8533 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:188534 replacements.SetUsernameStr("user2");
8535 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:448536 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
8537
rhalavatib7bd7c792017-04-27 05:25:168538 std::unique_ptr<URLRequest> r(context.CreateRequest(
8539 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198540 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448541
Wez2a31b222018-06-07 22:07:158542 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448543
8544 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
8545
8546 // Make sure we sent the cookie in the restarted transaction.
8547 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8548 != std::string::npos);
8549 }
8550}
8551
Aaron Tagliaboschi028009e2019-03-07 16:28:068552TEST_F(URLRequestTestHTTP, AuthChallengeWithFilteredCookie) {
8553 ASSERT_TRUE(http_test_server()->Start());
8554
8555 GURL url_requiring_auth = http_test_server()->GetURL(
8556 "/auth-basic?set-cookie-if-not-challenged&set-cookie-if-challenged");
8557
8558 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8559 std::make_unique<TestNetworkDelegate>()); // Must outlive URLRequest.
8560 filtering_network_delegate.SetCookieFilter(
8561 "got_challenged"); // Filter the cookie auth-basic sets
8562 TestURLRequestContext context(true);
8563 context.set_network_delegate(&filtering_network_delegate);
8564 context.Init();
8565
8566 TestDelegate delegate;
8567
8568 delegate.set_credentials(AuthCredentials(kUser, kSecret));
8569
8570 std::unique_ptr<URLRequest> request(
8571 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &delegate,
8572 TRAFFIC_ANNOTATION_FOR_TESTS));
8573 request->Start();
8574
8575 delegate.RunUntilComplete();
8576 EXPECT_THAT(delegate.request_status(), IsOk());
8577
8578 // Make sure the cookie was actually filtered.
8579 EXPECT_EQ(std::string::npos,
8580 delegate.data_received().find("Cookie: got_challenged=true"));
8581 // Make sure it was blocked twice.
8582 EXPECT_EQ(2, filtering_network_delegate.blocked_set_cookie_count());
8583}
8584
[email protected]58e32bb2013-01-21 18:23:258585// Tests that load timing works as expected with auth and the cache.
8586TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:558587 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:258588
8589 // populate the cache
8590 {
8591 TestDelegate d;
8592 d.set_credentials(AuthCredentials(kUser, kSecret));
8593
Ryan Sleevib8449e02018-07-15 04:31:078594 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168595 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8596 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198597 r->Start();
[email protected]58e32bb2013-01-21 18:23:258598
Wez2a31b222018-06-07 22:07:158599 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258600
8601 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8602
8603 LoadTimingInfo load_timing_info_before_auth;
8604 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
8605 &load_timing_info_before_auth));
8606 TestLoadTimingNotReused(load_timing_info_before_auth,
8607 CONNECT_TIMING_HAS_DNS_TIMES);
8608
8609 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198610 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:258611 // The test server does not support keep alive sockets, so the second
8612 // request with auth should use a new socket.
8613 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
8614 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
8615 load_timing_info.socket_log_id);
8616 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
8617 load_timing_info.connect_timing.connect_start);
8618 }
8619
[email protected]3b23a222013-05-15 21:33:258620 // Repeat request with end-to-end validation. Since auth-basic results in a
8621 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258622 // response should be fetched from the cache.
8623 {
8624 TestDelegate d;
8625 d.set_credentials(AuthCredentials(kUser, kSecret));
8626
Ryan Sleevib8449e02018-07-15 04:31:078627 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168628 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8629 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198630 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8631 r->Start();
[email protected]58e32bb2013-01-21 18:23:258632
Wez2a31b222018-06-07 22:07:158633 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258634
8635 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8636
8637 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198638 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258639
[email protected]3b23a222013-05-15 21:33:258640 // Since there was a request that went over the wire, the load timing
8641 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258642 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198643 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258644 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258645 }
8646}
8647
[email protected]316c1e5e2012-09-12 15:17:448648// In this test, we do a POST which the server will 302 redirect.
8649// The subsequent transaction should use GET, and should not send the
8650// Content-Type header.
8651// http://code.google.com/p/chromium/issues/detail?id=843
8652TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558653 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448654
8655 const char kData[] = "hello world";
8656
8657 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078658 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168659 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8660 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198661 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078662 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448663
8664 // Set headers (some of which are specific to the POST).
8665 HttpRequestHeaders headers;
Yeol45b9e0a2018-07-27 02:03:298666 headers.SetHeader("Content-Type",
8667 "multipart/form-data;"
8668 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ");
8669 headers.SetHeader("Accept",
8670 "text/xml,application/xml,application/xhtml+xml,"
8671 "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
8672 headers.SetHeader("Accept-Language", "en-US,en");
8673 headers.SetHeader("Accept-Charset", "ISO-8859-1,*,utf-8");
8674 headers.SetHeader("Content-Length", "11");
8675 headers.SetHeader("Origin", "http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198676 req->SetExtraRequestHeaders(headers);
8677 req->Start();
Wez2a31b222018-06-07 22:07:158678 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448679
8680 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198681 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448682 EXPECT_EQ("text/html", mime_type);
8683
8684 const std::string& data = d.data_received();
8685
8686 // Check that the post-specific headers were stripped:
8687 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8688 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498689 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448690
8691 // These extra request headers should not have been stripped.
8692 EXPECT_TRUE(ContainsString(data, "Accept:"));
8693 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8694 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8695}
8696
jww5fe460ff2015-03-28 00:22:518697// The following tests check that we handle mutating the request for HTTP
8698// redirects as expected.
8699// See https://crbug.com/56373, https://crbug.com/102130, and
8700// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448701
8702TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558703 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448704
tommycli59a63432015-11-06 00:10:558705 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518706 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558707 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448708
8709 HTTPRedirectMethodTest(url, "POST", "GET", true);
8710 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8711 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518712
8713 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8714 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498715 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8716 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8717 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408718 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8719 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448720}
8721
8722TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558723 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448724
tommycli59a63432015-11-06 00:10:558725 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518726 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558727 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448728
8729 HTTPRedirectMethodTest(url, "POST", "GET", true);
8730 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8731 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518732
8733 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8734 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498735 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8736 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8737 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408738 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8739 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448740}
8741
8742TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558743 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448744
tommycli59a63432015-11-06 00:10:558745 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518746 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558747 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448748
8749 HTTPRedirectMethodTest(url, "POST", "GET", true);
8750 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8751 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518752
Alex Clarke1e08882b32017-10-06 14:22:408753 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8754 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8755 std::string());
8756 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8757 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8758 std::string());
jww5fe460ff2015-03-28 00:22:518759 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8760 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408761 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8762 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8763 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8764 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8765 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498766 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8767 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8768 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408769 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
8770 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:448771}
8772
8773TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558774 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448775
tommycli59a63432015-11-06 00:10:558776 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518777 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558778 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448779
8780 HTTPRedirectMethodTest(url, "POST", "POST", true);
8781 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8782 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518783
8784 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8785 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8786 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8787 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408788 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8789 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448790}
8791
[email protected]0a17aab32014-04-24 03:32:378792TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558793 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378794
tommycli59a63432015-11-06 00:10:558795 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518796 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558797 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378798
8799 HTTPRedirectMethodTest(url, "POST", "POST", true);
8800 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8801 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518802
8803 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8804 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8805 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8806 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408807 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8808 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:378809}
8810
8811// Make sure that 308 responses without bodies are not treated as redirects.
8812// Certain legacy apis that pre-date the response code expect this behavior
8813// (Like Google Drive).
8814TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558815 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378816
8817 TestDelegate d;
tommycli59a63432015-11-06 00:10:558818 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378819
Ryan Sleevib8449e02018-07-15 04:31:078820 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168821 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378822
[email protected]f7022f32014-08-21 16:32:198823 request->Start();
Wez2a31b222018-06-07 22:07:158824 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:508825 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378826 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198827 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378828 EXPECT_EQ("This is not a redirect.", d.data_received());
8829}
8830
[email protected]f878230e2014-04-03 15:36:148831TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558832 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148833
tommycli59a63432015-11-06 00:10:558834 GURL original_url(
8835 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8836 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148837
8838 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148839 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8840 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148841
Josh Karlinbe37f912018-12-07 01:05:148842 r->Start();
8843 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148844
Josh Karlinbe37f912018-12-07 01:05:148845 EXPECT_EQ(2U, r->url_chain().size());
8846 EXPECT_EQ(OK, d.request_status());
8847 EXPECT_EQ(original_url, r->original_url());
8848 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148849}
8850
[email protected]cba24642014-08-15 20:49:598851TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558852 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598853
tommycli59a63432015-11-06 00:10:558854 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598855 GURL first_party_url("http://example.com");
8856
8857 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148858 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8859 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8860 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598861
Josh Karlinbe37f912018-12-07 01:05:148862 r->Start();
8863 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598864
Josh Karlinbe37f912018-12-07 01:05:148865 EXPECT_EQ(2U, r->url_chain().size());
8866 EXPECT_EQ(OK, d.request_status());
8867 EXPECT_EQ(first_party_url, r->site_for_cookies());
8868}
8869
8870TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameOrigin) {
8871 ASSERT_TRUE(http_test_server()->Start());
8872
8873 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8874 url::Origin top_frame_origin =
8875 url::Origin::Create(GURL("http://example.com"));
8876 TestDelegate d;
8877
8878 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8879 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8880 r->set_top_frame_origin(top_frame_origin);
8881
8882 r->Start();
8883 d.RunUntilComplete();
8884
8885 EXPECT_EQ(2U, r->url_chain().size());
8886 EXPECT_EQ(OK, d.request_status());
8887 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
8888}
8889
8890TEST_F(URLRequestTestHTTP, RedirectPreserveUnsetTopFrameOrigin) {
8891 ASSERT_TRUE(http_test_server()->Start());
8892
8893 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8894 TestDelegate d;
8895
8896 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8897 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8898 // Since we're not setting a top frame origin, we wouldn't expect one after
8899 // the redirect.
8900 r->Start();
8901 d.RunUntilComplete();
8902
8903 EXPECT_EQ(2U, r->url_chain().size());
8904 EXPECT_EQ(OK, d.request_status());
8905 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:598906}
8907
Josh Karlinf3caee1642018-12-10 22:54:278908TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameURL) {
8909 ASSERT_TRUE(http_test_server()->Start());
8910
8911 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8912 url::Origin top_frame_origin =
8913 url::Origin::Create(GURL("http://example.com"));
8914 TestDelegate d;
8915 {
8916 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8917 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8918 r->set_top_frame_origin(top_frame_origin);
8919
8920 r->Start();
8921 d.RunUntilComplete();
8922
8923 EXPECT_EQ(2U, r->url_chain().size());
8924 EXPECT_EQ(OK, d.request_status());
8925 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
8926 }
8927}
8928
[email protected]cba24642014-08-15 20:49:598929TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558930 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598931
tommycli59a63432015-11-06 00:10:558932 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598933 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558934 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598935
8936 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148937
Ryan Sleevib8449e02018-07-15 04:31:078938 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168939 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468940 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198941 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598942 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8943
[email protected]f7022f32014-08-21 16:32:198944 r->Start();
Wez2a31b222018-06-07 22:07:158945 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598946
[email protected]f7022f32014-08-21 16:32:198947 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508948 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468949 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
Josh Karlinbe37f912018-12-07 01:05:148950}
8951
8952TEST_F(URLRequestTestHTTP, RedirectUpdateTopFrameOrigin) {
8953 ASSERT_TRUE(http_test_server()->Start());
8954
8955 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8956 url::Origin original_top_frame_origin =
8957 url::Origin::Create(GURL("http://example.com"));
8958 url::Origin expected_top_frame_origin =
8959 url::Origin::Create(GURL(http_test_server()->GetURL("/echo")));
8960
8961 TestDelegate d;
8962
8963 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8964 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8965 r->set_top_frame_origin(original_top_frame_origin);
8966 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8967
8968 r->Start();
8969 d.RunUntilComplete();
8970
8971 EXPECT_EQ(2U, r->url_chain().size());
8972 EXPECT_EQ(OK, d.request_status());
8973 EXPECT_EQ(expected_top_frame_origin, *r->top_frame_origin());
8974}
8975
8976TEST_F(URLRequestTestHTTP, RedirectIgnoreUnsetTopFrameOrigin) {
8977 ASSERT_TRUE(http_test_server()->Start());
8978
8979 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
8980 TestDelegate d;
8981
8982 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8983 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8984 // Since we're not setting a top frame origin, we wouldn't expect one after
8985 // the redirect.
8986 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8987
8988 r->Start();
8989 d.RunUntilComplete();
8990
8991 EXPECT_EQ(2U, r->url_chain().size());
8992 EXPECT_EQ(OK, d.request_status());
8993 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:598994}
8995
[email protected]316c1e5e2012-09-12 15:17:448996TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558997 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448998
8999 const char kData[] = "hello world";
9000
9001 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079002 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169003 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9004 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199005 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079006 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:449007 HttpRequestHeaders headers;
9008 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:249009 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:199010 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:449011
danakj8522a25b2016-04-16 00:17:369012 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559013 req.get(), &default_network_delegate_,
9014 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429015 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9016 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:449017
[email protected]f7022f32014-08-21 16:32:199018 req->Start();
Wez2a31b222018-06-07 22:07:159019 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:199020 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:449021}
9022
9023TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:559024 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449025
9026 const char kData[] = "hello world";
9027
9028 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079029 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169030 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9031 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199032 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079033 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:449034 HttpRequestHeaders headers;
9035 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:249036 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:199037 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:449038
danakj8522a25b2016-04-16 00:17:369039 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559040 req.get(), &default_network_delegate_,
9041 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:099042 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:429043 "Very Good Reason"));
9044 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:449045
[email protected]f7022f32014-08-21 16:32:199046 req->Start();
Wez2a31b222018-06-07 22:07:159047 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:199048 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:449049 EXPECT_EQ(kData, d.data_received());
9050}
9051
9052// Check that default A-L header is sent.
9053TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559054 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449055
[email protected]8790210c2013-12-02 05:29:539056 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:249057 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:449058 TestURLRequestContext context(true);
9059 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:439060 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:449061 context.Init();
9062
9063 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369064 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:559065 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169066 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199067 req->Start();
Wez2a31b222018-06-07 22:07:159068 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449069 EXPECT_EQ("en", d.data_received());
9070}
9071
9072// Check that an empty A-L header is not sent. http://crbug.com/77365.
9073TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559074 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449075
[email protected]8790210c2013-12-02 05:29:539076 std::string empty_string; // Avoid most vexing parse on line below.
9077 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:249078 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:449079 TestURLRequestContext context(true);
9080 context.set_network_delegate(&network_delegate);
9081 context.Init();
9082 // We override the language after initialization because empty entries
9083 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:439084 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:449085
9086 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369087 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:559088 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169089 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199090 req->Start();
Wez2a31b222018-06-07 22:07:159091 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449092 EXPECT_EQ("None", d.data_received());
9093}
9094
9095// Check that if request overrides the A-L header, the default is not appended.
9096// See http://crbug.com/20894
9097TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559098 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449099
9100 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079101 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559102 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169103 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449104 HttpRequestHeaders headers;
9105 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:199106 req->SetExtraRequestHeaders(headers);
9107 req->Start();
Wez2a31b222018-06-07 22:07:159108 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449109 EXPECT_EQ(std::string("ru"), d.data_received());
9110}
9111
9112// Check that default A-E header is sent.
9113TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559114 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449115
9116 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079117 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559118 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169119 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449120 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:199121 req->SetExtraRequestHeaders(headers);
9122 req->Start();
Wez2a31b222018-06-07 22:07:159123 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449124 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
9125}
9126
9127// Check that if request overrides the A-E header, the default is not appended.
9128// See http://crbug.com/47381
9129TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559130 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449131
9132 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079133 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559134 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169135 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449136 HttpRequestHeaders headers;
9137 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:199138 req->SetExtraRequestHeaders(headers);
9139 req->Start();
Wez2a31b222018-06-07 22:07:159140 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449141 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
9142 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
9143}
9144
[email protected]84f05432013-03-15 01:00:129145// Check that setting the A-C header sends the proper header.
9146TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:559147 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449148
9149 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079150 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559151 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:169152 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449153 HttpRequestHeaders headers;
9154 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:199155 req->SetExtraRequestHeaders(headers);
9156 req->Start();
Wez2a31b222018-06-07 22:07:159157 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449158 EXPECT_EQ(std::string("koi-8r"), d.data_received());
9159}
9160
9161// Check that default User-Agent header is sent.
9162TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:559163 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449164
9165 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079166 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559167 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169168 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199169 req->Start();
Wez2a31b222018-06-07 22:07:159170 d.RunUntilComplete();
Ryan Sleevib8449e02018-07-15 04:31:079171 EXPECT_EQ(default_context().http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:379172 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449173}
9174
9175// Check that if request overrides the User-Agent header,
9176// the default is not appended.
marqf14fff8d2015-12-02 15:52:299177// TODO(crbug.com/564656) This test is flaky on iOS.
9178#if defined(OS_IOS)
9179#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
9180#else
9181#define MAYBE_OverrideUserAgent OverrideUserAgent
9182#endif
9183TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:559184 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449185
9186 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079187 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559188 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169189 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449190 HttpRequestHeaders headers;
9191 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:199192 req->SetExtraRequestHeaders(headers);
9193 req->Start();
Wez2a31b222018-06-07 22:07:159194 d.RunUntilComplete();
[email protected]cd6f2522014-01-16 18:27:359195 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449196}
9197
[email protected]ee4c30d2012-11-07 15:08:439198// Check that a NULL HttpUserAgentSettings causes the corresponding empty
9199// User-Agent header to be sent but does not send the Accept-Language and
9200// Accept-Charset headers.
9201TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:559202 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:439203
[email protected]ceefd7fd2012-11-29 00:36:249204 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:439205 TestURLRequestContext context(true);
9206 context.set_network_delegate(&network_delegate);
9207 context.Init();
9208 // We override the HttpUserAgentSettings after initialization because empty
9209 // entries get overridden by Init().
Raul Tambre94493c652019-03-11 17:18:359210 context.set_http_user_agent_settings(nullptr);
[email protected]ee4c30d2012-11-07 15:08:439211
9212 struct {
9213 const char* request;
9214 const char* expected_response;
tommycli59a63432015-11-06 00:10:559215 } tests[] = {{"/echoheader?Accept-Language", "None"},
9216 {"/echoheader?Accept-Charset", "None"},
9217 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:439218
Avi Drissman4365a4782018-12-28 19:26:249219 for (size_t i = 0; i < base::size(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:439220 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369221 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169222 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
9223 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199224 req->Start();
Wez2a31b222018-06-07 22:07:159225 d.RunUntilComplete();
[email protected]ee4c30d2012-11-07 15:08:439226 EXPECT_EQ(tests[i].expected_response, d.data_received())
9227 << " Request = \"" << tests[i].request << "\"";
9228 }
9229}
9230
[email protected]5033ab82013-03-22 20:17:469231// Make sure that URLRequest passes on its priority updates to
9232// newly-created jobs after the first one.
9233TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:559234 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:469235
9236 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079237 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169238 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9239 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199240 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:469241
danakj8522a25b2016-04-16 00:17:369242 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559243 req.get(), &default_network_delegate_,
9244 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429245 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9246 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:469247
[email protected]f7022f32014-08-21 16:32:199248 req->SetPriority(LOW);
9249 req->Start();
9250 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:469251
mmenkeed0498b2015-12-08 23:20:429252 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:369253 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:429254 req.get(), &default_network_delegate_, &job_priority));
9255 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:469256
9257 // Should trigger |job| to be started.
Wez2a31b222018-06-07 22:07:159258 d.RunUntilComplete();
mmenkeed0498b2015-12-08 23:20:429259 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:469260}
9261
[email protected]80abdad2014-03-15 00:20:549262// Check that creating a network request while entering/exiting suspend mode
9263// fails as it should. This is the only case where an HttpTransactionFactory
9264// does not return an HttpTransaction.
9265TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
9266 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:369267 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
Ryan Sleevib8449e02018-07-15 04:31:079268 default_context().http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:549269 network_layer->OnSuspend();
9270
dchengc7eeda422015-12-26 03:56:489271 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:039272 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:279273 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:549274
9275 TestURLRequestContext context(true);
9276 context.set_http_transaction_factory(&http_cache);
9277 context.Init();
9278
9279 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369280 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169281 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9282 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199283 req->Start();
Wez2a31b222018-06-07 22:07:159284 d.RunUntilComplete();
[email protected]80abdad2014-03-15 00:20:549285
9286 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:509287 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:549288}
9289
mmenke2281f3762015-11-02 20:38:179290namespace {
[email protected]80abdad2014-03-15 00:20:549291
mmenke2281f3762015-11-02 20:38:179292// HttpTransactionFactory that synchronously fails to create transactions.
9293class FailingHttpTransactionFactory : public HttpTransactionFactory {
9294 public:
9295 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
9296 : network_session_(network_session) {}
9297
Chris Watkins7a41d3552017-12-01 02:13:279298 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:179299
9300 // HttpTransactionFactory methods:
9301 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:369302 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:179303 return ERR_FAILED;
9304 }
9305
9306 HttpCache* GetCache() override { return nullptr; }
9307
9308 HttpNetworkSession* GetSession() override { return network_session_; }
9309
9310 private:
9311 HttpNetworkSession* network_session_;
9312
9313 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
9314};
9315
9316} // namespace
9317
9318// Check that when a request that fails to create an HttpTransaction can be
9319// cancelled while the failure notification is pending, and doesn't send two
9320// failure notifications.
9321//
9322// This currently only happens when in suspend mode and there's no cache, but
9323// just use a special HttpTransactionFactory, to avoid depending on those
9324// behaviors.
9325TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
9326 FailingHttpTransactionFactory http_transaction_factory(
Ryan Sleevib8449e02018-07-15 04:31:079327 default_context().http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:549328 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:179329 context.set_http_transaction_factory(&http_transaction_factory);
9330 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:549331 context.Init();
9332
9333 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369334 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169335 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9336 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:179337 // Don't send cookies (Collecting cookies is asynchronous, and need request to
9338 // try to create an HttpNetworkTransaction synchronously on start).
9339 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:199340 req->Start();
mmenke2281f3762015-11-02 20:38:179341 req->Cancel();
Wez2a31b222018-06-07 22:07:159342 d.RunUntilComplete();
mmenke2281f3762015-11-02 20:38:179343 // Run pending error task, if there is one.
9344 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:549345
9346 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:179347 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509348 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:179349
9350 // NetworkDelegate should see the cancellation, but not the error.
9351 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
9352 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:549353}
9354
ttuttlec0c828492015-05-15 01:25:559355TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:559356 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559357
9358 TestDelegate d;
tommycli59a63432015-11-06 00:10:559359 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079360 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169361 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559362
9363 req->Start();
Wez2a31b222018-06-07 22:07:159364 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559365
9366 EXPECT_TRUE(req->response_info().network_accessed);
9367}
9368
9369TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:559370 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559371
9372 // Populate the cache.
9373 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079374 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169375 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9376 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559377 req->Start();
Wez2a31b222018-06-07 22:07:159378 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559379
maksim.sisovb53724b52016-09-16 05:30:509380 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559381 EXPECT_TRUE(req->response_info().network_accessed);
9382 EXPECT_FALSE(req->response_info().was_cached);
9383
Ryan Sleevib8449e02018-07-15 04:31:079384 req = default_context().CreateRequest(
9385 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9386 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:559387 req->Start();
Wez2a31b222018-06-07 22:07:159388 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559389
maksim.sisovb53724b52016-09-16 05:30:509390 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559391 EXPECT_FALSE(req->response_info().network_accessed);
9392 EXPECT_TRUE(req->response_info().was_cached);
9393}
9394
9395TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:559396 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559397
9398 TestDelegate d;
tommycli59a63432015-11-06 00:10:559399 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079400 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169401 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:339402 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:559403
9404 req->Start();
Wez2a31b222018-06-07 22:07:159405 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559406
9407 EXPECT_FALSE(req->response_info().network_accessed);
9408}
9409
rdsmithbf8c3c12016-11-18 18:16:249410// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:089411// correctly in the absence of contention.
9412TEST_F(URLRequestTestHTTP, ThrottledPriority) {
9413 ASSERT_TRUE(http_test_server()->Start());
9414
9415 TestDelegate d;
9416 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079417 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169418 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:089419 req->Start();
Wez2a31b222018-06-07 22:07:159420 d.RunUntilComplete();
rdsmith5eb6fbc2016-10-21 17:36:089421
9422 EXPECT_TRUE(req->status().is_success());
9423}
9424
ricea3a1c71f2016-06-17 10:05:269425TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
9426 ASSERT_TRUE(http_test_server()->Start());
9427
9428 TestDelegate d;
9429 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169430 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9431 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269432 req->Start();
Wez2a31b222018-06-07 22:07:159433 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269434
9435 EXPECT_EQ(5, req->GetRawBodyBytes());
9436}
9437
9438TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
9439 ASSERT_TRUE(http_test_server()->Start());
9440
9441 TestDelegate d;
9442 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169443 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
9444 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269445 req->Start();
Wez2a31b222018-06-07 22:07:159446 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269447
9448 EXPECT_EQ(30, req->GetRawBodyBytes());
9449}
9450
jamd3f5a3c2016-10-27 18:52:029451// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
9452// the delegate isn't called back synchronously.
9453TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
9454 ASSERT_TRUE(http_test_server()->Start());
9455 default_network_delegate_.set_before_start_transaction_fails();
9456
9457 TestDelegate d;
9458 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169459 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
9460 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:029461 req->Start();
9462 DCHECK(!d.response_completed());
Wez2a31b222018-06-07 22:07:159463 d.RunUntilComplete();
jamd3f5a3c2016-10-27 18:52:029464 DCHECK(d.response_completed());
9465 EXPECT_EQ(ERR_FAILED, d.request_status());
9466}
9467
bengr1bf8e942014-11-07 01:36:509468class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9469 public:
9470 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9471 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9472 // tests into the factory tests.
Raul Tambre94493c652019-03-11 17:18:359473 URLRequestInterceptorTestHTTP()
9474 : URLRequestTestHTTP(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:509475
9476 void SetUpFactory() override {
9477 interceptor_ = new MockURLRequestInterceptor();
9478 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369479 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509480 }
9481
9482 MockURLRequestInterceptor* interceptor() const {
9483 return interceptor_;
9484 }
9485
9486 private:
9487 MockURLRequestInterceptor* interceptor_;
9488};
9489
9490TEST_F(URLRequestInterceptorTestHTTP,
9491 NetworkDelegateNotificationOnRedirectIntercept) {
9492 interceptor()->set_intercept_redirect(true);
9493 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9494 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9495
tommycli59a63432015-11-06 00:10:559496 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509497
9498 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369499 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169500 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9501 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509502 req->Start();
Wez2a31b222018-06-07 22:07:159503 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509504
9505 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9506 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509507 int status = d.request_status();
9508 EXPECT_EQ(OK, status);
9509 if (status == OK)
bengr1bf8e942014-11-07 01:36:509510 EXPECT_EQ(200, req->response_headers()->response_code());
9511
9512 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9513 EXPECT_EQ(1, d.response_started_count());
9514 EXPECT_EQ(0, d.received_redirect_count());
9515
9516 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009517 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509518 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9519}
9520
9521TEST_F(URLRequestInterceptorTestHTTP,
9522 NetworkDelegateNotificationOnErrorIntercept) {
9523 // Intercept that error and respond with an OK response.
9524 interceptor()->set_intercept_final_response(true);
9525 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9526 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9527 default_network_delegate()->set_can_be_intercepted_on_error(true);
9528
tommycli59a63432015-11-06 00:10:559529 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509530
9531 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369532 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559533 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169534 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509535 req->set_method("GET");
9536 req->Start();
Wez2a31b222018-06-07 22:07:159537 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509538
9539 EXPECT_TRUE(interceptor()->did_intercept_final());
9540
9541 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509542 int status = d.request_status();
9543 EXPECT_EQ(OK, status);
9544 if (status == OK)
bengr1bf8e942014-11-07 01:36:509545 EXPECT_EQ(200, req->response_headers()->response_code());
9546 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9547 EXPECT_EQ(1, d.response_started_count());
9548 EXPECT_EQ(0, d.received_redirect_count());
9549
9550 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009551 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509552 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9553}
9554
9555TEST_F(URLRequestInterceptorTestHTTP,
9556 NetworkDelegateNotificationOnResponseIntercept) {
9557 // Intercept that error and respond with an OK response.
9558 interceptor()->set_intercept_final_response(true);
9559
9560 // Intercept with a real URLRequestHttpJob.
9561 interceptor()->set_use_url_request_http_job(true);
9562
tommycli59a63432015-11-06 00:10:559563 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509564
9565 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369566 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169567 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9568 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509569 req->set_method("GET");
9570 req->Start();
Wez2a31b222018-06-07 22:07:159571 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509572
9573 EXPECT_TRUE(interceptor()->did_intercept_final());
9574
9575 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509576 int status = d.request_status();
9577 EXPECT_EQ(OK, status);
9578 if (status == OK)
bengr1bf8e942014-11-07 01:36:509579 EXPECT_EQ(200, req->response_headers()->response_code());
9580 EXPECT_EQ("hello", d.data_received());
9581 EXPECT_EQ(1, d.response_started_count());
9582 EXPECT_EQ(0, d.received_redirect_count());
9583
9584 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009585 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509586 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9587}
9588
mkwst0c5eab872014-11-21 14:18:549589class URLRequestTestReferrerPolicy : public URLRequestTest {
9590 public:
Chris Watkins7a41d3552017-12-01 02:13:279591 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:549592
tommycli59a63432015-11-06 00:10:559593 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9594 origin_server_.reset(new EmbeddedTestServer(type));
9595 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9596 origin_server_->AddDefaultHandlers(
9597 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9598 } else {
9599 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9600 }
mkwst0c5eab872014-11-21 14:18:549601 ASSERT_TRUE(origin_server_->Start());
9602 }
9603
tommycli59a63432015-11-06 00:10:559604 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9605 net::EmbeddedTestServer::Type dest_type) {
9606 origin_server_.reset(new EmbeddedTestServer(origin_type));
9607 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9608 origin_server_->AddDefaultHandlers(
9609 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9610 } else {
9611 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9612 }
mkwst0c5eab872014-11-21 14:18:549613 ASSERT_TRUE(origin_server_->Start());
9614
tommycli59a63432015-11-06 00:10:559615 destination_server_.reset(new EmbeddedTestServer(dest_type));
9616 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9617 destination_server_->AddDefaultHandlers(
9618 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9619 } else {
9620 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9621 }
mkwst0c5eab872014-11-21 14:18:549622 ASSERT_TRUE(destination_server_->Start());
9623 }
9624
9625 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9626 const GURL& referrer,
9627 const GURL& expected) {
9628 // Create and execute the request: we'll only have a |destination_server_|
9629 // if the origins are meant to be distinct. Otherwise, we'll use the
9630 // |origin_server_| for both endpoints.
9631 GURL destination_url =
tommycli59a63432015-11-06 00:10:559632 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9633 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549634 GURL origin_url =
tommycli59a63432015-11-06 00:10:559635 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549636
9637 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079638 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169639 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549640 req->set_referrer_policy(policy);
9641 req->SetReferrer(referrer.spec());
9642 req->Start();
Wez2a31b222018-06-07 22:07:159643 d.RunUntilComplete();
mkwst0c5eab872014-11-21 14:18:549644
9645 EXPECT_EQ(1, d.response_started_count());
9646 EXPECT_EQ(1, d.received_redirect_count());
9647 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509648 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549649 EXPECT_EQ(200, req->response_headers()->response_code());
9650
9651 EXPECT_EQ(expected.spec(), req->referrer());
9652 if (expected.is_empty())
9653 EXPECT_EQ("None", d.data_received());
9654 else
9655 EXPECT_EQ(expected.spec(), d.data_received());
9656 }
9657
tommycli59a63432015-11-06 00:10:559658 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549659
9660 private:
danakj8522a25b2016-04-16 00:17:369661 std::unique_ptr<EmbeddedTestServer> origin_server_;
9662 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549663};
9664
9665TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559666 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549667
estarkc8ccba82017-06-13 22:37:409668 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549669 VerifyReferrerAfterRedirect(
9670 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409671 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549672
9673 VerifyReferrerAfterRedirect(
9674 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409675 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549676
9677 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409678 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549679
estarkc8ccba82017-06-13 22:37:409680 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9681 referrer);
9682
9683 // The original referrer set on the request is expected to obey the referrer
9684 // policy and already be stripped to the origin; thus this test case just
9685 // checks that this policy doesn't cause the referrer to change when following
9686 // a redirect.
9687 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9688 referrer.GetOrigin());
9689
9690 VerifyReferrerAfterRedirect(
9691 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9692 referrer);
9693
9694 // The original referrer set on the request is expected to obey the referrer
9695 // policy and already be stripped to the origin; thus this test case just
9696 // checks that this policy doesn't cause the referrer to change when following
9697 // a redirect.
9698 VerifyReferrerAfterRedirect(
9699 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9700 referrer.GetOrigin(), referrer.GetOrigin());
9701
9702 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549703}
9704
tommycli59a63432015-11-06 00:10:559705TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9706 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9707 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409708 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549709
9710 VerifyReferrerAfterRedirect(
9711 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409712 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549713
9714 VerifyReferrerAfterRedirect(
9715 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409716 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549717
9718 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409719 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9720 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549721
estarkc8ccba82017-06-13 22:37:409722 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9723 referrer);
9724
9725 // The original referrer set on the request is expected to obey the referrer
9726 // policy and already be stripped to the origin; thus this test case just
9727 // checks that this policy doesn't cause the referrer to change when following
9728 // a redirect.
9729 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9730 referrer.GetOrigin());
9731
9732 VerifyReferrerAfterRedirect(
9733 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9734
9735 // The original referrer set on the request is expected to obey the referrer
9736 // policy and already be stripped to the origin; thus this test case just
9737 // checks that this policy doesn't cause the referrer to change when following
9738 // a redirect.
9739 VerifyReferrerAfterRedirect(
9740 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9741 referrer.GetOrigin(), referrer.GetOrigin());
9742
9743 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549744}
9745
9746TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559747 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409748 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549749
9750 VerifyReferrerAfterRedirect(
9751 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409752 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549753
9754 VerifyReferrerAfterRedirect(
9755 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409756 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549757
9758 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409759 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549760
estarkc8ccba82017-06-13 22:37:409761 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9762 referrer);
9763
9764 // The original referrer set on the request is expected to obey the referrer
9765 // policy and already be stripped to the origin; thus this test case just
9766 // checks that this policy doesn't cause the referrer to change when following
9767 // a redirect.
9768 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9769 referrer.GetOrigin());
9770
9771 VerifyReferrerAfterRedirect(
9772 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9773 referrer);
9774
9775 // The original referrer set on the request is expected to obey the referrer
9776 // policy and already be stripped to the origin; thus this test case just
9777 // checks that this policy doesn't cause the referrer to change when following
9778 // a redirect.
9779 VerifyReferrerAfterRedirect(
9780 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9781 referrer.GetOrigin(), referrer.GetOrigin());
9782
9783 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549784}
9785
tommycli59a63432015-11-06 00:10:559786TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
9787 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9788 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409789 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549790
9791 VerifyReferrerAfterRedirect(
9792 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409793 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549794
9795 VerifyReferrerAfterRedirect(
9796 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409797 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549798
9799 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409800 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559801 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549802
estarkc8ccba82017-06-13 22:37:409803 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9804 referrer);
9805
9806 // The original referrer set on the request is expected to obey the referrer
9807 // policy and already be stripped to the origin; thus this test case just
9808 // checks that this policy doesn't cause the referrer to change when following
9809 // a redirect.
9810 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9811 referrer.GetOrigin());
9812
9813 VerifyReferrerAfterRedirect(
9814 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9815
9816 // The original referrer set on the request is expected to obey the referrer
9817 // policy and already be stripped to the origin; thus this test case just
9818 // checks that this policy doesn't cause the referrer to change when following
9819 // a redirect.
9820 VerifyReferrerAfterRedirect(
9821 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9822 referrer.GetOrigin(), referrer.GetOrigin());
9823
9824 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549825}
9826
tommycli59a63432015-11-06 00:10:559827TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
9828 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9829 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409830 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549831
9832 VerifyReferrerAfterRedirect(
9833 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409834 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549835
9836 VerifyReferrerAfterRedirect(
9837 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409838 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549839
9840 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409841 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559842 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549843
estarkc8ccba82017-06-13 22:37:409844 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9845 referrer);
9846
9847 // The original referrer set on the request is expected to obey the referrer
9848 // policy and already be stripped to the origin; thus this test case just
9849 // checks that this policy doesn't cause the referrer to change when following
9850 // a redirect.
9851 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9852 referrer.GetOrigin());
9853
9854 VerifyReferrerAfterRedirect(
9855 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9856
9857 // The original referrer set on the request is expected to obey the referrer
9858 // policy and already be stripped to the origin; thus this test case just
9859 // checks that this policy doesn't cause the referrer to change when following
9860 // a redirect.
9861 VerifyReferrerAfterRedirect(
9862 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9863 referrer.GetOrigin(), referrer.GetOrigin());
9864
9865 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549866}
9867
tommycli59a63432015-11-06 00:10:559868TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
9869 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9870 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409871 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549872
9873 VerifyReferrerAfterRedirect(
9874 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409875 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549876
9877 VerifyReferrerAfterRedirect(
9878 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409879 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549880
9881 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409882 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559883 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549884
estarkc8ccba82017-06-13 22:37:409885 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9886 referrer);
9887
9888 // The original referrer set on the request is expected to obey the referrer
9889 // policy and already be stripped to the origin; thus this test case just
9890 // checks that this policy doesn't cause the referrer to change when following
9891 // a redirect.
9892 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9893 referrer.GetOrigin());
9894
9895 VerifyReferrerAfterRedirect(
9896 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9897
9898 // The original referrer set on the request is expected to obey the referrer
9899 // policy and already be stripped to the origin, though it should be
9900 // subsequently cleared during the downgrading redirect.
9901 VerifyReferrerAfterRedirect(
9902 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9903 referrer.GetOrigin(), GURL());
9904
9905 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549906}
9907
Bence Béky98447b12018-05-08 03:14:019908class HTTPSRequestTest : public TestWithScopedTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:509909 public:
fdorayf33fede2017-05-11 21:18:109910 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:099911 default_context_.set_network_delegate(&default_network_delegate_);
9912 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:509913 }
Martijn Croonenb1383da2017-10-11 11:56:359914 ~HTTPSRequestTest() override {
9915 SetTransportSecurityStateSourceForTesting(nullptr);
9916 }
[email protected]87a09a92011-07-14 15:50:509917
9918 protected:
[email protected]ceefd7fd2012-11-29 00:36:249919 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:099920 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:469921};
9922
[email protected]c044616e2013-02-20 02:01:269923TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:559924 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9925 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229926 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119927 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469928
[email protected]ea224582008-12-07 20:25:469929 TestDelegate d;
9930 {
danakj8522a25b2016-04-16 00:17:369931 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169932 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9933 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199934 r->Start();
9935 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469936
Wez2a31b222018-06-07 22:07:159937 d.RunUntilComplete();
[email protected]ea224582008-12-07 20:25:469938
9939 EXPECT_EQ(1, d.response_started_count());
9940 EXPECT_FALSE(d.received_data_before_response());
9941 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199942 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199943 EXPECT_EQ(test_server.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:379944 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
[email protected]6d81b482011-02-22 19:47:199945 EXPECT_EQ(test_server.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:379946 r->GetResponseRemoteEndpoint().port());
[email protected]ea224582008-12-07 20:25:469947 }
[email protected]ea224582008-12-07 20:25:469948}
9949
[email protected]5774ada2010-07-15 06:30:549950TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559951 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9952 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9953 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229954 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119955 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339956
9957 bool err_allowed = true;
9958 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9959 TestDelegate d;
9960 {
9961 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369962 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169963 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9964 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339965
[email protected]f7022f32014-08-21 16:32:199966 r->Start();
9967 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339968
Wez2a31b222018-06-07 22:07:159969 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339970
9971 EXPECT_EQ(1, d.response_started_count());
9972 EXPECT_FALSE(d.received_data_before_response());
9973 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179974 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339975 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199976 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179977 } else {
[email protected]bacff652009-03-31 17:50:339978 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179979 }
[email protected]bacff652009-03-31 17:50:339980 }
9981 }
9982}
9983
[email protected]5774ada2010-07-15 06:30:549984TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559985 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9986 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9987 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229988 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119989 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339990
9991 // Iterate from false to true, just so that we do the opposite of the
9992 // previous test in order to increase test coverage.
9993 bool err_allowed = false;
9994 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9995 TestDelegate d;
9996 {
9997 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369998 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169999 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10000 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:3310001
[email protected]f7022f32014-08-21 16:32:1910002 r->Start();
10003 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:3310004
Wez2a31b222018-06-07 22:07:1510005 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:3310006
10007 EXPECT_EQ(1, d.response_started_count());
10008 EXPECT_FALSE(d.received_data_before_response());
10009 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:1710010 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:3310011 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:1910012 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:1710013 } else {
[email protected]bacff652009-03-31 17:50:3310014 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:1710015 }
[email protected]bacff652009-03-31 17:50:3310016 }
10017 }
10018}
[email protected]73e0bba2009-02-19 22:57:0910019
Emily Stark79fba5842019-04-25 04:59:3610020// A TestDelegate used to test that an appropriate net error code is provided
10021// when an SSL certificate error occurs.
10022class SSLNetErrorTestDelegate : public TestDelegate {
10023 public:
10024 void OnSSLCertificateError(URLRequest* request,
10025 int net_error,
10026 const SSLInfo& ssl_info,
10027 bool fatal) override {
10028 net_error_ = net_error;
10029 on_ssl_certificate_error_called_ = true;
10030 TestDelegate::OnSSLCertificateError(request, net_error, ssl_info, fatal);
10031 }
10032
10033 bool on_ssl_certificate_error_called() {
10034 return on_ssl_certificate_error_called_;
10035 }
10036
10037 int net_error() { return net_error_; }
10038
10039 private:
10040 bool on_ssl_certificate_error_called_ = false;
10041 int net_error_ = net::OK;
10042};
10043
10044// Tests that the URLRequest::Delegate receives an appropriate net error code
10045// when an SSL certificate error occurs.
10046TEST_F(HTTPSRequestTest, SSLNetErrorReportedToDelegate) {
10047 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10048 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
10049 test_server.AddDefaultHandlers(
10050 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10051 ASSERT_TRUE(test_server.Start());
10052
10053 SSLNetErrorTestDelegate d;
10054 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10055 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10056 TRAFFIC_ANNOTATION_FOR_TESTS));
10057 r->Start();
10058 EXPECT_TRUE(r->is_pending());
10059 d.RunUntilComplete();
10060
10061 EXPECT_TRUE(d.on_ssl_certificate_error_called());
10062 EXPECT_EQ(net::ERR_CERT_DATE_INVALID, d.net_error());
10063}
10064
tommycli59a63432015-11-06 00:10:5510065// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
10066// security state. (see http://crbug.com/550977).
10067#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:3510068// This tests that a load of a domain with preloaded HSTS and HPKP with a
10069// certificate error sets the |certificate_errors_are_fatal| flag correctly.
10070// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:4410071TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:3510072 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
10073
tommycli59a63432015-11-06 00:10:5510074 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10075 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10076 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:4410077 ASSERT_TRUE(test_server.Start());
10078
Martijn Croonenb1383da2017-10-11 11:56:3510079 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
10080 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
10081 // means that we have to use a MockHostResolver in order to direct
10082 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
10083 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:4410084
10085 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:2410086 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:4410087 TestURLRequestContext context(true);
10088 context.set_network_delegate(&network_delegate);
10089 context.set_host_resolver(&host_resolver);
10090 TransportSecurityState transport_security_state;
10091 context.set_transport_security_state(&transport_security_state);
10092 context.Init();
10093
10094 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610095 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:3510096 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:3610097 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610098 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410099
[email protected]f7022f32014-08-21 16:32:1910100 r->Start();
10101 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410102
Wez2a31b222018-06-07 22:07:1510103 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410104
10105 EXPECT_EQ(1, d.response_started_count());
10106 EXPECT_FALSE(d.received_data_before_response());
10107 EXPECT_TRUE(d.have_certificate_errors());
10108 EXPECT_TRUE(d.certificate_errors_are_fatal());
10109}
10110
10111// This tests that cached HTTPS page loads do not cause any updates to the
10112// TransportSecurityState.
10113TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:3510114 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
10115
[email protected]316c1e5e2012-09-12 15:17:4410116 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
10117 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:5510118 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10119 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10120 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:4410121 ASSERT_TRUE(test_server.Start());
10122
Martijn Croonenb1383da2017-10-11 11:56:3510123 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
10124 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
10125 // means that we have to use a MockHostResolver in order to direct
10126 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
10127 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:4410128
10129 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:2410130 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:4410131 TestURLRequestContext context(true);
10132 context.set_network_delegate(&network_delegate);
10133 context.set_host_resolver(&host_resolver);
10134 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:2610135
martijnc0d6b622015-06-30 19:14:4010136 TransportSecurityState::STSState static_sts_state;
10137 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610138 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510139 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:4410140 context.set_transport_security_state(&transport_security_state);
10141 context.Init();
10142
martijnc0d6b622015-06-30 19:14:4010143 TransportSecurityState::STSState dynamic_sts_state;
10144 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:3510145 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
10146 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
10147 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
10148 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610149
[email protected]316c1e5e2012-09-12 15:17:4410150 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610151 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:3510152 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:3610153 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610154 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410155
[email protected]f7022f32014-08-21 16:32:1910156 r->Start();
10157 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410158
Wez2a31b222018-06-07 22:07:1510159 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410160
10161 EXPECT_EQ(1, d.response_started_count());
10162 EXPECT_FALSE(d.received_data_before_response());
10163 EXPECT_TRUE(d.have_certificate_errors());
10164 EXPECT_TRUE(d.certificate_errors_are_fatal());
10165
[email protected]9e6968d2014-05-07 21:46:2610166 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:4010167 TransportSecurityState::STSState new_static_sts_state;
10168 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610169 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510170 "hsts-hpkp-preloaded.test", &new_static_sts_state,
10171 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:4010172 TransportSecurityState::STSState new_dynamic_sts_state;
10173 TransportSecurityState::PKPState new_dynamic_pkp_state;
10174 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:3510175 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:4010176 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:3510177 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610178
martijnc0d6b622015-06-30 19:14:4010179 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
10180 EXPECT_EQ(new_static_sts_state.include_subdomains,
10181 static_sts_state.include_subdomains);
10182 EXPECT_EQ(new_static_pkp_state.include_subdomains,
10183 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:4810184 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
10185 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
10186 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:4410187}
10188
[email protected]8ccc69f2012-11-28 19:52:1410189// Make sure HSTS preserves a POST request's method and body.
10190TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
10191 static const char kData[] = "hello world";
10192
tommycli59a63432015-11-06 00:10:5510193 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10194 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210195 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:1410196 ASSERT_TRUE(test_server.Start());
10197
10198
10199 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10200 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:5510201 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:2210202 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:1410203 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:1410204
10205 // Force https for www.somewhere.com.
10206 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:2010207 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
10208 bool include_subdomains = false;
10209 transport_security_state.AddHSTS("www.somewhere.com", expiry,
10210 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:1410211
10212 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10213
10214 TestURLRequestContext context(true);
10215 context.set_host_resolver(&host_resolver);
10216 context.set_transport_security_state(&transport_security_state);
10217 context.set_network_delegate(&network_delegate);
10218 context.Init();
10219
10220 TestDelegate d;
10221 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
10222 // cause a certificate error. Ignore the error.
10223 d.set_allow_certificate_errors(true);
10224
danakj8522a25b2016-04-16 00:17:3610225 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:1910226 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:3610227 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610228 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910229 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:0710230 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:1410231
[email protected]f7022f32014-08-21 16:32:1910232 req->Start();
Wez2a31b222018-06-07 22:07:1510233 d.RunUntilComplete();
[email protected]8ccc69f2012-11-28 19:52:1410234
[email protected]f7022f32014-08-21 16:32:1910235 EXPECT_EQ("https", req->url().scheme());
10236 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:1410237 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:4010238
10239 LoadTimingInfo load_timing_info;
10240 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
10241 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
10242 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:1410243}
10244
rob4e0be1f2014-09-11 23:40:2210245// Make sure that the CORS headers are added to cross-origin HSTS redirects.
10246TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
10247 static const char kOriginHeaderValue[] = "http://www.example.com";
10248
tommycli59a63432015-11-06 00:10:5510249 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10250 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:2210251 ASSERT_TRUE(test_server.Start());
10252
10253 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10254 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:5510255 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
10256 // default.
rob4e0be1f2014-09-11 23:40:2210257 MockHostResolver host_resolver;
10258
10259 TransportSecurityState transport_security_state;
10260 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
10261 bool include_subdomains = false;
10262 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
10263
10264 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10265
10266 MockCertVerifier cert_verifier;
10267 cert_verifier.set_default_result(OK);
10268
10269 TestURLRequestContext context(true);
10270 context.set_host_resolver(&host_resolver);
10271 context.set_transport_security_state(&transport_security_state);
10272 context.set_network_delegate(&network_delegate);
10273 context.set_cert_verifier(&cert_verifier);
10274 context.Init();
10275
10276 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
10277 test_server.host_port_pair().port()));
10278 url::Replacements<char> replacements;
10279 const char kNewScheme[] = "https";
10280 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
10281 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
10282
10283 TestDelegate d;
rob4e0be1f2014-09-11 23:40:2210284
rhalavatib7bd7c792017-04-27 05:25:1610285 std::unique_ptr<URLRequest> req(context.CreateRequest(
10286 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:2210287 // Set Origin header to simulate a cross-origin request.
10288 HttpRequestHeaders request_headers;
10289 request_headers.SetHeader("Origin", kOriginHeaderValue);
10290 req->SetExtraRequestHeaders(request_headers);
10291
10292 req->Start();
Wez0e717112018-06-18 23:09:2210293 d.RunUntilRedirect();
rob4e0be1f2014-09-11 23:40:2210294
10295 EXPECT_EQ(1, d.received_redirect_count());
10296
10297 const HttpResponseHeaders* headers = req->response_headers();
10298 std::string redirect_location;
Raul Tambre94493c652019-03-11 17:18:3510299 EXPECT_TRUE(
10300 headers->EnumerateHeader(nullptr, "Location", &redirect_location));
rob4e0be1f2014-09-11 23:40:2210301 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
10302
10303 std::string received_cors_header;
Raul Tambre94493c652019-03-11 17:18:3510304 EXPECT_TRUE(headers->EnumerateHeader(nullptr, "Access-Control-Allow-Origin",
rob4e0be1f2014-09-11 23:40:2210305 &received_cors_header));
10306 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
10307}
10308
[email protected]316c1e5e2012-09-12 15:17:4410309namespace {
10310
10311class SSLClientAuthTestDelegate : public TestDelegate {
10312 public:
10313 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
Wez0e717112018-06-18 23:09:2210314 set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:4410315 }
dchengb03027d2014-10-21 12:00:2010316 void OnCertificateRequested(URLRequest* request,
10317 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:4410318 on_certificate_requested_count_++;
Wez0e717112018-06-18 23:09:2210319 std::move(on_certificate_requested_).Run();
10320 }
10321 void RunUntilCertificateRequested() {
10322 base::RunLoop run_loop;
10323 on_certificate_requested_ = run_loop.QuitClosure();
10324 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:4410325 }
10326 int on_certificate_requested_count() {
10327 return on_certificate_requested_count_;
10328 }
10329 private:
10330 int on_certificate_requested_count_;
Wez0e717112018-06-18 23:09:2210331 base::OnceClosure on_certificate_requested_;
[email protected]316c1e5e2012-09-12 15:17:4410332};
10333
David Benjamin76a40ad2018-02-24 22:22:0810334class TestSSLPrivateKey : public SSLPrivateKey {
10335 public:
10336 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
10337 : key_(std::move(key)) {}
10338
10339 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
10340 int sign_count() const { return sign_count_; }
10341
David Benjaminb65b0732018-11-09 20:33:5310342 std::string GetProviderName() override { return key_->GetProviderName(); }
David Benjamin76a40ad2018-02-24 22:22:0810343 std::vector<uint16_t> GetAlgorithmPreferences() override {
10344 return key_->GetAlgorithmPreferences();
10345 }
10346 void Sign(uint16_t algorithm,
10347 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:2610348 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:0810349 sign_count_++;
10350 if (fail_signing_) {
10351 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:2610352 FROM_HERE, base::BindOnce(std::move(callback),
10353 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
10354 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:0810355 } else {
David Benjamin8f2d2c12018-02-27 00:08:2610356 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:0810357 }
10358 }
10359
10360 private:
10361 ~TestSSLPrivateKey() override = default;
10362
10363 scoped_refptr<SSLPrivateKey> key_;
10364 bool fail_signing_ = false;
10365 int sign_count_ = 0;
10366};
10367
[email protected]316c1e5e2012-09-12 15:17:4410368} // namespace
10369
10370// TODO(davidben): Test the rest of the code. Specifically,
10371// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:4410372// - Getting a certificate request in an SSL renegotiation sending the
10373// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:0810374TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:5510375 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10376 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:1210377 ssl_config.client_cert_type =
10378 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:0810379 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:5510380 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210381 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410382 ASSERT_TRUE(test_server.Start());
10383
10384 SSLClientAuthTestDelegate d;
10385 {
danakj8522a25b2016-04-16 00:17:3610386 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610387 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10388 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410389
[email protected]f7022f32014-08-21 16:32:1910390 r->Start();
10391 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410392
Wez0e717112018-06-18 23:09:2210393 d.RunUntilCertificateRequested();
10394 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410395
10396 EXPECT_EQ(1, d.on_certificate_requested_count());
10397 EXPECT_FALSE(d.received_data_before_response());
10398 EXPECT_EQ(0, d.bytes_received());
10399
10400 // Send no certificate.
10401 // TODO(davidben): Get temporary client cert import (with keys) working on
10402 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:5410403 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:4410404
Wez2a31b222018-06-07 22:07:1510405 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410406
David Benjamin76a40ad2018-02-24 22:22:0810407 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:4410408 EXPECT_EQ(1, d.response_started_count());
10409 EXPECT_FALSE(d.received_data_before_response());
10410 EXPECT_NE(0, d.bytes_received());
10411 }
10412}
10413
David Benjamin76a40ad2018-02-24 22:22:0810414TEST_F(HTTPSRequestTest, ClientAuth) {
10415 std::unique_ptr<FakeClientCertIdentity> identity =
10416 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10417 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10418 ASSERT_TRUE(identity);
10419 scoped_refptr<TestSSLPrivateKey> private_key =
10420 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10421
10422 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10423 net::SSLServerConfig ssl_config;
10424 ssl_config.client_cert_type =
10425 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10426 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10427 test_server.AddDefaultHandlers(
10428 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10429 ASSERT_TRUE(test_server.Start());
10430
10431 {
10432 SSLClientAuthTestDelegate d;
10433 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10434 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10435 TRAFFIC_ANNOTATION_FOR_TESTS));
10436
10437 r->Start();
10438 EXPECT_TRUE(r->is_pending());
10439
Wez0e717112018-06-18 23:09:2210440 d.RunUntilCertificateRequested();
10441 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810442
10443 EXPECT_EQ(1, d.on_certificate_requested_count());
10444 EXPECT_FALSE(d.received_data_before_response());
10445 EXPECT_EQ(0, d.bytes_received());
10446
10447 // Send a certificate.
10448 r->ContinueWithCertificate(identity->certificate(), private_key);
10449
Wez2a31b222018-06-07 22:07:1510450 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810451
10452 EXPECT_EQ(OK, d.request_status());
10453 EXPECT_EQ(1, d.response_started_count());
10454 EXPECT_FALSE(d.received_data_before_response());
10455 EXPECT_NE(0, d.bytes_received());
10456
10457 // The private key should have been used.
10458 EXPECT_EQ(1, private_key->sign_count());
10459 }
10460
10461 // Close all connections and clear the session cache to force a new handshake.
10462 default_context_.http_transaction_factory()
10463 ->GetSession()
10464 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710465 default_context_.http_transaction_factory()
10466 ->GetSession()
10467 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810468
10469 // Connecting again should not call OnCertificateRequested. The identity is
10470 // taken from the client auth cache.
10471 {
10472 SSLClientAuthTestDelegate d;
10473 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10474 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10475 TRAFFIC_ANNOTATION_FOR_TESTS));
10476
10477 r->Start();
10478 EXPECT_TRUE(r->is_pending());
10479
Wez2a31b222018-06-07 22:07:1510480 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810481
10482 EXPECT_EQ(OK, d.request_status());
10483 EXPECT_EQ(0, d.on_certificate_requested_count());
10484 EXPECT_FALSE(d.received_data_before_response());
10485 EXPECT_EQ(1, d.response_started_count());
10486 EXPECT_FALSE(d.received_data_before_response());
10487 EXPECT_NE(0, d.bytes_received());
10488
10489 // The private key should have been used.
10490 EXPECT_EQ(2, private_key->sign_count());
10491 }
10492}
10493
10494// Test that private keys that fail to sign anything get evicted from the cache.
10495TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
10496 std::unique_ptr<FakeClientCertIdentity> identity =
10497 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10498 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10499 ASSERT_TRUE(identity);
10500 scoped_refptr<TestSSLPrivateKey> private_key =
10501 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10502 private_key->set_fail_signing(true);
10503
10504 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10505 net::SSLServerConfig ssl_config;
10506 ssl_config.client_cert_type =
10507 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10508 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10509 test_server.AddDefaultHandlers(
10510 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10511 ASSERT_TRUE(test_server.Start());
10512
10513 {
10514 SSLClientAuthTestDelegate d;
10515 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10516 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10517 TRAFFIC_ANNOTATION_FOR_TESTS));
10518
10519 r->Start();
10520 EXPECT_TRUE(r->is_pending());
Wez0e717112018-06-18 23:09:2210521
10522 d.RunUntilCertificateRequested();
10523 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810524
10525 EXPECT_EQ(1, d.on_certificate_requested_count());
10526 EXPECT_FALSE(d.received_data_before_response());
10527 EXPECT_EQ(0, d.bytes_received());
10528
10529 // Send a certificate.
10530 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510531 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810532
10533 // The private key cannot sign anything, so we report an error.
10534 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
10535 EXPECT_EQ(1, d.response_started_count());
10536 EXPECT_FALSE(d.received_data_before_response());
10537 EXPECT_EQ(0, d.bytes_received());
10538
10539 // The private key should have been used.
10540 EXPECT_EQ(1, private_key->sign_count());
10541 }
10542
10543 // Close all connections and clear the session cache to force a new handshake.
10544 default_context_.http_transaction_factory()
10545 ->GetSession()
10546 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710547 default_context_.http_transaction_factory()
10548 ->GetSession()
10549 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810550
10551 // The bad identity should have been evicted from the cache, so connecting
10552 // again should call OnCertificateRequested again.
10553 {
10554 SSLClientAuthTestDelegate d;
10555 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10556 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10557 TRAFFIC_ANNOTATION_FOR_TESTS));
10558
10559 r->Start();
10560 EXPECT_TRUE(r->is_pending());
10561
Wez0e717112018-06-18 23:09:2210562 d.RunUntilCertificateRequested();
10563 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810564
10565 EXPECT_EQ(1, d.on_certificate_requested_count());
10566 EXPECT_FALSE(d.received_data_before_response());
10567 EXPECT_EQ(0, d.bytes_received());
10568
10569 // There should have been no additional uses of the private key.
10570 EXPECT_EQ(1, private_key->sign_count());
10571 }
10572}
10573
10574// Test that cached private keys that fail to sign anything trigger a
10575// retry. This is so we handle unplugged smartcards
10576// gracefully. https://crbug.com/813022.
10577TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
10578 std::unique_ptr<FakeClientCertIdentity> identity =
10579 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10580 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10581 ASSERT_TRUE(identity);
10582 scoped_refptr<TestSSLPrivateKey> private_key =
10583 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10584
10585 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10586 net::SSLServerConfig ssl_config;
10587 ssl_config.client_cert_type =
10588 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10589 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10590 test_server.AddDefaultHandlers(
10591 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10592 ASSERT_TRUE(test_server.Start());
10593
10594 // Connect with a client certificate to put it in the client auth cache.
10595 {
10596 SSLClientAuthTestDelegate d;
10597 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10598 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10599 TRAFFIC_ANNOTATION_FOR_TESTS));
10600
10601 r->Start();
10602 EXPECT_TRUE(r->is_pending());
10603
Wez0e717112018-06-18 23:09:2210604 d.RunUntilCertificateRequested();
10605 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810606
10607 EXPECT_EQ(1, d.on_certificate_requested_count());
10608 EXPECT_FALSE(d.received_data_before_response());
10609 EXPECT_EQ(0, d.bytes_received());
10610
10611 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510612 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810613
10614 EXPECT_EQ(OK, d.request_status());
10615 EXPECT_EQ(1, d.response_started_count());
10616 EXPECT_FALSE(d.received_data_before_response());
10617 EXPECT_NE(0, d.bytes_received());
10618
10619 // The private key should have been used.
10620 EXPECT_EQ(1, private_key->sign_count());
10621 }
10622
10623 // Close all connections and clear the session cache to force a new handshake.
10624 default_context_.http_transaction_factory()
10625 ->GetSession()
10626 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710627 default_context_.http_transaction_factory()
10628 ->GetSession()
10629 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810630
10631 // Cause the private key to fail. Connecting again should attempt to use it,
10632 // notice the failure, and then request a new identity via
10633 // OnCertificateRequested.
10634 private_key->set_fail_signing(true);
10635
10636 {
10637 SSLClientAuthTestDelegate d;
10638 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10639 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10640 TRAFFIC_ANNOTATION_FOR_TESTS));
10641
10642 r->Start();
10643 EXPECT_TRUE(r->is_pending());
10644
Wez0e717112018-06-18 23:09:2210645 d.RunUntilCertificateRequested();
10646 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810647
10648 // There was an additional signing call on the private key (the one which
10649 // failed).
10650 EXPECT_EQ(2, private_key->sign_count());
10651
10652 // That caused another OnCertificateRequested call.
10653 EXPECT_EQ(1, d.on_certificate_requested_count());
10654 EXPECT_FALSE(d.received_data_before_response());
10655 EXPECT_EQ(0, d.bytes_received());
10656 }
10657}
10658
[email protected]316c1e5e2012-09-12 15:17:4410659TEST_F(HTTPSRequestTest, ResumeTest) {
10660 // Test that we attempt a session resume when making two connections to the
10661 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:2210662 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410663 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210664 SpawnedTestServer test_server(
10665 SpawnedTestServer::TYPE_HTTPS,
10666 ssl_options,
10667 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410668 ASSERT_TRUE(test_server.Start());
10669
Daniel McArdle3a663d62019-01-31 00:48:4710670 default_context_.http_transaction_factory()
10671 ->GetSession()
10672 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4410673
10674 {
10675 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610676 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610677 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10678 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410679
[email protected]f7022f32014-08-21 16:32:1910680 r->Start();
10681 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410682
Wez2a31b222018-06-07 22:07:1510683 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410684
10685 EXPECT_EQ(1, d.response_started_count());
10686 }
10687
10688 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10689 CloseAllConnections();
10690
10691 {
10692 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610693 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610694 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10695 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410696
[email protected]f7022f32014-08-21 16:32:1910697 r->Start();
10698 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410699
Wez2a31b222018-06-07 22:07:1510700 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410701
10702 // The response will look like;
Steven Valdez0ef94d02018-11-19 23:28:1310703 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]316c1e5e2012-09-12 15:17:4410704 // insert abc
10705 // lookup abc
10706 // insert xyz
10707 //
10708 // With a newline at the end which makes the split think that there are
10709 // four lines.
10710
10711 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2910712 std::vector<std::string> lines = base::SplitString(
10713 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Steven Valdez0ef94d02018-11-19 23:28:1310714 ASSERT_EQ(5u, lines.size()) << d.data_received();
[email protected]316c1e5e2012-09-12 15:17:4410715
10716 std::string session_id;
10717
Steven Valdez0ef94d02018-11-19 23:28:1310718 for (size_t i = 0; i < 3; i++) {
brettw3a2c6902015-07-06 19:43:2910719 std::vector<std::string> parts = base::SplitString(
10720 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410721 ASSERT_EQ(2u, parts.size());
Steven Valdez0ef94d02018-11-19 23:28:1310722 if (i % 2 == 1) {
[email protected]316c1e5e2012-09-12 15:17:4410723 EXPECT_EQ("insert", parts[0]);
10724 session_id = parts[1];
10725 } else {
10726 EXPECT_EQ("lookup", parts[0]);
Steven Valdez0ef94d02018-11-19 23:28:1310727 if (i != 0)
10728 EXPECT_EQ(session_id, parts[1]);
[email protected]316c1e5e2012-09-12 15:17:4410729 }
10730 }
10731 }
10732}
10733
10734TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
10735 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
10736 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2210737 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410738 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210739 SpawnedTestServer test_server(
10740 SpawnedTestServer::TYPE_HTTPS,
10741 ssl_options,
10742 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410743 ASSERT_TRUE(test_server.Start());
10744
Daniel McArdle3a663d62019-01-31 00:48:4710745 default_context_.http_transaction_factory()
10746 ->GetSession()
10747 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4410748
10749 {
10750 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610751 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0410752 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1610753 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410754
[email protected]f7022f32014-08-21 16:32:1910755 r->Start();
10756 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410757
Wez2a31b222018-06-07 22:07:1510758 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410759
10760 EXPECT_EQ(1, d.response_started_count());
10761 }
10762
10763 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4110764 HttpNetworkSession::Context session_context;
10765 session_context.host_resolver = default_context_.host_resolver();
10766 session_context.cert_verifier = default_context_.cert_verifier();
10767 session_context.transport_security_state =
10768 default_context_.transport_security_state();
10769 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2010770 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4110771 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5910772 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4110773 session_context.ssl_config_service = default_context_.ssl_config_service();
10774 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4410775 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4110776 session_context.http_server_properties =
10777 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4410778
mmenke6ddfbea2017-05-31 21:48:4110779 HttpNetworkSession network_session(HttpNetworkSession::Params(),
10780 session_context);
zhongyi4928bd52017-02-08 02:16:2710781 std::unique_ptr<HttpCache> cache(
10782 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
10783 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4410784
10785 default_context_.set_http_transaction_factory(cache.get());
10786
10787 {
10788 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610789 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610790 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10791 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410792
[email protected]f7022f32014-08-21 16:32:1910793 r->Start();
10794 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410795
Wez2a31b222018-06-07 22:07:1510796 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410797
[email protected]316c1e5e2012-09-12 15:17:4410798 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0410799 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]316c1e5e2012-09-12 15:17:4410800 }
10801}
10802
Daniel McArdleda3fa942019-02-15 16:41:2110803// Test that sessions started with privacy mode enabled cannot be resumed when
10804// it is disabled, and vice versa.
10805TEST_F(HTTPSRequestTest, NoSessionResumptionBetweenPrivacyModes) {
10806 // Start a server.
10807 SpawnedTestServer test_server(
10808 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(),
10809 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10810 ASSERT_TRUE(test_server.Start());
10811 const auto url = test_server.GetURL("/");
10812
10813 auto ConnectAndCheckHandshake = [this, url](bool allow_credentials,
10814 auto expected_handshake) {
10815 // Construct request and indirectly set the privacy mode.
10816 TestDelegate d;
10817 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10818 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
10819 r->set_allow_credentials(allow_credentials);
10820
10821 // Start the request and check the SSL handshake type.
10822 r->Start();
10823 EXPECT_TRUE(r->is_pending());
10824 d.RunUntilComplete();
10825 EXPECT_EQ(1, d.response_started_count());
10826 EXPECT_EQ(expected_handshake, r->ssl_info().handshake_type);
10827 };
10828
10829 // Exhaustively check all pairs of privacy mode values. Note that we are using
10830 // allow_credentials to indirectly enable/disable privacy mode.
10831 const bool kAllowCredentialsValues[] = {false, true};
10832 for (const auto allow_creds_1 : kAllowCredentialsValues) {
10833 for (const auto allow_creds_2 : kAllowCredentialsValues) {
10834 SCOPED_TRACE(base::StringPrintf("allow_creds_1=%d, allow_creds_2=%d",
10835 allow_creds_1, allow_creds_2));
10836
10837 // The session cache starts off empty, so we expect a full handshake.
10838 ConnectAndCheckHandshake(allow_creds_1, SSLInfo::HANDSHAKE_FULL);
10839
10840 // The second handshake depends on whether we are using the same session
10841 // cache as the first request.
10842 ConnectAndCheckHandshake(allow_creds_2, allow_creds_1 == allow_creds_2
10843 ? SSLInfo::HANDSHAKE_RESUME
10844 : SSLInfo::HANDSHAKE_FULL);
10845 // Flush both session caches.
10846 auto* network_session =
10847 default_context_.http_transaction_factory()->GetSession();
10848 network_session->ClearSSLSessionCache();
10849 }
10850 }
10851}
10852
Bence Béky98447b12018-05-08 03:14:0110853class HTTPSFallbackTest : public TestWithScopedTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:5510854 public:
fdorayf33fede2017-05-11 21:18:1010855 HTTPSFallbackTest() : context_(true) {
Nick Harper2243e8002018-09-28 20:33:2610856 ssl_config_service_ = std::make_unique<TestSSLConfigService>();
davidben095ebb52017-04-12 22:23:3410857 context_.set_ssl_config_service(ssl_config_service_.get());
10858 }
Chris Watkins7a41d3552017-12-01 02:13:2710859 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5510860
10861 protected:
davidben095ebb52017-04-12 22:23:3410862 TestSSLConfigService* ssl_config_service() {
10863 return ssl_config_service_.get();
10864 }
10865
[email protected]48d2b7c52014-06-27 01:16:5510866 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
10867 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0010868 context_.Init();
10869 delegate_.set_allow_certificate_errors(true);
10870
[email protected]48d2b7c52014-06-27 01:16:5510871 SpawnedTestServer test_server(
10872 SpawnedTestServer::TYPE_HTTPS,
10873 ssl_options,
10874 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10875 ASSERT_TRUE(test_server.Start());
10876
tommycli59a63432015-11-06 00:10:5510877 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1610878 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5510879 request_->Start();
10880
Wez2a31b222018-06-07 22:07:1510881 delegate_.RunUntilComplete();
[email protected]48d2b7c52014-06-27 01:16:5510882 }
10883
davidben095ebb52017-04-12 22:23:3410884 void ExpectConnection(int version) {
10885 EXPECT_EQ(1, delegate_.response_started_count());
10886 EXPECT_NE(0, delegate_.bytes_received());
10887 EXPECT_EQ(version, SSLConnectionStatusToVersion(
10888 request_->ssl_info().connection_status));
10889 }
10890
[email protected]48d2b7c52014-06-27 01:16:5510891 void ExpectFailure(int error) {
10892 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5010893 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5510894 }
10895
10896 private:
Ryan Sleevib8449e02018-07-15 04:31:0710897 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5510898 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4710899 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610900 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:5510901};
10902
davidbenb127ca82015-06-15 19:05:4210903// Tests the TLS 1.0 fallback doesn't happen.
10904TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5510905 SpawnedTestServer::SSLOptions ssl_options(
10906 SpawnedTestServer::SSLOptions::CERT_OK);
10907 ssl_options.tls_intolerant =
10908 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
10909
10910 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5510911 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4210912}
10913
davidben5a312152016-06-27 22:11:4710914// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5510915TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4210916 SpawnedTestServer::SSLOptions ssl_options(
10917 SpawnedTestServer::SSLOptions::CERT_OK);
10918 ssl_options.tls_intolerant =
10919 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
10920
10921 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5510922 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
10923}
10924
David Benjamind61bd532019-04-23 21:11:3710925// Tests the TLS 1.2 fallback doesn't happen.
10926TEST_F(HTTPSFallbackTest, TLSv1_2NoFallback) {
davidben095ebb52017-04-12 22:23:3410927 SpawnedTestServer::SSLOptions ssl_options(
10928 SpawnedTestServer::SSLOptions::CERT_OK);
10929 ssl_options.tls_intolerant =
10930 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
davidben095ebb52017-04-12 22:23:3410931
10932 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
David Benjamind61bd532019-04-23 21:11:3710933 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidben095ebb52017-04-12 22:23:3410934}
10935
Bence Béky98447b12018-05-08 03:14:0110936class HTTPSSessionTest : public TestWithScopedTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:2410937 public:
fdorayf33fede2017-05-11 21:18:1010938 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5910939 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410940
10941 default_context_.set_network_delegate(&default_network_delegate_);
10942 default_context_.set_cert_verifier(&cert_verifier_);
10943 default_context_.Init();
10944 }
Chris Watkins7a41d3552017-12-01 02:13:2710945 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2410946
10947 protected:
10948 MockCertVerifier cert_verifier_;
10949 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
10950 TestURLRequestContext default_context_;
10951};
10952
10953// Tests that session resumption is not attempted if an invalid certificate
10954// is presented.
10955TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
10956 SpawnedTestServer::SSLOptions ssl_options;
10957 ssl_options.record_resume = true;
10958 SpawnedTestServer test_server(
10959 SpawnedTestServer::TYPE_HTTPS,
10960 ssl_options,
10961 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10962 ASSERT_TRUE(test_server.Start());
10963
Daniel McArdle3a663d62019-01-31 00:48:4710964 default_context_.http_transaction_factory()
10965 ->GetSession()
10966 ->ClearSSLSessionCache();
[email protected]a8fed1742013-12-27 02:14:2410967
10968 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5910969 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2410970 {
10971 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610972 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0410973 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1610974 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410975
[email protected]f7022f32014-08-21 16:32:1910976 r->Start();
10977 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410978
Wez2a31b222018-06-07 22:07:1510979 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410980
10981 EXPECT_EQ(1, d.response_started_count());
10982 }
10983
10984 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10985 CloseAllConnections();
10986
10987 // Now change the certificate to be acceptable (so that the response is
10988 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910989 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410990 {
10991 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610992 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610993 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10994 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410995
[email protected]f7022f32014-08-21 16:32:1910996 r->Start();
10997 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410998
Wez2a31b222018-06-07 22:07:1510999 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2411000
[email protected]a8fed1742013-12-27 02:14:2411001 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0411002 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]a8fed1742013-12-27 02:14:2411003 }
11004}
11005
[email protected]dffe8242012-03-20 15:14:2711006// This the fingerprint of the "Testing CA" certificate used by the testserver.
11007// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5811008static const SHA256HashValue kOCSPTestCertFingerprint = {{
11009 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
11010 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
11011 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1511012}};
[email protected]dffe8242012-03-20 15:14:2711013
[email protected]51523f52013-07-31 21:57:2811014// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
11015// testserver.
mattm0b12a6f2016-11-29 19:57:1611016static const SHA256HashValue kOCSPTestCertSPKI = {{
11017 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
11018 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
11019 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
11020}};
[email protected]51523f52013-07-31 21:57:2811021
[email protected]dffe8242012-03-20 15:14:2711022// This is the policy OID contained in the certificates that testserver
11023// generates.
11024static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
11025
11026class HTTPSOCSPTest : public HTTPSRequestTest {
11027 public:
11028 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0911029 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0811030 ev_test_policy_(
11031 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
11032 kOCSPTestCertFingerprint,
11033 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0211034 }
11035
dcheng67be2b1f2014-10-27 21:47:2911036 void SetUp() override {
Matt Muellera4aaa9d2019-04-24 21:09:1411037 cert_net_fetcher_ = base::MakeRefCounted<CertNetFetcherImpl>();
11038 cert_verifier_ = CertVerifier::CreateDefault(cert_net_fetcher_);
11039 context_.set_cert_verifier(cert_verifier_.get());
Ryan Sleevi8a9c9c12018-05-09 02:36:2311040 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
[email protected]ef2bf422012-05-11 03:27:0911041 context_.Init();
[email protected]dffe8242012-03-20 15:14:2711042
Matt Muellera4aaa9d2019-04-24 21:09:1411043 cert_net_fetcher_->SetURLRequestContext(&context_);
Ryan Sleevi24fe2682018-08-16 21:33:4611044 context_.cert_verifier()->SetConfig(GetCertVerifierConfig());
11045
[email protected]cba24642014-08-15 20:49:5911046 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2011047 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
Matt Mueller09c8fd9a2019-05-04 00:37:2411048 ASSERT_TRUE(root_cert);
[email protected]90499482013-06-01 00:39:5011049 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2711050
svaldez2135be52016-04-20 16:34:5311051#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0911052 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2711053#endif
11054 }
11055
dadrian612337a2016-07-20 22:36:5811056 void DoConnectionWithDelegate(
11057 const SpawnedTestServer::SSLOptions& ssl_options,
11058 TestDelegate* delegate,
11059 SSLInfo* out_ssl_info) {
11060 // Always overwrite |out_ssl_info|.
11061 out_ssl_info->Reset();
11062
[email protected]ce7d0cbc2013-05-03 18:57:2211063 SpawnedTestServer test_server(
11064 SpawnedTestServer::TYPE_HTTPS,
11065 ssl_options,
11066 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2711067 ASSERT_TRUE(test_server.Start());
11068
dadrian612337a2016-07-20 22:36:5811069 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1611070 std::unique_ptr<URLRequest> r(
11071 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
11072 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911073 r->Start();
[email protected]dffe8242012-03-20 15:14:2711074
Wez2a31b222018-06-07 22:07:1511075 delegate->RunUntilComplete();
dadrian612337a2016-07-20 22:36:5811076 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2711077
dadrian612337a2016-07-20 22:36:5811078 *out_ssl_info = r->ssl_info();
11079 }
11080
11081 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
11082 CertStatus* out_cert_status) {
11083 // Always overwrite |out_cert_status|.
11084 *out_cert_status = 0;
11085
11086 TestDelegate d;
11087 SSLInfo ssl_info;
11088 ASSERT_NO_FATAL_FAILURE(
11089 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
11090
11091 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2711092 }
11093
dcheng67be2b1f2014-10-27 21:47:2911094 ~HTTPSOCSPTest() override {
Matt Muellera4aaa9d2019-04-24 21:09:1411095 cert_net_fetcher_->Shutdown();
svaldez2135be52016-04-20 16:34:5311096#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1811097 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2711098#endif
11099 }
11100
[email protected]a13234c2012-03-20 21:45:0211101 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611102 // GetCertVerifierConfig() configures the URLRequestContext that will be used
11103 // for making connections to the testserver. This can be overridden in test
11104 // subclasses for different behaviour.
11105 virtual CertVerifier::Config GetCertVerifierConfig() {
11106 CertVerifier::Config config;
11107 config.enable_rev_checking = true;
11108 return config;
[email protected]a13234c2012-03-20 21:45:0211109 }
11110
danakj8522a25b2016-04-16 00:17:3611111 std::unique_ptr<ScopedTestRoot> test_root_;
Ryan Sleevib8449e02018-07-15 04:31:0711112 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
Matt Muellera4aaa9d2019-04-24 21:09:1411113 scoped_refptr<CertNetFetcherImpl> cert_net_fetcher_;
11114 std::unique_ptr<CertVerifier> cert_verifier_;
[email protected]ef2bf422012-05-11 03:27:0911115 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3611116 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2711117};
11118
[email protected]a13234c2012-03-20 21:45:0211119static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2011120#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0211121 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
11122 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0411123 // TODO(eroman): Should this also be the return value for
11124 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0211125 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
11126#else
11127 return 0;
11128#endif
11129}
11130
[email protected]3a86a712013-07-30 07:16:2011131// SystemSupportsHardFailRevocationChecking returns true iff the current
11132// operating system supports revocation checking and can distinguish between
11133// situations where a given certificate lacks any revocation information (eg:
11134// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
11135// revocation information cannot be obtained (eg: the CRL was unreachable).
11136// If it does not, then tests which rely on 'hard fail' behaviour should be
11137// skipped.
11138static bool SystemSupportsHardFailRevocationChecking() {
Eric Roman1b628daa2017-10-19 19:52:0411139#if defined(OS_WIN) || defined(USE_NSS_CERTS) || \
11140 defined(USE_BUILTIN_CERT_VERIFIER)
[email protected]3a86a712013-07-30 07:16:2011141 return true;
11142#else
11143 return false;
11144#endif
11145}
11146
[email protected]a13234c2012-03-20 21:45:0211147// SystemUsesChromiumEVMetadata returns true iff the current operating system
11148// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
11149// several tests are effected because our testing EV certificate won't be
11150// recognised as EV.
11151static bool SystemUsesChromiumEVMetadata() {
Eric Roman5f8d9d22017-10-17 02:32:5211152#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0111153 return true;
Eric Roman5f8d9d22017-10-17 02:32:5211154#else
11155 return false;
[email protected]05454a432012-03-20 20:04:0111156#endif
11157}
11158
mattmaf868e72016-09-23 23:25:2011159// Returns the expected CertStatus for tests that expect an online revocation
11160// check failure as a result of checking a test EV cert, which will not
11161// actually trigger an online revocation check on some platforms.
11162static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
11163 if (SystemUsesChromiumEVMetadata()) {
11164 return ExpectedCertStatusForFailedOnlineRevocationCheck();
11165 } else {
11166 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
11167 // be enabled, and thus there will not be a revocation check to fail.
11168 return 0u;
11169 }
11170}
11171
[email protected]b6f2de32012-08-17 04:35:0811172static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3911173#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0211174 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
11175 return false;
11176#else
11177 return true;
11178#endif
11179}
11180
davidbend1fb2f12014-11-08 02:51:0011181static bool SystemSupportsOCSPStapling() {
Matt Mueller7f60dc42019-04-26 22:47:1011182#if defined(OS_ANDROID)
mathpc992e602015-10-21 20:34:0311183 return false;
Matt Mueller7f60dc42019-04-26 22:47:1011184#elif defined(OS_MACOSX)
11185 // The SecTrustSetOCSPResponse function exists since macOS 10.9+, but does
11186 // not actually do anything until 10.12.
11187 if (base::mac::IsAtLeastOS10_12())
11188 return true;
11189 return false;
11190#else
11191 return true;
mathpc992e602015-10-21 20:34:0311192#endif
davidbend1fb2f12014-11-08 02:51:0011193}
11194
[email protected]dffe8242012-03-20 15:14:2711195TEST_F(HTTPSOCSPTest, Valid) {
11196 if (!SystemSupportsOCSP()) {
11197 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11198 return;
11199 }
11200
[email protected]ce7d0cbc2013-05-03 18:57:2211201 SpawnedTestServer::SSLOptions ssl_options(
11202 SpawnedTestServer::SSLOptions::CERT_AUTO);
11203 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2711204
[email protected]924e9f92012-12-16 22:00:5311205 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211206 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711207
11208 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11209
[email protected]a13234c2012-03-20 21:45:0211210 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11211 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2711212
11213 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11214}
11215
11216TEST_F(HTTPSOCSPTest, Revoked) {
11217 if (!SystemSupportsOCSP()) {
11218 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11219 return;
11220 }
11221
[email protected]ce7d0cbc2013-05-03 18:57:2211222 SpawnedTestServer::SSLOptions ssl_options(
11223 SpawnedTestServer::SSLOptions::CERT_AUTO);
11224 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2711225
11226 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211227 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711228
[email protected]dffe8242012-03-20 15:14:2711229 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2711230 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11231 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11232}
11233
11234TEST_F(HTTPSOCSPTest, Invalid) {
11235 if (!SystemSupportsOCSP()) {
11236 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11237 return;
11238 }
11239
[email protected]ce7d0cbc2013-05-03 18:57:2211240 SpawnedTestServer::SSLOptions ssl_options(
11241 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811242 ssl_options.ocsp_status =
11243 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2711244
[email protected]924e9f92012-12-16 22:00:5311245 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211246 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711247
Eric Roman1b628daa2017-10-19 19:52:0411248#if defined(USE_BUILTIN_CERT_VERIFIER)
11249 // TODO(649017): This test uses soft-fail revocation checking, but returns an
11250 // invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
11251 // doesn't consider this a candidate for soft-fail (only considers
11252 // network-level failures as skippable).
11253 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11254 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11255#else
[email protected]a13234c2012-03-20 21:45:0211256 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2711257 cert_status & CERT_STATUS_ALL_ERRORS);
Eric Roman1b628daa2017-10-19 19:52:0411258#endif
[email protected]dffe8242012-03-20 15:14:2711259
11260 // Without a positive OCSP response, we shouldn't show the EV status.
11261 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11262 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11263}
[email protected]a13234c2012-03-20 21:45:0211264
Matt Mueller5339d862018-05-02 18:53:5711265TEST_F(HTTPSOCSPTest, IntermediateValid) {
11266 if (!SystemSupportsOCSP()) {
11267 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11268 return;
11269 }
11270
11271 SpawnedTestServer::SSLOptions ssl_options(
11272 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11273 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11274 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11275
11276 CertStatus cert_status;
11277 DoConnection(ssl_options, &cert_status);
11278
11279 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11280
11281 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11282 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11283
11284 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11285}
11286
11287TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
11288 if (!SystemSupportsOCSP()) {
11289 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11290 return;
11291 }
11292
11293 SpawnedTestServer::SSLOptions ssl_options(
11294 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11295 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11296 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11297 // Use an OCSP response for the intermediate that would be too old for a leaf
11298 // cert, but is still valid for an intermediate.
11299 ssl_options.ocsp_intermediate_date =
11300 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
11301
11302 CertStatus cert_status;
11303 DoConnection(ssl_options, &cert_status);
11304
11305 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11306
11307 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11308 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11309
11310 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11311}
11312
11313TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
11314 if (!SystemSupportsOCSP()) {
11315 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11316 return;
11317 }
11318
11319 SpawnedTestServer::SSLOptions ssl_options(
11320 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11321 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11322 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11323 ssl_options.ocsp_intermediate_date =
11324 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
11325
11326 CertStatus cert_status;
11327 DoConnection(ssl_options, &cert_status);
11328
11329#if defined(USE_BUILTIN_CERT_VERIFIER)
11330 // The builtin verifier enforces the baseline requirements for max age of an
11331 // intermediate's OCSP response.
11332 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11333 cert_status & CERT_STATUS_ALL_ERRORS);
11334 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11335#else
11336 // The platform verifiers are more lenient.
11337 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11338 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11339 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11340#endif
11341 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11342}
11343
11344TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
11345 if (!SystemSupportsOCSP()) {
11346 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11347 return;
11348 }
11349
11350 SpawnedTestServer::SSLOptions ssl_options(
11351 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11352 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11353 ssl_options.ocsp_intermediate_status =
11354 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11355
11356 CertStatus cert_status;
11357 DoConnection(ssl_options, &cert_status);
11358
11359#if defined(OS_WIN)
11360 // TODO(mattm): why does CertVerifyProcWin accept this?
11361 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11362#else
11363 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11364#endif
11365 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11366 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11367}
11368
davidbend1fb2f12014-11-08 02:51:0011369TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0311370 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011371 LOG(WARNING)
11372 << "Skipping test because system doesn't support OCSP stapling";
11373 return;
11374 }
11375
11376 SpawnedTestServer::SSLOptions ssl_options(
11377 SpawnedTestServer::SSLOptions::CERT_AUTO);
11378 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11379 ssl_options.staple_ocsp_response = true;
11380 ssl_options.ocsp_server_unavailable = true;
11381
11382 CertStatus cert_status;
11383 DoConnection(ssl_options, &cert_status);
11384
11385 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11386
11387 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11388 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11389
11390 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11391}
11392
davidben6c3191b2014-11-21 22:38:0411393// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4811394#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0411395#define MAYBE_RevokedStapled DISABLED_RevokedStapled
11396#else
11397#define MAYBE_RevokedStapled RevokedStapled
11398#endif
11399TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0311400 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011401 LOG(WARNING)
11402 << "Skipping test because system doesn't support OCSP stapling";
11403 return;
11404 }
11405
11406 SpawnedTestServer::SSLOptions ssl_options(
11407 SpawnedTestServer::SSLOptions::CERT_AUTO);
11408 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11409 ssl_options.staple_ocsp_response = true;
11410 ssl_options.ocsp_server_unavailable = true;
11411
11412 CertStatus cert_status;
11413 DoConnection(ssl_options, &cert_status);
11414
11415 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11416 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11417 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11418}
11419
dadrian612337a2016-07-20 22:36:5811420static const struct OCSPVerifyTestData {
11421 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
11422 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
11423 OCSPVerifyResult::ResponseStatus response_status;
11424 bool has_revocation_status;
11425 OCSPRevocationStatus cert_status;
11426} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3111427 // 0
dadrian612337a2016-07-20 22:36:5811428 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11429 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11430 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11431 OCSPVerifyResult::PROVIDED,
11432 true,
11433 OCSPRevocationStatus::GOOD},
11434
Eric Roman8673b812017-09-20 18:57:3111435 // 1
dadrian612337a2016-07-20 22:36:5811436 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11437 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11438 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11439 OCSPVerifyResult::INVALID_DATE,
11440 false,
11441 OCSPRevocationStatus::UNKNOWN},
11442
Eric Roman8673b812017-09-20 18:57:3111443 // 2
dadrian612337a2016-07-20 22:36:5811444 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11445 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11446 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11447 OCSPVerifyResult::INVALID_DATE,
11448 false,
11449 OCSPRevocationStatus::UNKNOWN},
11450
Eric Roman8673b812017-09-20 18:57:3111451 // 3
dadrian612337a2016-07-20 22:36:5811452 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11453 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11454 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11455 OCSPVerifyResult::INVALID_DATE,
11456 false,
11457 OCSPRevocationStatus::UNKNOWN},
11458
Eric Roman8673b812017-09-20 18:57:3111459 // 4
dadrian612337a2016-07-20 22:36:5811460 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11461 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11462 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11463 OCSPVerifyResult::INVALID_DATE,
11464 false,
11465 OCSPRevocationStatus::UNKNOWN},
11466
Eric Roman8673b812017-09-20 18:57:3111467 // 5
dadrian612337a2016-07-20 22:36:5811468 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
11469 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11470 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11471 OCSPVerifyResult::ERROR_RESPONSE,
11472 false,
11473 OCSPRevocationStatus::UNKNOWN},
11474
Eric Roman8673b812017-09-20 18:57:3111475 // 6
dadrian612337a2016-07-20 22:36:5811476 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
11477 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11478 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11479 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
11480 false,
11481 OCSPRevocationStatus::UNKNOWN},
11482
Eric Roman8673b812017-09-20 18:57:3111483 // 7
dadrian612337a2016-07-20 22:36:5811484 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
11485 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11486 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11487 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
11488 false,
11489 OCSPRevocationStatus::UNKNOWN},
11490
Eric Roman8673b812017-09-20 18:57:3111491 // 8
dadrian612337a2016-07-20 22:36:5811492 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11493 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11494 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11495 OCSPVerifyResult::INVALID_DATE,
11496 false,
11497 OCSPRevocationStatus::UNKNOWN},
11498
Eric Roman8673b812017-09-20 18:57:3111499 // 9
dadrian612337a2016-07-20 22:36:5811500 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11501 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11502 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11503 OCSPVerifyResult::PROVIDED,
11504 true,
11505 OCSPRevocationStatus::UNKNOWN},
11506
Eric Roman8673b812017-09-20 18:57:3111507 // 10
dadrian612337a2016-07-20 22:36:5811508 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11509 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11510 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11511 OCSPVerifyResult::INVALID_DATE,
11512 false,
11513 OCSPRevocationStatus::UNKNOWN},
11514
Eric Roman8673b812017-09-20 18:57:3111515 // 11
dadrian612337a2016-07-20 22:36:5811516 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11517 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11518 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11519 OCSPVerifyResult::INVALID_DATE,
11520 false,
11521 OCSPRevocationStatus::UNKNOWN},
11522
Eric Roman8673b812017-09-20 18:57:3111523 // 12
dadrian612337a2016-07-20 22:36:5811524 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11525 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11526 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
11527 OCSPVerifyResult::BAD_PRODUCED_AT,
11528 false,
11529 OCSPRevocationStatus::UNKNOWN},
11530
Eric Roman8673b812017-09-20 18:57:3111531 // 13
dadrian612337a2016-07-20 22:36:5811532 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11533 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11534 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11535 OCSPVerifyResult::BAD_PRODUCED_AT,
11536 false,
11537 OCSPRevocationStatus::UNKNOWN},
11538
Eric Roman8673b812017-09-20 18:57:3111539 // 14
dadrian612337a2016-07-20 22:36:5811540 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11541 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11542 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11543 OCSPVerifyResult::BAD_PRODUCED_AT,
11544 false,
11545 OCSPRevocationStatus::UNKNOWN},
11546
Eric Roman8673b812017-09-20 18:57:3111547 // 15
dadrian612337a2016-07-20 22:36:5811548 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11549 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11550 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11551 OCSPVerifyResult::PROVIDED,
11552 true,
11553 OCSPRevocationStatus::GOOD},
11554
Eric Roman8673b812017-09-20 18:57:3111555 // 16
dadrian612337a2016-07-20 22:36:5811556 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11557 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11558 {SpawnedTestServer::SSLOptions::OCSP_OK,
11559 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11560 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11561 OCSPVerifyResult::PROVIDED,
11562 true,
11563 OCSPRevocationStatus::GOOD},
11564
Eric Roman8673b812017-09-20 18:57:3111565 // 17
dadrian612337a2016-07-20 22:36:5811566 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11567 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11568 {SpawnedTestServer::SSLOptions::OCSP_OK,
11569 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11570 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11571 OCSPVerifyResult::PROVIDED,
11572 true,
11573 OCSPRevocationStatus::GOOD},
11574
Eric Roman8673b812017-09-20 18:57:3111575 // 18
dadrian612337a2016-07-20 22:36:5811576 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11577 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11578 {SpawnedTestServer::SSLOptions::OCSP_OK,
11579 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11580 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11581 OCSPVerifyResult::PROVIDED,
11582 true,
11583 OCSPRevocationStatus::GOOD},
11584
Eric Roman8673b812017-09-20 18:57:3111585 // 19
dadrian612337a2016-07-20 22:36:5811586 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11587 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11588 {SpawnedTestServer::SSLOptions::OCSP_OK,
11589 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11590 {SpawnedTestServer::SSLOptions::OCSP_OK,
11591 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11592 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11593 OCSPVerifyResult::INVALID_DATE,
11594 false,
11595 OCSPRevocationStatus::UNKNOWN},
11596
Eric Roman8673b812017-09-20 18:57:3111597 // 20
dadrian612337a2016-07-20 22:36:5811598 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11599 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11600 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11601 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11602 {SpawnedTestServer::SSLOptions::OCSP_OK,
11603 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11604 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11605 OCSPVerifyResult::PROVIDED,
11606 true,
11607 OCSPRevocationStatus::REVOKED},
11608
Eric Roman8673b812017-09-20 18:57:3111609 // 21
dadrian612337a2016-07-20 22:36:5811610 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11611 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11612 {SpawnedTestServer::SSLOptions::OCSP_OK,
11613 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11614 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11615 OCSPVerifyResult::PROVIDED,
11616 true,
11617 OCSPRevocationStatus::UNKNOWN},
11618
Eric Roman8673b812017-09-20 18:57:3111619 // 22
dadrian612337a2016-07-20 22:36:5811620 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11621 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11622 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11623 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11624 {SpawnedTestServer::SSLOptions::OCSP_OK,
11625 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11626 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11627 OCSPVerifyResult::PROVIDED,
11628 true,
11629 OCSPRevocationStatus::UNKNOWN},
11630
Eric Roman8673b812017-09-20 18:57:3111631 // 23
dadrian612337a2016-07-20 22:36:5811632 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11633 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11634 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11635 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11636 false,
11637 OCSPRevocationStatus::UNKNOWN},
11638
Eric Roman8673b812017-09-20 18:57:3111639 // 24
dadrian612337a2016-07-20 22:36:5811640 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11641 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11642 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11643 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11644 false,
11645 OCSPRevocationStatus::UNKNOWN},
11646
Eric Roman8673b812017-09-20 18:57:3111647// These tests fail when using NSS for certificate verification, as NSS fails
11648// and doesn't return the partial path. As a result the OCSP checks being done
11649// at the CertVerifyProc layer cannot access the issuer certificate.
11650#if !defined(USE_NSS_CERTS)
11651 // 25
11652 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11653 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11654 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11655 OCSPVerifyResult::PROVIDED,
11656 true,
11657 OCSPRevocationStatus::REVOKED},
11658
11659 // 26
11660 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11661 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11662 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11663 OCSPVerifyResult::INVALID_DATE,
11664 false,
11665 OCSPRevocationStatus::UNKNOWN},
11666
11667 // 27
11668 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11669 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11670 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11671 OCSPVerifyResult::INVALID_DATE,
11672 false,
11673 OCSPRevocationStatus::UNKNOWN},
11674#endif
dadrian612337a2016-07-20 22:36:5811675};
11676
11677class HTTPSOCSPVerifyTest
11678 : public HTTPSOCSPTest,
11679 public testing::WithParamInterface<OCSPVerifyTestData> {};
11680
Christos Froussios09e6ac42019-04-05 14:08:2011681// TODO(crbug.com/949958): The test is flaky on Mac
11682#if defined(OS_MACOSX)
11683#define MAYBE_VerifyResult DISABLED_VerifyResult
11684#else
11685#define MAYBE_VerifyResult VerifyResult
11686#endif
11687TEST_P(HTTPSOCSPVerifyTest, MAYBE_VerifyResult) {
dadrian612337a2016-07-20 22:36:5811688 SpawnedTestServer::SSLOptions ssl_options(
11689 SpawnedTestServer::SSLOptions::CERT_AUTO);
11690 OCSPVerifyTestData test = GetParam();
11691
11692 ssl_options.ocsp_responses = test.ocsp_responses;
11693 ssl_options.ocsp_produced = test.ocsp_produced;
11694 ssl_options.staple_ocsp_response = true;
11695
11696 SSLInfo ssl_info;
11697 OCSPErrorTestDelegate delegate;
11698 ASSERT_NO_FATAL_FAILURE(
11699 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
11700
11701 // The SSLInfo must be extracted from |delegate| on error, due to how
11702 // URLRequest caches certificate errors.
11703 if (delegate.have_certificate_errors()) {
11704 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
11705 ssl_info = delegate.ssl_info();
11706 }
11707
11708 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
11709
11710 if (test.has_revocation_status)
11711 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
11712}
11713
Victor Costan8fb98f6f2019-02-01 17:08:2911714INSTANTIATE_TEST_SUITE_P(OCSPVerify,
11715 HTTPSOCSPVerifyTest,
11716 testing::ValuesIn(kOCSPVerifyData));
dadrian612337a2016-07-20 22:36:5811717
mattm0b12a6f2016-11-29 19:57:1611718class HTTPSAIATest : public HTTPSOCSPTest {
11719 public:
Ryan Sleevi24fe2682018-08-16 21:33:4611720 CertVerifier::Config GetCertVerifierConfig() override {
11721 CertVerifier::Config config;
11722 return config;
mattm0b12a6f2016-11-29 19:57:1611723 }
11724};
11725
11726TEST_F(HTTPSAIATest, AIAFetching) {
11727 SpawnedTestServer::SSLOptions ssl_options(
11728 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
11729 SpawnedTestServer test_server(
11730 SpawnedTestServer::TYPE_HTTPS, ssl_options,
11731 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11732 ASSERT_TRUE(test_server.Start());
11733
Ryan Sleevi5b4702a2018-04-06 22:23:5611734 // Unmark the certificate's OID as EV, which will disable revocation
11735 // checking.
11736 ev_test_policy_.reset();
11737
mattm0b12a6f2016-11-29 19:57:1611738 TestDelegate d;
11739 d.set_allow_certificate_errors(true);
11740 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611741 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11742 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611743
11744 r->Start();
11745 EXPECT_TRUE(r->is_pending());
11746
Wez2a31b222018-06-07 22:07:1511747 d.RunUntilComplete();
mattm0b12a6f2016-11-29 19:57:1611748
11749 EXPECT_EQ(1, d.response_started_count());
11750
11751 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4811752 EXPECT_EQ(OK, d.request_status());
11753 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11754 ASSERT_TRUE(r->ssl_info().cert);
11755 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611756 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3411757 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611758}
11759
[email protected]3a86a712013-07-30 07:16:2011760class HTTPSHardFailTest : public HTTPSOCSPTest {
11761 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611762 CertVerifier::Config GetCertVerifierConfig() override {
11763 CertVerifier::Config config;
11764 config.require_rev_checking_local_anchors = true;
11765 return config;
[email protected]3a86a712013-07-30 07:16:2011766 }
11767};
11768
[email protected]3a86a712013-07-30 07:16:2011769TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
11770 if (!SystemSupportsOCSP()) {
11771 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11772 return;
11773 }
11774
11775 if (!SystemSupportsHardFailRevocationChecking()) {
11776 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
11777 << "revocation checking";
11778 return;
11779 }
11780
11781 SpawnedTestServer::SSLOptions ssl_options(
11782 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811783 ssl_options.ocsp_status =
11784 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2011785
11786 CertStatus cert_status;
11787 DoConnection(ssl_options, &cert_status);
11788
Eric Roman1b628daa2017-10-19 19:52:0411789#if defined(USE_BUILTIN_CERT_VERIFIER)
11790 // TODO(crbug.com/649017): Should we consider invalid response as
11791 // affirmatively revoked?
11792 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11793 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11794#else
11795 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
11796#endif
[email protected]3a86a712013-07-30 07:16:2011797
11798 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0411799 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2011800 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11801}
11802
[email protected]a13234c2012-03-20 21:45:0211803class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
11804 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611805 CertVerifier::Config GetCertVerifierConfig() override {
11806 CertVerifier::Config config;
11807 return config;
[email protected]a13234c2012-03-20 21:45:0211808 }
11809};
11810
11811TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
11812 if (!SystemSupportsOCSP()) {
11813 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11814 return;
11815 }
11816
[email protected]ce7d0cbc2013-05-03 18:57:2211817 SpawnedTestServer::SSLOptions ssl_options(
11818 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811819 ssl_options.ocsp_status =
11820 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0211821
[email protected]924e9f92012-12-16 22:00:5311822 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211823 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211824
mattmaf868e72016-09-23 23:25:2011825 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211826 cert_status & CERT_STATUS_ALL_ERRORS);
11827
11828 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811829 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11830 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211831}
11832
[email protected]be0fff62013-08-29 23:37:4811833TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
11834 if (!SystemSupportsOCSP()) {
11835 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11836 return;
11837 }
11838
11839 SpawnedTestServer::SSLOptions ssl_options(
11840 SpawnedTestServer::SSLOptions::CERT_AUTO);
11841 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]be0fff62013-08-29 23:37:4811842
11843 CertStatus cert_status;
11844 DoConnection(ssl_options, &cert_status);
11845
mattm1a282f52016-11-10 21:49:4211846// Currently only works for Windows and OS X. When using NSS, it's not
11847// possible to determine whether the check failed because of actual
11848// revocation or because there was an OCSP failure.
11849#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4811850 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11851#else
11852 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11853#endif
11854
11855 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11856 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11857 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11858}
11859
[email protected]a13234c2012-03-20 21:45:0211860TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
11861 if (!SystemSupportsOCSP()) {
11862 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11863 return;
11864 }
11865
[email protected]ce7d0cbc2013-05-03 18:57:2211866 SpawnedTestServer::SSLOptions ssl_options(
11867 SpawnedTestServer::SSLOptions::CERT_AUTO);
11868 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0211869
11870 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211871 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211872
11873 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11874
11875 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11876 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0811877 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11878 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211879}
11880
11881TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
11882 if (!SystemSupportsOCSP()) {
11883 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11884 return;
11885 }
11886
[email protected]ce7d0cbc2013-05-03 18:57:2211887 SpawnedTestServer::SSLOptions ssl_options(
11888 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811889 ssl_options.ocsp_status =
11890 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211891 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11892 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11893 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211894
11895 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211896 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211897
mattmaf868e72016-09-23 23:25:2011898 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211899 cert_status & CERT_STATUS_ALL_ERRORS);
11900
11901 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811902 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11903 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211904}
11905
[email protected]51523f52013-07-31 21:57:2811906TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
11907 if (!SystemSupportsOCSP()) {
11908 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11909 return;
11910 }
11911
11912 SpawnedTestServer::SSLOptions ssl_options(
11913 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811914 ssl_options.ocsp_status =
11915 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211916 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11917 cert_verifier_config.crl_set =
11918 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {});
11919 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2811920
11921 CertStatus cert_status;
11922 DoConnection(ssl_options, &cert_status);
11923
11924 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
11925 // revocation check for EV.
11926 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11927 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11928 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11929 EXPECT_FALSE(
11930 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11931}
11932
11933TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
11934 if (!SystemSupportsOCSP()) {
11935 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11936 return;
11937 }
11938
[email protected]ce7d0cbc2013-05-03 18:57:2211939 SpawnedTestServer::SSLOptions ssl_options(
11940 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811941 ssl_options.ocsp_status =
11942 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211943 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11944 cert_verifier_config.crl_set = CRLSet::EmptyCRLSetForTesting();
11945 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211946
[email protected]51523f52013-07-31 21:57:2811947 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1211948 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211949
[email protected]51523f52013-07-31 21:57:2811950 // Even with a fresh CRLSet, we should still do online revocation checks when
11951 // the certificate chain isn't covered by the CRLSet, which it isn't in this
11952 // test.
mattmaf868e72016-09-23 23:25:2011953 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2811954 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0211955
[email protected]51523f52013-07-31 21:57:2811956 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0211957 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2811958 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211959}
11960
11961class HTTPSCRLSetTest : public HTTPSOCSPTest {
11962 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611963 CertVerifier::Config GetCertVerifierConfig() override {
11964 CertVerifier::Config config;
11965 return config;
Ryan Sleevi5b4702a2018-04-06 22:23:5611966 }
11967
11968 void SetUp() override {
11969 HTTPSOCSPTest::SetUp();
11970
11971 // Unmark the certificate's OID as EV, which should disable revocation
11972 // checking (as per the user preference).
11973 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0211974 }
11975};
11976
11977TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2211978 SpawnedTestServer::SSLOptions ssl_options(
11979 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811980 ssl_options.ocsp_status =
11981 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211982 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11983 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11984 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211985
[email protected]924e9f92012-12-16 22:00:5311986 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211987 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211988
11989 // If we're not trying EV verification then, even if the CRLSet has expired,
11990 // we don't fall back to online revocation checks.
11991 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11992 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11993 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11994}
[email protected]51523f52013-07-31 21:57:2811995
Ryan Sleevi5b4702a2018-04-06 22:23:5611996TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
11997 // Test that when online revocation checking is disabled, and the leaf
11998 // certificate is not EV, that no revocation checking actually happens.
11999 if (!SystemSupportsOCSP()) {
12000 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12001 return;
12002 }
12003
12004 SpawnedTestServer::SSLOptions ssl_options(
12005 SpawnedTestServer::SSLOptions::CERT_AUTO);
12006 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Ryan Sleevib369d712018-08-20 16:43:2212007
12008 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12009 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
12010 context_.cert_verifier()->SetConfig(cert_verifier_config);
Ryan Sleevi5b4702a2018-04-06 22:23:5612011
12012 CertStatus cert_status;
12013 DoConnection(ssl_options, &cert_status);
12014
12015 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12016
12017 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12018 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12019}
12020
[email protected]51523f52013-07-31 21:57:2812021TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2512022#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2812023 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12024 return;
12025#endif
12026
12027 SpawnedTestServer::SSLOptions ssl_options(
12028 SpawnedTestServer::SSLOptions::CERT_AUTO);
12029 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12030 ssl_options.cert_serial = 10;
Ryan Sleevib369d712018-08-20 16:43:2212031
12032 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12033 cert_verifier_config.crl_set =
12034 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {});
12035 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2812036
12037 CertStatus cert_status = 0;
12038 DoConnection(ssl_options, &cert_status);
12039
12040 // If the certificate is recorded as revoked in the CRLSet, that should be
12041 // reflected without online revocation checking.
12042 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12043 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612044 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2812045}
Adam Langleyea6d6782017-12-05 23:57:3312046
12047TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
12048#if defined(OS_ANDROID)
12049 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12050 return;
12051#endif
12052
12053 SpawnedTestServer::SSLOptions ssl_options(
12054 SpawnedTestServer::SSLOptions::CERT_AUTO);
12055 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12056 static const char kCommonName[] = "Test CN";
12057 ssl_options.cert_common_name = kCommonName;
12058
12059 {
Ryan Sleevib369d712018-08-20 16:43:2212060 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12061 cert_verifier_config.crl_set =
12062 CRLSet::ForTesting(false, nullptr, "", kCommonName, {});
12063 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3312064
12065 CertStatus cert_status = 0;
12066 DoConnection(ssl_options, &cert_status);
12067
12068 // If the certificate is recorded as revoked in the CRLSet, that should be
12069 // reflected without online revocation checking.
12070 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12071 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612072 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3312073 }
12074
12075 const uint8_t kTestServerSPKISHA256[32] = {
12076 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
12077 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
12078 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
12079 };
12080 const std::string spki_hash(
12081 reinterpret_cast<const char*>(kTestServerSPKISHA256),
12082 sizeof(kTestServerSPKISHA256));
12083
12084 {
Ryan Sleevib369d712018-08-20 16:43:2212085 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12086 cert_verifier_config.crl_set =
12087 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash});
12088 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3312089
12090 CertStatus cert_status = 0;
12091 DoConnection(ssl_options, &cert_status);
12092
12093 // When the correct SPKI hash is specified, the connection should succeed
12094 // even though the subject is listed in the CRLSet.
12095 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12096 }
12097}
[email protected]316c1e5e2012-09-12 15:17:4412098#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2712099
Sergey Ulanovc4580e72017-09-13 23:30:1112100#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
12101 !defined(OS_FUCHSIA)
12102// FTP uses a second TCP connection with the port number allocated dynamically
12103// on the server side, so it would be hard to make RemoteTestServer proxy FTP
12104// connections reliably. FTP tests are disabled on platforms that use
12105// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3112106class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1112107 public:
[email protected]d9fca99a2012-02-24 16:16:2012108 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0512109 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5512110 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4712111 // Can't use |default_context_|'s HostResolver to set up the
12112 // FTPTransactionFactory because it hasn't been created yet.
Ryan Sleevib8449e02018-07-15 04:31:0712113 default_context().set_host_resolver(&host_resolver_);
mmenke9f2ec60c2015-06-01 20:59:4712114 }
12115
12116 // URLRequestTest interface:
12117 void SetUpFactory() override {
12118 // Add FTP support to the default URLRequestContext.
12119 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0512120 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4712121 }
12122
12123 std::string GetTestFileContents() {
12124 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1912125 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4712126 path = path.Append(kTestFilePath);
12127 path = path.AppendASCII(kFtpTestFile);
12128 std::string contents;
12129 EXPECT_TRUE(base::ReadFileToString(path, &contents));
12130 return contents;
[email protected]95409e12010-08-17 20:07:1112131 }
12132
[email protected]b89ca032009-08-31 21:41:3112133 protected:
mmenke9f2ec60c2015-06-01 20:59:4712134 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4712135
tommycli59a63432015-11-06 00:10:5512136 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3112137};
12138
[email protected]d2a133182012-08-05 16:44:0812139// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0912140TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0812141 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0812142
12143 TestDelegate d;
12144 {
Ryan Sleevib8449e02018-07-15 04:31:0712145 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612146 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912147 r->Start();
12148 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0812149
Wez2a31b222018-06-07 22:07:1512150 d.RunUntilComplete();
[email protected]d2a133182012-08-05 16:44:0812151
[email protected]f7022f32014-08-21 16:32:1912152 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5012153 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0812154 }
12155}
12156
mmenke9f2ec60c2015-06-01 20:59:4712157TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5512158 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112159
[email protected]a25e90e2009-09-09 17:05:3712160 TestDelegate d;
12161 {
Ryan Sleevib8449e02018-07-15 04:31:0712162 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612163 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
12164 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912165 r->Start();
12166 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712167
Wez2a31b222018-06-07 22:07:1512168 d.RunUntilComplete();
[email protected]a25e90e2009-09-09 17:05:3712169
[email protected]f7022f32014-08-21 16:32:1912170 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712171 EXPECT_EQ(1, d.response_started_count());
12172 EXPECT_FALSE(d.received_data_before_response());
12173 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5512174 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712175 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512176 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712177 r->GetResponseRemoteEndpoint().port());
[email protected]a25e90e2009-09-09 17:05:3712178 }
12179}
12180
mmenke9f2ec60c2015-06-01 20:59:4712181TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5512182 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112183
[email protected]dd265012009-01-08 20:45:2712184 TestDelegate d;
12185 {
Ryan Sleevib8449e02018-07-15 04:31:0712186 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612187 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
12188 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912189 r->Start();
12190 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712191
Wez2a31b222018-06-07 22:07:1512192 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712193
[email protected]f7022f32014-08-21 16:32:1912194 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712195 EXPECT_EQ(1, d.response_started_count());
12196 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712197 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512198 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712199 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512200 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712201 r->GetResponseRemoteEndpoint().port());
[email protected]dd265012009-01-08 20:45:2712202 }
12203}
12204
Mike West80462a12018-11-27 16:05:0612205TEST_F(URLRequestTestFTP, FTPMimeType) {
12206 ASSERT_TRUE(ftp_test_server_.Start());
12207
12208 struct {
12209 const char* path;
12210 const char* mime;
12211 } test_cases[] = {
12212 {"/", "text/vnd.chromium.ftp-dir"},
12213 {kFtpTestFile, "application/octet-stream"},
12214 };
12215
12216 for (const auto test : test_cases) {
12217 TestDelegate d;
12218
12219 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
12220 ftp_test_server_.GetURL(test.path), DEFAULT_PRIORITY, &d,
12221 TRAFFIC_ANNOTATION_FOR_TESTS));
12222 r->Start();
12223 EXPECT_TRUE(r->is_pending());
12224
12225 d.RunUntilComplete();
12226
12227 std::string mime;
12228 r->GetMimeType(&mime);
12229 EXPECT_EQ(test.mime, mime);
12230 }
12231}
12232
mmenke9f2ec60c2015-06-01 20:59:4712233TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5512234 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112235
[email protected]dd265012009-01-08 20:45:2712236 TestDelegate d;
12237 {
Ryan Sleevib8449e02018-07-15 04:31:0712238 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512239 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12240 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612241 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912242 r->Start();
12243 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712244
Wez2a31b222018-06-07 22:07:1512245 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712246
[email protected]f7022f32014-08-21 16:32:1912247 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4712248 EXPECT_EQ(1, d.response_started_count());
12249 EXPECT_FALSE(d.received_data_before_response());
12250 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512251 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712252 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512253 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712254 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:2512255
12256 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1912257 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2512258 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2712259 }
12260}
12261
mmenke9f2ec60c2015-06-01 20:59:4712262TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5512263 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112264
[email protected]dd265012009-01-08 20:45:2712265 TestDelegate d;
12266 {
Ryan Sleevib8449e02018-07-15 04:31:0712267 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512268 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12269 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612270 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912271 r->Start();
12272 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712273
Wez2a31b222018-06-07 22:07:1512274 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712275
[email protected]f7022f32014-08-21 16:32:1912276 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712277 EXPECT_EQ(1, d.response_started_count());
12278 EXPECT_FALSE(d.received_data_before_response());
12279 EXPECT_EQ(d.bytes_received(), 0);
12280 }
12281}
12282
mmenke9f2ec60c2015-06-01 20:59:4712283TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5512284 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112285
[email protected]8b8a197d2009-08-26 15:57:5812286 TestDelegate d;
12287 // Set correct login credentials. The delegate will be asked for them when
12288 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812289 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812290 {
Ryan Sleevib8449e02018-07-15 04:31:0712291 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512292 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12293 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612294 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912295 r->Start();
12296 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812297
Wez2a31b222018-06-07 22:07:1512298 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812299
[email protected]f7022f32014-08-21 16:32:1912300 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812301 EXPECT_EQ(1, d.response_started_count());
12302 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712303 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812304 }
12305}
12306
mmenke9f2ec60c2015-06-01 20:59:4712307TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5512308 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112309
[email protected]dd265012009-01-08 20:45:2712310 TestDelegate d;
12311 {
Ryan Sleevib8449e02018-07-15 04:31:0712312 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512313 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12314 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612315 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912316 r->Start();
12317 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712318
Wez2a31b222018-06-07 22:07:1512319 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712320
[email protected]f7022f32014-08-21 16:32:1912321 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712322 EXPECT_EQ(1, d.response_started_count());
12323 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712324 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2712325 }
12326}
[email protected]8b8a197d2009-08-26 15:57:5812327
mmenke9f2ec60c2015-06-01 20:59:4712328TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5512329 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112330
[email protected]8b8a197d2009-08-26 15:57:5812331 TestDelegate d;
12332 // Set correct login credentials. The delegate will be asked for them when
12333 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812334 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812335 {
Ryan Sleevib8449e02018-07-15 04:31:0712336 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512337 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12338 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612339 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912340 r->Start();
12341 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812342
Wez2a31b222018-06-07 22:07:1512343 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812344
[email protected]f7022f32014-08-21 16:32:1912345 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812346 EXPECT_EQ(1, d.response_started_count());
12347 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712348 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812349 }
12350}
[email protected]60a3df52009-09-22 16:13:2412351
mmenke9f2ec60c2015-06-01 20:59:4712352TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5512353 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112354
danakj8522a25b2016-04-16 00:17:3612355 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412356 {
12357 // Pass correct login identity in the URL.
Ryan Sleevib8449e02018-07-15 04:31:0712358 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512359 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12360 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612361 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912362 r->Start();
12363 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412364
Wez2a31b222018-06-07 22:07:1512365 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412366
[email protected]f7022f32014-08-21 16:32:1912367 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412368 EXPECT_EQ(1, d->response_started_count());
12369 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712370 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412371 }
12372
12373 d.reset(new TestDelegate);
12374 {
12375 // This request should use cached identity from previous request.
Ryan Sleevib8449e02018-07-15 04:31:0712376 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612377 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12378 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912379 r->Start();
12380 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412381
Wez2a31b222018-06-07 22:07:1512382 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412383
[email protected]f7022f32014-08-21 16:32:1912384 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412385 EXPECT_EQ(1, d->response_started_count());
12386 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712387 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412388 }
12389}
12390
mmenke9f2ec60c2015-06-01 20:59:4712391TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5512392 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112393
danakj8522a25b2016-04-16 00:17:3612394 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412395 // Set correct login credentials. The delegate will be asked for them when
12396 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812397 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2412398 {
Ryan Sleevib8449e02018-07-15 04:31:0712399 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512400 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12401 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612402 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912403 r->Start();
12404 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412405
Wez2a31b222018-06-07 22:07:1512406 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412407
[email protected]f7022f32014-08-21 16:32:1912408 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412409 EXPECT_EQ(1, d->response_started_count());
12410 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712411 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412412 }
12413
12414 // Use a new delegate without explicit credentials. The cached ones should be
12415 // used.
12416 d.reset(new TestDelegate);
12417 {
12418 // Don't pass wrong credentials in the URL, they would override valid cached
12419 // ones.
Ryan Sleevib8449e02018-07-15 04:31:0712420 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612421 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12422 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912423 r->Start();
12424 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412425
Wez2a31b222018-06-07 22:07:1512426 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412427
[email protected]f7022f32014-08-21 16:32:1912428 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412429 EXPECT_EQ(1, d->response_started_count());
12430 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712431 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412432 }
12433}
ricea3a1c71f2016-06-17 10:05:2612434
12435TEST_F(URLRequestTestFTP, RawBodyBytes) {
12436 ASSERT_TRUE(ftp_test_server_.Start());
12437
12438 TestDelegate d;
12439 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612440 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12441 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2612442 req->Start();
Wez2a31b222018-06-07 22:07:1512443 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:2612444
12445 EXPECT_EQ(6, req->GetRawBodyBytes());
12446}
12447
Matt Menkef1b97e02019-05-13 23:52:4112448class URLRequestTestFTPOverHttpProxy : public URLRequestTestFTP {
12449 public:
12450 // Test interface:
12451 void SetUp() override {
12452 proxy_resolution_service_ = ProxyResolutionService::CreateFixed(
12453 "localhost", TRAFFIC_ANNOTATION_FOR_TESTS);
12454 default_context_->set_proxy_resolution_service(
12455 proxy_resolution_service_.get());
12456 URLRequestTestFTP::SetUp();
12457 }
12458
12459 private:
12460 std::unique_ptr<ProxyResolutionService> proxy_resolution_service_;
12461};
12462
12463// Check that FTP is not supported over an HTTP proxy.
12464TEST_F(URLRequestTestFTPOverHttpProxy, Fails) {
12465 TestDelegate delegate;
12466 std::unique_ptr<URLRequest> request(
12467 default_context_->CreateRequest(GURL("ftp://foo.test/"), DEFAULT_PRIORITY,
12468 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12469 request->Start();
12470 delegate.RunUntilComplete();
12471
12472 EXPECT_THAT(delegate.request_status(), IsError(ERR_NO_SUPPORTED_PROXIES));
12473}
12474
brettwa1228ebb2016-10-28 03:51:3412475#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5112476
ttuttlec0c828492015-05-15 01:25:5512477TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
12478 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712479 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612480 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512481
12482 EXPECT_FALSE(req->response_info().network_accessed);
12483
12484 req->Start();
Wez2a31b222018-06-07 22:07:1512485 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512486
12487 EXPECT_EQ(1, default_network_delegate_.completed_requests());
12488 EXPECT_FALSE(req->response_info().network_accessed);
12489}
12490
12491TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
12492 MockHostResolver host_resolver;
12493 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
12494 TestURLRequestContext context(true);
12495 context.set_network_delegate(&network_delegate);
12496 context.set_host_resolver(&host_resolver);
12497 host_resolver.rules()->AddSimulatedFailure("*");
12498 context.Init();
12499
12500 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612501 std::unique_ptr<URLRequest> req(
12502 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
12503 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512504
12505 EXPECT_FALSE(req->response_info().network_accessed);
12506
12507 req->Start();
Wez2a31b222018-06-07 22:07:1512508 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512509 EXPECT_TRUE(req->response_info().network_accessed);
12510}
12511
mmenkeed0498b2015-12-08 23:20:4212512// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2212513// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4212514TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2212515 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712516 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612517 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
12518 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2212519
danakj8522a25b2016-04-16 00:17:3612520 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2212521 req.get(), &default_network_delegate_,
12522 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4212523 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
12524 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2212525
12526 req->Start();
12527 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2212528 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5012529 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2212530 EXPECT_EQ(0, d.received_redirect_count());
12531}
12532
Andrey Kosyakov2e893e62017-08-31 17:00:5212533TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412534 ASSERT_TRUE(http_test_server()->Start());
12535 TestURLRequestContext context;
12536 GURL url(http_test_server()->GetURL("/cachetime"));
12537 TestDelegate delegate;
12538 HttpRequestHeaders extra_headers;
12539 extra_headers.SetHeader("X-Foo", "bar");
12540
12541 {
Andrey Kosyakov2e893e62017-08-31 17:00:5212542 HttpRawRequestHeaders raw_req_headers;
12543 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12544
Andrey Kosyakov83a6eee2017-08-14 19:20:0412545 std::unique_ptr<URLRequest> r(context.CreateRequest(
12546 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12547 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212548 r->SetRequestHeadersCallback(base::Bind(
12549 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
12550 r->SetResponseHeadersCallback(base::Bind(
12551 [](scoped_refptr<const HttpResponseHeaders>* left,
12552 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12553 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412554 r->Start();
12555 while (!delegate.response_started_count())
12556 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5212557 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412558 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212559 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412560 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212561 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412562 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212563 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
12564 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
12565 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
12566 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412567 }
12568 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412569 std::unique_ptr<URLRequest> r(context.CreateRequest(
12570 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12571 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212572 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412573 FAIL() << "Callback should not be called unless request is sent";
12574 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212575 r->SetResponseHeadersCallback(
12576 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
12577 FAIL() << "Callback should not be called unless request is sent";
12578 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412579 r->Start();
Wez2a31b222018-06-07 22:07:1512580 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412581 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412582 }
12583}
12584
Andrey Kosyakov2e893e62017-08-31 17:00:5212585TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412586 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5212587 HttpRawRequestHeaders raw_req_headers;
12588 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12589
Andrey Kosyakov83a6eee2017-08-14 19:20:0412590 TestURLRequestContext context;
12591 TestDelegate delegate;
12592 HttpRequestHeaders extra_headers;
12593 extra_headers.SetHeader("X-Foo", "bar");
Andrey Kosyakov83a6eee2017-08-14 19:20:0412594 GURL url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:0712595 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412596 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12597 r->SetExtraRequestHeaders(extra_headers);
12598 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5212599 base::Unretained(&raw_req_headers)));
12600 r->SetResponseHeadersCallback(base::Bind(
12601 [](scoped_refptr<const HttpResponseHeaders>* left,
12602 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12603 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412604 r->Start();
Wez0e717112018-06-18 23:09:2212605 delegate.RunUntilRedirect();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412606
12607 ASSERT_EQ(1, delegate.received_redirect_count());
12608 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212609 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412610 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212611 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412612 EXPECT_EQ("gzip, deflate", value);
12613 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5212614 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
12615 raw_req_headers.request_line());
12616 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
12617 EXPECT_EQ(302, raw_resp_headers->response_code());
12618 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412619
Andrey Kosyakov2e893e62017-08-31 17:00:5212620 raw_req_headers = HttpRawRequestHeaders();
12621 raw_resp_headers = nullptr;
Arthur Sonzognib8465ff72019-01-04 18:44:3512622 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
12623 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:1512624 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212625 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412626 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212627 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412628 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212629 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
12630 raw_req_headers.request_line());
12631 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412632}
12633
Andrey Kosyakov2e893e62017-08-31 17:00:5212634TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412635 TestDelegate request_delegate;
12636
Ryan Sleevib8449e02018-07-15 04:31:0712637 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412638 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
12639 TRAFFIC_ANNOTATION_FOR_TESTS));
12640 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
12641 FAIL() << "Callback should not be called unless request is sent";
12642 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212643 r->SetResponseHeadersCallback(
12644 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12645 FAIL() << "Callback should not be called unless request is sent";
12646 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412647 r->Start();
Wez2a31b222018-06-07 22:07:1512648 request_delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412649 EXPECT_FALSE(r->is_pending());
12650}
12651
Andrey Kosyakov2e893e62017-08-31 17:00:5212652TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412653 ASSERT_TRUE(http_test_server()->Start());
12654 GURL url(http_test_server()->GetURL("/auth-basic"));
12655
12656 TestURLRequestContext context;
12657 TestDelegate delegate;
12658
12659 delegate.set_credentials(AuthCredentials(kUser, kSecret));
12660 HttpRequestHeaders extra_headers;
12661 extra_headers.SetHeader("X-Foo", "bar");
12662
Andrey Kosyakov2e893e62017-08-31 17:00:5212663 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
12664 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0412665
Andrey Kosyakov2e893e62017-08-31 17:00:5212666 using RespHeadersVector =
12667 std::vector<scoped_refptr<const HttpResponseHeaders>>;
12668 RespHeadersVector raw_resp_headers;
12669
12670 auto req_headers_callback = base::Bind(
12671 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
12672 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
12673 },
12674 &raw_req_headers);
12675 auto resp_headers_callback = base::Bind(
12676 [](RespHeadersVector* vec,
12677 scoped_refptr<const HttpResponseHeaders> headers) {
12678 vec->push_back(headers);
12679 },
12680 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412681 std::unique_ptr<URLRequest> r(context.CreateRequest(
12682 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12683 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212684 r->SetRequestHeadersCallback(req_headers_callback);
12685 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412686 r->Start();
Wez2a31b222018-06-07 22:07:1512687 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412688 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5212689 ASSERT_EQ(raw_req_headers.size(), 2u);
12690 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412691 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212692 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
12693 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412694 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212695 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
12696 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412697 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212698 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
12699 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
12700 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
12701 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
12702
12703 std::unique_ptr<URLRequest> r2(context.CreateRequest(
12704 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12705 r2->SetExtraRequestHeaders(extra_headers);
12706 r2->SetRequestHeadersCallback(req_headers_callback);
12707 r2->SetResponseHeadersCallback(resp_headers_callback);
12708 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
12709 r2->Start();
Wez2a31b222018-06-07 22:07:1512710 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212711 EXPECT_FALSE(r2->is_pending());
12712 ASSERT_EQ(raw_req_headers.size(), 3u);
12713 ASSERT_EQ(raw_resp_headers.size(), 3u);
12714 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
12715 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
12716 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
12717 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412718}
12719
Andrey Kosyakov2e893e62017-08-31 17:00:5212720TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412721 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
12722 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712723 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412724 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12725 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5212726 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0412727 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212728 r->SetResponseHeadersCallback(
12729 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12730 FAIL() << "Callback should not be called for non-HTTP schemes";
12731 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412732 r->Start();
Wez2a31b222018-06-07 22:07:1512733 d.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412734 EXPECT_FALSE(r->is_pending());
12735}
12736
Carlos ILaef65d62018-06-04 21:24:1312737TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
12738 TestDelegate d;
12739 BlockingNetworkDelegate network_delegate(
12740 BlockingNetworkDelegate::SYNCHRONOUS);
12741 const GURL kOriginalUrl("https://original.test");
12742 const GURL kRedirectUrl("http://redirect.test");
12743 network_delegate.set_redirect_url(kRedirectUrl);
12744 TestURLRequestContext context(true /* delay_initialization */);
12745 context.set_network_delegate(&network_delegate);
12746 context.Init();
12747
12748 std::unique_ptr<URLRequest> r(context.CreateRequest(
12749 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12750 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312751 r->Start();
Wez0e717112018-06-18 23:09:2212752 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312753 GURL::Replacements replacements;
12754 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12755 // was set.
12756 replacements.SetSchemeStr("https");
12757 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12758 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412759 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312760}
12761
12762TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
12763 TestDelegate d;
12764 BlockingNetworkDelegate network_delegate(
12765 BlockingNetworkDelegate::SYNCHRONOUS);
12766 const GURL kOriginalUrl("https://original.test");
12767 const GURL kRedirectUrl("http://redirect.test:80");
12768 network_delegate.set_redirect_url(kRedirectUrl);
12769 TestURLRequestContext context(true /* delay_initialization */);
12770 context.set_network_delegate(&network_delegate);
12771 context.Init();
12772
12773 std::unique_ptr<URLRequest> r(context.CreateRequest(
12774 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12775 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312776 r->Start();
Wez0e717112018-06-18 23:09:2212777 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312778 GURL::Replacements replacements;
12779 // The URL host should have not been changed.
12780 EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
12781 // The scheme should now be https, and the effective port should now be 443.
12782 EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
12783 EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
Carlos IL0d67fc72018-06-22 17:18:4412784 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312785}
12786
12787TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
12788 TestDelegate d;
12789 BlockingNetworkDelegate network_delegate(
12790 BlockingNetworkDelegate::SYNCHRONOUS);
12791 const GURL kOriginalUrl("https://original.test");
12792 const GURL kRedirectUrl("http://redirect.test:1234");
12793 network_delegate.set_redirect_url(kRedirectUrl);
12794 TestURLRequestContext context(true /* delay_initialization */);
12795 context.set_network_delegate(&network_delegate);
12796 context.Init();
12797
12798 std::unique_ptr<URLRequest> r(context.CreateRequest(
12799 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12800 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312801 r->Start();
Wez0e717112018-06-18 23:09:2212802 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312803 GURL::Replacements replacements;
12804 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12805 // was set, nonstandard port should not have been modified.
12806 replacements.SetSchemeStr("https");
12807 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12808 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412809 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312810}
12811
12812TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
12813 TestDelegate d;
12814 BlockingNetworkDelegate network_delegate(
12815 BlockingNetworkDelegate::SYNCHRONOUS);
12816 const GURL kOriginalUrl("https://original.test");
12817 const GURL kRedirectUrl("http://redirect.test");
12818 network_delegate.set_redirect_url(kRedirectUrl);
12819 TestURLRequestContext context(true /* delay_initialization */);
12820 context.set_network_delegate(&network_delegate);
12821 context.Init();
12822 std::unique_ptr<URLRequest> r(context.CreateRequest(
12823 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12824 r->set_upgrade_if_insecure(false);
Carlos ILaef65d62018-06-04 21:24:1312825 r->Start();
Wez0e717112018-06-18 23:09:2212826 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312827 // The redirect URL should not be changed if the upgrade_if_insecure flag is
12828 // not set.
12829 EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412830 EXPECT_FALSE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312831}
12832
Paul Jensen60e45532018-02-19 16:04:1812833// Test that URLRequests get properly tagged.
12834#if defined(OS_ANDROID)
12835TEST_F(URLRequestTestHTTP, TestTagging) {
Peter Collingbourne8ccab722019-02-12 18:10:4812836 if (!CanGetTaggedBytes()) {
12837 DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
12838 return;
12839 }
12840
Paul Jensen60e45532018-02-19 16:04:1812841 ASSERT_TRUE(http_test_server()->Start());
12842
12843 // The tag under which the system reports untagged traffic.
12844 static const int32_t UNTAGGED_TAG = 0;
12845
12846 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
12847
12848 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
12849 TestDelegate delegate;
Ryan Sleevib8449e02018-07-15 04:31:0712850 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Paul Jensen60e45532018-02-19 16:04:1812851 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
12852 TRAFFIC_ANNOTATION_FOR_TESTS));
12853 EXPECT_EQ(SocketTag(), req->socket_tag());
12854 req->Start();
Wez2a31b222018-06-07 22:07:1512855 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812856
12857 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
12858
12859 int32_t tag_val1 = 0x12345678;
12860 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
12861 old_traffic = GetTaggedBytes(tag_val1);
12862
12863 // Test specific tag value.
Ryan Sleevib8449e02018-07-15 04:31:0712864 req = default_context().CreateRequest(http_test_server()->GetURL("/"),
12865 DEFAULT_PRIORITY, &delegate,
12866 TRAFFIC_ANNOTATION_FOR_TESTS);
Paul Jensen60e45532018-02-19 16:04:1812867 req->set_socket_tag(tag1);
12868 EXPECT_EQ(tag1, req->socket_tag());
12869 req->Start();
Wez2a31b222018-06-07 22:07:1512870 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812871
12872 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
12873}
12874#endif
12875
Steven Valdez1c1859172019-04-10 15:33:2812876// Provides a response to the 0RTT request indicating whether it was received
12877// as early data, sending HTTP_TOO_EARLY if enabled.
12878class ZeroRTTResponse : public test_server::BasicHttpResponse {
12879 public:
12880 ZeroRTTResponse(bool zero_rtt, bool send_too_early)
12881 : zero_rtt_(zero_rtt), send_too_early_(send_too_early) {}
12882 ~ZeroRTTResponse() override {}
12883
12884 void SendResponse(const test_server::SendBytesCallback& send,
12885 const test_server::SendCompleteCallback& done) override {
12886 AddCustomHeader("Vary", "Early-Data");
12887 set_content_type("text/plain");
12888 AddCustomHeader("Cache-Control", "no-cache");
12889 if (zero_rtt_) {
12890 if (send_too_early_)
12891 set_code(HTTP_TOO_EARLY);
12892 set_content("1");
12893 } else {
12894 set_content("0");
12895 }
12896
12897 // Since the EmbeddedTestServer doesn't keep the socket open by default,
12898 // it is explicitly kept alive to allow the remaining leg of the 0RTT
12899 // handshake to be received after the early data.
12900 send.Run(ToResponseString(), base::DoNothing());
12901 }
12902
12903 private:
12904 bool zero_rtt_;
12905 bool send_too_early_;
12906
12907 DISALLOW_COPY_AND_ASSIGN(ZeroRTTResponse);
12908};
12909
12910std::unique_ptr<test_server::HttpResponse> HandleZeroRTTRequest(
12911 const test_server::HttpRequest& request) {
12912 if (request.GetURL().path() != "/zerortt")
12913 return nullptr;
12914 auto iter = request.headers.find("Early-Data");
12915 bool zero_rtt = iter != request.headers.end() && iter->second == "1";
12916 return std::make_unique<ZeroRTTResponse>(zero_rtt, false);
12917}
12918
12919class HTTPSEarlyDataTest : public TestWithScopedTaskEnvironment {
12920 public:
12921 HTTPSEarlyDataTest()
12922 : context_(true), test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
12923 auto params = std::make_unique<HttpNetworkSession::Params>();
12924 params->enable_early_data = true;
12925 context_.set_http_network_session_params(std::move(params));
12926
12927 context_.set_network_delegate(&network_delegate_);
12928 cert_verifier_.set_default_result(OK);
12929 context_.set_cert_verifier(&cert_verifier_);
12930
12931 ssl_config_service_ = std::make_unique<TestSSLConfigService>();
12932 ssl_config_service_->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
12933 context_.set_ssl_config_service(ssl_config_service_.get());
12934
12935 context_.Init();
12936
12937 ssl_config_.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
12938 ssl_config_.early_data_enabled = true;
12939 test_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config_);
12940 test_server_.AddDefaultHandlers(
12941 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
12942 test_server_.RegisterRequestHandler(
12943 base::BindRepeating(&HandleZeroRTTRequest));
12944 }
12945
12946 ~HTTPSEarlyDataTest() override = default;
12947
12948 void ResetSSLConfig(net::EmbeddedTestServer::ServerCertificate cert,
12949 uint16_t version) {
12950 ssl_config_.version_max = version;
12951 test_server_.ResetSSLConfig(cert, ssl_config_);
12952 }
12953
12954 protected:
12955 MockCertVerifier cert_verifier_;
12956 TestNetworkDelegate network_delegate_; // Must outlive URLRequest.
12957 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
12958 TestURLRequestContext context_;
12959
12960 SSLServerConfig ssl_config_;
12961 EmbeddedTestServer test_server_;
12962};
12963
12964// TLSEarlyDataTest tests that we handle early data correctly.
12965TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTest) {
12966 ASSERT_TRUE(test_server_.Start());
12967 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
12968
12969 {
12970 TestDelegate d;
12971 std::unique_ptr<URLRequest> r(context_.CreateRequest(
12972 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
12973 TRAFFIC_ANNOTATION_FOR_TESTS));
12974 r->Start();
12975 EXPECT_TRUE(r->is_pending());
12976
12977 base::RunLoop().Run();
12978
12979 EXPECT_EQ(1, d.response_started_count());
12980
12981 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
12982 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
12983 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
12984 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
12985 r->ssl_info().cert.get()));
12986
12987 // The Early-Data header should be omitted in the initial request, and the
12988 // handler should return "0".
12989 EXPECT_EQ("0", d.data_received());
12990 }
12991
12992 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
12993
12994 {
12995 TestDelegate d;
12996 std::unique_ptr<URLRequest> r(context_.CreateRequest(
12997 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
12998 TRAFFIC_ANNOTATION_FOR_TESTS));
12999
13000 r->Start();
13001 EXPECT_TRUE(r->is_pending());
13002
13003 base::RunLoop().Run();
13004
13005 EXPECT_EQ(1, d.response_started_count());
13006
13007 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13008 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13009 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13010 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13011 r->ssl_info().cert.get()));
13012
13013 // The Early-Data header should be a single '1' in the resumed request, and
13014 // the handler should return "1".
13015 EXPECT_EQ("1", d.data_received());
13016 }
13017}
13018
13019// TLSEarlyDataTest tests that we handle early data correctly for POST.
13020TEST_F(HTTPSEarlyDataTest, TLSEarlyDataPOSTTest) {
13021 ASSERT_TRUE(test_server_.Start());
13022 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13023
13024 {
13025 TestDelegate d;
13026 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13027 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13028 TRAFFIC_ANNOTATION_FOR_TESTS));
13029 r->Start();
13030 EXPECT_TRUE(r->is_pending());
13031
13032 base::RunLoop().Run();
13033
13034 EXPECT_EQ(1, d.response_started_count());
13035
13036 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13037 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13038 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13039 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13040 r->ssl_info().cert.get()));
13041
13042 // The Early-Data header should be omitted in the initial request, and the
13043 // handler should return "0".
13044 EXPECT_EQ("0", d.data_received());
13045 }
13046
13047 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13048
13049 {
13050 TestDelegate d;
13051 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13052 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13053 TRAFFIC_ANNOTATION_FOR_TESTS));
13054 r->set_method("POST");
13055 r->Start();
13056 EXPECT_TRUE(r->is_pending());
13057
13058 base::RunLoop().Run();
13059
13060 EXPECT_EQ(1, d.response_started_count());
13061
13062 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13063 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13064 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13065 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13066 r->ssl_info().cert.get()));
13067
13068 // The Early-Data header should be omitted in the request, since we don't
13069 // send POSTs over early data, and the handler should return "0".
13070 EXPECT_EQ("0", d.data_received());
13071 }
13072}
13073
13074std::unique_ptr<test_server::HttpResponse> HandleTooEarly(
13075 bool* sent_425,
13076 const test_server::HttpRequest& request) {
13077 if (request.GetURL().path() != "/tooearly")
13078 return nullptr;
13079 auto iter = request.headers.find("Early-Data");
13080 bool zero_rtt = iter != request.headers.end() && iter->second == "1";
13081 if (zero_rtt)
13082 *sent_425 = true;
13083 return std::make_unique<ZeroRTTResponse>(zero_rtt, true);
13084}
13085
13086// Test that we handle 425 (Too Early) correctly.
13087TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTooEarlyTest) {
13088 bool sent_425 = false;
13089 test_server_.RegisterRequestHandler(
13090 base::BindRepeating(&HandleTooEarly, base::Unretained(&sent_425)));
13091 ASSERT_TRUE(test_server_.Start());
13092 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13093
13094 {
13095 TestDelegate d;
13096 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13097 test_server_.GetURL("/tooearly"), DEFAULT_PRIORITY, &d,
13098 TRAFFIC_ANNOTATION_FOR_TESTS));
13099 r->Start();
13100 EXPECT_TRUE(r->is_pending());
13101
13102 d.RunUntilComplete();
13103
13104 EXPECT_EQ(1, d.response_started_count());
13105
13106 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13107 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13108 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13109 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13110 r->ssl_info().cert.get()));
13111
13112 // The Early-Data header should be omitted in the initial request, and the
13113 // handler should return "0".
13114 EXPECT_EQ("0", d.data_received());
13115 EXPECT_FALSE(sent_425);
13116 }
13117
13118 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13119
13120 {
13121 TestDelegate d;
13122 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13123 test_server_.GetURL("/tooearly"), DEFAULT_PRIORITY, &d,
13124 TRAFFIC_ANNOTATION_FOR_TESTS));
13125
13126 r->Start();
13127 EXPECT_TRUE(r->is_pending());
13128
13129 d.RunUntilComplete();
13130
13131 EXPECT_EQ(1, d.response_started_count());
13132
13133 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13134 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13135 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13136 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13137 r->ssl_info().cert.get()));
13138
13139 // The resumption request will encounter a 425 error and retry without early
13140 // data, and the handler should return "0".
13141 EXPECT_EQ("0", d.data_received());
13142 EXPECT_TRUE(sent_425);
13143 }
13144}
13145
13146// TLSEarlyDataRejectTest tests that we gracefully handle an early data reject
13147// and retry without early data.
13148TEST_F(HTTPSEarlyDataTest, TLSEarlyDataRejectTest) {
13149 ASSERT_TRUE(test_server_.Start());
13150 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13151
13152 {
13153 TestDelegate d;
13154 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13155 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13156 TRAFFIC_ANNOTATION_FOR_TESTS));
13157
13158 r->Start();
13159 EXPECT_TRUE(r->is_pending());
13160
13161 d.RunUntilComplete();
13162
13163 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13164 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13165 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13166 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13167 r->ssl_info().cert.get()));
13168
13169 // The Early-Data header should be omitted in the initial request, and the
13170 // handler should return "0".
13171 EXPECT_EQ("0", d.data_received());
13172 }
13173
13174 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13175
13176 // The certificate in the resumption is changed to confirm that the
13177 // certificate change is observed.
13178 scoped_refptr<X509Certificate> old_cert = test_server_.GetCertificate();
13179 ResetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED,
13180 SSL_PROTOCOL_VERSION_TLS1_3);
13181
13182 {
13183 TestDelegate d;
13184 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13185 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13186 TRAFFIC_ANNOTATION_FOR_TESTS));
13187
13188 r->Start();
13189 EXPECT_TRUE(r->is_pending());
13190
13191 d.RunUntilComplete();
13192
13193 EXPECT_EQ(1, d.response_started_count());
13194
13195 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13196 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13197 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13198 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13199 r->ssl_info().cert.get()));
13200 EXPECT_FALSE(old_cert->EqualsIncludingChain(r->ssl_info().cert.get()));
13201
13202 // The Early-Data header should be omitted in the rejected request, and the
13203 // handler should return "0".
13204 EXPECT_EQ("0", d.data_received());
13205 }
13206}
13207
13208// TLSEarlyDataTLS12RejectTest tests that we gracefully handle an early data
13209// reject from a TLS 1.2 server and retry without early data.
13210TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTLS12RejectTest) {
13211 ASSERT_TRUE(test_server_.Start());
13212 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13213
13214 {
13215 TestDelegate d;
13216 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13217 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13218 TRAFFIC_ANNOTATION_FOR_TESTS));
13219
13220 r->Start();
13221 EXPECT_TRUE(r->is_pending());
13222
13223 d.RunUntilComplete();
13224
13225 EXPECT_EQ(1, d.response_started_count());
13226
13227 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13228 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13229 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13230 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13231 r->ssl_info().cert.get()));
13232
13233 // The Early-Data header should be omitted in the initial request, and the
13234 // handler should return "0".
13235 EXPECT_EQ("0", d.data_received());
13236 }
13237
13238 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13239
13240 // The certificate in the resumption is changed to confirm that the
13241 // certificate change is observed.
13242 scoped_refptr<X509Certificate> old_cert = test_server_.GetCertificate();
13243 ResetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED,
13244 SSL_PROTOCOL_VERSION_TLS1_2);
13245
13246 {
13247 TestDelegate d;
13248 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13249 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13250 TRAFFIC_ANNOTATION_FOR_TESTS));
13251
13252 r->Start();
13253 EXPECT_TRUE(r->is_pending());
13254
13255 d.RunUntilComplete();
13256
13257 EXPECT_EQ(1, d.response_started_count());
13258
13259 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_2,
13260 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13261 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13262 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13263 r->ssl_info().cert.get()));
13264 EXPECT_FALSE(old_cert->EqualsIncludingChain(r->ssl_info().cert.get()));
13265
13266 // The Early-Data header should be omitted in the rejected request, and the
13267 // handler should return "0".
13268 EXPECT_EQ("0", d.data_received());
13269 }
13270}
13271
[email protected]7461a402011-03-24 23:19:5113272} // namespace net