blob: 4646cf103240eff6d359a957a61e8e9b69a4d546 [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"
[email protected]255620da2013-08-19 13:14:2937#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4538#include "base/single_thread_task_runner.h"
Avi Drissman4365a4782018-12-28 19:26:2439#include "base/stl_util.h"
[email protected]4dc3ad4f2013-06-11 07:15:5040#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5541#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2242#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2243#include "base/strings/string_util.h"
44#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0545#include "base/strings/utf_string_conversions.h"
Devlin Cronine4bcb40e2018-06-05 18:02:4746#include "base/test/metrics/histogram_tester.h"
Emily Stark4cfecf072017-08-08 01:05:5147#include "base/test/scoped_feature_list.h"
gabf767595f2016-05-11 18:50:3548#include "base/threading/thread_task_runner_handle.h"
estark06e0dac2015-08-07 21:56:0149#include "base/values.h"
mmenkefd9d15c2017-06-29 13:45:5450#include "build/buildflag.h"
mmenkecbc2b712014-10-09 20:29:0751#include "net/base/chunked_upload_data_stream.h"
tfarina43a416b2016-01-06 21:48:0752#include "net/base/directory_listing.h"
mmenkecbc2b712014-10-09 20:29:0753#include "net/base/elements_upload_data_stream.h"
David Benjamina7fde612019-03-15 14:20:5854#include "net/base/escape.h"
Mike Westfbd44112019-05-08 18:23:3755#include "net/base/features.h"
Aaron Tagliaboschi028009e2019-03-07 16:28:0656#include "net/base/layered_network_delegate.h"
initial.commit586acc5fe2008-07-26 22:42:5257#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2558#include "net/base/load_timing_info.h"
59#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0660#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5261#include "net/base/net_module.h"
Lily Houghton582d4622018-01-22 22:43:4062#include "net/base/proxy_server.h"
[email protected]2ca01e52013-10-31 22:05:1963#include "net/base/request_priority.h"
zhongyi18ddddd2017-02-03 19:06:3664#include "net/base/test_completion_callback.h"
[email protected]f288ef02012-12-15 20:28:2865#include "net/base/upload_bytes_element_reader.h"
66#include "net/base/upload_data_stream.h"
67#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4468#include "net/base/url_util.h"
Matt Muellera4aaa9d2019-04-24 21:09:1469#include "net/cert/cert_net_fetcher.h"
Ryan Sleevib369d712018-08-20 16:43:2270#include "net/cert/crl_set.h"
rsleevid6de8302016-06-21 01:33:2071#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4772#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3673#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1174#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2475#include "net/cert/mock_cert_verifier.h"
zhongyi18ddddd2017-02-03 19:06:3676#include "net/cert/multi_log_ct_verifier.h"
eranmdcec9632016-10-10 14:16:1077#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1178#include "net/cert/test_root_certs.h"
Matt Muellera4aaa9d2019-04-24 21:09:1479#include "net/cert_net/cert_net_fetcher_impl.h"
Aaron Tagliaboschifd4f3f012019-05-30 23:05:5480#include "net/cookies/canonical_cookie_test_helpers.h"
[email protected]aa84a7e2012-03-15 21:29:0681#include "net/cookies/cookie_monster.h"
82#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5283#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5384#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3885#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5286#include "net/http/http_cache.h"
87#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1988#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2589#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2190#include "net/http/http_response_headers.h"
zhongyi18ddddd2017-02-03 19:06:3691#include "net/http/http_server_properties_impl.h"
[email protected]e50efea2014-03-24 18:41:0092#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0093#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1994#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5195#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4696#include "net/log/test_net_log_entry.h"
97#include "net/log/test_net_log_util.h"
Scott Violet0caaaf432018-03-24 00:43:5998#include "net/net_buildflags.h"
Lily Houghtonffe89daa02018-03-09 18:30:0399#include "net/proxy_resolution/proxy_resolution_service.h"
Ryan Hamiltona3ee93a72018-08-01 22:03:08100#include "net/quic/mock_crypto_client_stream_factory.h"
101#include "net/quic/quic_server_info.h"
zhongyi18ddddd2017-02-03 19:06:36102#include "net/socket/socket_test_util.h"
[email protected]c3456bb2011-12-12 22:22:19103#include "net/socket/ssl_client_socket.h"
David Benjamin76a40ad2018-02-24 22:22:08104#include "net/ssl/client_cert_identity_test_util.h"
[email protected]536fd0b2013-03-14 17:41:57105#include "net/ssl/ssl_connection_status_flags.h"
David Benjamin76a40ad2018-02-24 22:22:08106#include "net/ssl/ssl_private_key.h"
tommycli59a63432015-11-06 00:10:55107#include "net/ssl/ssl_server_config.h"
[email protected]6e7845ae2013-03-29 21:48:11108#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:36109#include "net/test/embedded_test_server/embedded_test_server.h"
110#include "net/test/embedded_test_server/http_request.h"
111#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:01112#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21113#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43114#include "net/test/test_data_directory.h"
Bence Béky98447b12018-05-08 03:14:01115#include "net/test/test_with_scoped_task_environment.h"
mmenkefb18c772015-09-30 22:22:50116#include "net/test/url_request/url_request_failed_job.h"
Carlos ILaef65d62018-06-04 21:24:13117#include "net/test/url_request/url_request_mock_http_job.h"
rhalavatib7bd7c792017-04-27 05:25:16118#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34119#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43120#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52121#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50122#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14123#include "net/url_request/url_request_http_job.h"
Thiemo Nagel0793b9c532018-04-18 16:57:58124#include "net/url_request/url_request_http_job_histogram.h"
bengr1bf8e942014-11-07 01:36:50125#include "net/url_request/url_request_intercepting_job_factory.h"
126#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49127#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51128#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47129#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44130#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01131#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52132#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15133#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52134
Eric Romanefddd0a2017-10-10 02:14:25135#if defined(OS_FUCHSIA)
136#define USE_BUILTIN_CERT_VERIFIER
137#endif
138
brettwa1228ebb2016-10-28 03:51:34139#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55140#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29141#include "net/url_request/file_protocol_handler.h"
142#include "net/url_request/url_request_file_dir_job.h"
143#endif
144
brettwa1228ebb2016-10-28 03:51:34145#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
Emily Stark01227982019-06-06 18:45:56146#include "net/ftp/ftp_auth_cache.h"
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
mmenkeed0498b2015-12-08 23:20:42336// Job that allows monitoring of its priority.
337class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
338 public:
339 // The latest priority of the job is always written to |request_priority_|.
340 PriorityMonitoringURLRequestJob(URLRequest* request,
341 NetworkDelegate* network_delegate,
342 RequestPriority* request_priority)
343 : URLRequestTestJob(request, network_delegate),
344 request_priority_(request_priority) {
345 *request_priority_ = DEFAULT_PRIORITY;
346 }
347
348 void SetPriority(RequestPriority priority) override {
349 *request_priority_ = priority;
350 URLRequestTestJob::SetPriority(priority);
351 }
352
353 private:
354 RequestPriority* const request_priority_;
355};
356
[email protected]71c64f62008-11-15 04:36:51357// Do a case-insensitive search through |haystack| for |needle|.
358bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50359 std::string::const_iterator it = std::search(
360 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
361 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51362 return it != haystack.end();
363}
364
danakj8522a25b2016-04-16 00:17:36365std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
366 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28367 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48368 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23369}
370
[email protected]96adadb2010-08-28 01:16:17371// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51372void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17373 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14374 uint16_t cipher_suite =
375 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29376 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17377}
378
[email protected]79e1fd62013-06-20 06:50:04379void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
380 const GURL& host_url) {
381 std::string sent_value;
382
383 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
384 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
385
386 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
387 EXPECT_EQ("keep-alive", sent_value);
388}
389
[email protected]dc5a5cf2012-09-26 02:49:30390// A network delegate that allows the user to choose a subset of request stages
391// to block in. When blocking, the delegate can do one of the following:
392// * synchronously return a pre-specified error code, or
393// * asynchronously return that value via an automatically called callback,
394// or
395// * block and wait for the user to do a callback.
396// Additionally, the user may also specify a redirect URL -- then each request
397// with the current URL different from the redirect target will be redirected
398// to that target, in the on-before-URL-request stage, independent of whether
399// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12400class BlockingNetworkDelegate : public TestNetworkDelegate {
401 public:
[email protected]dc5a5cf2012-09-26 02:49:30402 // Stages in which the delegate can block.
403 enum Stage {
[email protected]9045b8822012-01-13 20:35:35404 NOT_BLOCKED = 0,
405 ON_BEFORE_URL_REQUEST = 1 << 0,
406 ON_BEFORE_SEND_HEADERS = 1 << 1,
407 ON_HEADERS_RECEIVED = 1 << 2,
408 ON_AUTH_REQUIRED = 1 << 3
409 };
410
[email protected]dc5a5cf2012-09-26 02:49:30411 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59412 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30413 enum BlockMode {
414 SYNCHRONOUS, // No callback, returns specified return values.
415 AUTO_CALLBACK, // |this| posts a task to run the callback using the
416 // specified return codes.
417 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
418 // |auth_retval_| are ignored. In every blocking stage the
419 // message loop is quit.
420 };
421
422 // Creates a delegate which does not block at all.
423 explicit BlockingNetworkDelegate(BlockMode block_mode);
424
Wez2a31b222018-06-07 22:07:15425 // Runs the message loop until the delegate blocks.
426 void RunUntilBlocked();
427
[email protected]dc5a5cf2012-09-26 02:49:30428 // For users to trigger a callback returning |response|.
429 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
430 // Only call if |block_mode_| == USER_CALLBACK.
431 void DoCallback(int response);
432 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
433
434 // Setters.
435 void set_retval(int retval) {
436 ASSERT_NE(USER_CALLBACK, block_mode_);
437 ASSERT_NE(ERR_IO_PENDING, retval);
438 ASSERT_NE(OK, retval);
439 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35440 }
441
[email protected]dc5a5cf2012-09-26 02:49:30442 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
443 // |auth_credentials_| will be passed with the response.
444 void set_auth_retval(AuthRequiredResponse auth_retval) {
445 ASSERT_NE(USER_CALLBACK, block_mode_);
446 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
447 auth_retval_ = auth_retval;
448 }
449 void set_auth_credentials(const AuthCredentials& auth_credentials) {
450 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35451 }
452
[email protected]dc5a5cf2012-09-26 02:49:30453 void set_redirect_url(const GURL& url) {
454 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35455 }
456
[email protected]dc5a5cf2012-09-26 02:49:30457 void set_block_on(int block_on) {
458 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35459 }
460
[email protected]dc5a5cf2012-09-26 02:49:30461 // Allows the user to check in which state did we block.
462 Stage stage_blocked_for_callback() const {
463 EXPECT_EQ(USER_CALLBACK, block_mode_);
464 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35465 }
466
467 private:
Wez2a31b222018-06-07 22:07:15468 void OnBlocked();
469
David Benjamind1f287bf2018-06-12 01:57:20470 void RunCallback(int response, CompletionOnceCallback callback);
471 void RunAuthCallback(AuthRequiredResponse response, AuthCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30472
[email protected]9045b8822012-01-13 20:35:35473 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20474 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20475 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:20476 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35477
ryansturm2343cb62016-06-15 01:09:00478 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20479 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:00480 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35481
dchengb03027d2014-10-21 12:00:20482 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35483 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20484 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32485 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16486 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13487 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35488
dchengb03027d2014-10-21 12:00:20489 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35490 URLRequest* request,
491 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20492 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:13493 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35494
[email protected]dc5a5cf2012-09-26 02:49:30495 // Resets the callbacks and |stage_blocked_for_callback_|.
496 void Reset();
[email protected]9045b8822012-01-13 20:35:35497
[email protected]dc5a5cf2012-09-26 02:49:30498 // Checks whether we should block in |stage|. If yes, returns an error code
499 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
David Benjamind1f287bf2018-06-12 01:57:20500 int MaybeBlockStage(Stage stage, CompletionOnceCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30501
502 // Configuration parameters, can be adjusted by public methods:
503 const BlockMode block_mode_;
504
505 // Values returned on blocking stages when mode is SYNCHRONOUS or
506 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
507 int retval_; // To be returned in non-auth stages.
508 AuthRequiredResponse auth_retval_;
509
[email protected]5f714132014-03-26 10:41:16510 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30511 int block_on_; // Bit mask: in which stages to block.
512
513 // |auth_credentials_| will be copied to |*target_auth_credential_| on
514 // callback.
515 AuthCredentials auth_credentials_;
516 AuthCredentials* target_auth_credentials_;
517
518 // Internal variables, not set by not the user:
519 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
520 // USER_CALLBACK).
521 Stage stage_blocked_for_callback_;
522
523 // Callback objects stored during blocking stages.
David Benjamind1f287bf2018-06-12 01:57:20524 CompletionOnceCallback callback_;
[email protected]9045b8822012-01-13 20:35:35525 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30526
Wez2a31b222018-06-07 22:07:15527 // Closure to run to exit RunUntilBlocked().
528 base::OnceClosure on_blocked_;
529
[email protected]dc5a5cf2012-09-26 02:49:30530 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
531
532 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35533};
534
[email protected]dc5a5cf2012-09-26 02:49:30535BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
536 : block_mode_(block_mode),
537 retval_(OK),
538 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
539 block_on_(0),
Raul Tambre94493c652019-03-11 17:18:35540 target_auth_credentials_(nullptr),
[email protected]dc5a5cf2012-09-26 02:49:30541 stage_blocked_for_callback_(NOT_BLOCKED),
Raul Tambre94493c652019-03-11 17:18:35542 weak_factory_(this) {}
[email protected]dc5a5cf2012-09-26 02:49:30543
Wez2a31b222018-06-07 22:07:15544void BlockingNetworkDelegate::RunUntilBlocked() {
545 base::RunLoop run_loop;
546 on_blocked_ = run_loop.QuitClosure();
547 run_loop.Run();
548}
549
[email protected]dc5a5cf2012-09-26 02:49:30550void BlockingNetworkDelegate::DoCallback(int response) {
551 ASSERT_EQ(USER_CALLBACK, block_mode_);
552 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
553 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20554 CompletionOnceCallback callback = std::move(callback_);
[email protected]dc5a5cf2012-09-26 02:49:30555 Reset();
Wez2a31b222018-06-07 22:07:15556
557 // |callback| may trigger completion of a request, so post it as a task, so
558 // it will run under a subsequent TestDelegate::RunUntilComplete() loop.
559 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20560 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
561 weak_factory_.GetWeakPtr(), response,
562 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30563}
564
565void BlockingNetworkDelegate::DoAuthCallback(
566 NetworkDelegate::AuthRequiredResponse response) {
567 ASSERT_EQ(USER_CALLBACK, block_mode_);
568 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20569 AuthCallback auth_callback = std::move(auth_callback_);
[email protected]dc5a5cf2012-09-26 02:49:30570 Reset();
David Benjamind1f287bf2018-06-12 01:57:20571 RunAuthCallback(response, std::move(auth_callback));
[email protected]dc5a5cf2012-09-26 02:49:30572}
573
Wez2a31b222018-06-07 22:07:15574void BlockingNetworkDelegate::OnBlocked() {
575 // If this fails due to |on_blocked_| being null then OnBlocked() was run by
576 // a RunLoop other than RunUntilBlocked(), indicating a bug in the calling
577 // test.
578 std::move(on_blocked_).Run();
579}
580
[email protected]dc5a5cf2012-09-26 02:49:30581void BlockingNetworkDelegate::RunCallback(int response,
David Benjamind1f287bf2018-06-12 01:57:20582 CompletionOnceCallback callback) {
583 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30584}
585
586void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
David Benjamind1f287bf2018-06-12 01:57:20587 AuthCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30588 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
Raul Tambre94493c652019-03-11 17:18:35589 ASSERT_TRUE(target_auth_credentials_ != nullptr);
[email protected]dc5a5cf2012-09-26 02:49:30590 *target_auth_credentials_ = auth_credentials_;
591 }
David Benjamind1f287bf2018-06-12 01:57:20592 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30593}
594
David Benjamind1f287bf2018-06-12 01:57:20595int BlockingNetworkDelegate::OnBeforeURLRequest(URLRequest* request,
596 CompletionOnceCallback callback,
597 GURL* new_url) {
[email protected]dc5a5cf2012-09-26 02:49:30598 if (redirect_url_ == request->url())
599 return OK; // We've already seen this request and redirected elsewhere.
600
David Benjamind1f287bf2018-06-12 01:57:20601 // TestNetworkDelegate always completes synchronously.
602 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
603 request, base::NullCallback(), new_url));
[email protected]dc5a5cf2012-09-26 02:49:30604
605 if (!redirect_url_.is_empty())
606 *new_url = redirect_url_;
607
David Benjamind1f287bf2018-06-12 01:57:20608 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30609}
610
ryansturm2343cb62016-06-15 01:09:00611int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30612 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20613 CompletionOnceCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30614 HttpRequestHeaders* headers) {
David Benjamind1f287bf2018-06-12 01:57:20615 // TestNetworkDelegate always completes synchronously.
616 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
617 request, base::NullCallback(), headers));
[email protected]dc5a5cf2012-09-26 02:49:30618
David Benjamind1f287bf2018-06-12 01:57:20619 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30620}
621
622int BlockingNetworkDelegate::OnHeadersReceived(
623 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20624 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32625 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16626 scoped_refptr<HttpResponseHeaders>* override_response_headers,
627 GURL* allowed_unsafe_redirect_url) {
David Benjamind1f287bf2018-06-12 01:57:20628 // TestNetworkDelegate always completes synchronously.
629 CHECK_NE(ERR_IO_PENDING,
630 TestNetworkDelegate::OnHeadersReceived(
631 request, base::NullCallback(), original_response_headers,
632 override_response_headers, allowed_unsafe_redirect_url));
[email protected]dc5a5cf2012-09-26 02:49:30633
David Benjamind1f287bf2018-06-12 01:57:20634 return MaybeBlockStage(ON_HEADERS_RECEIVED, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30635}
636
637NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
638 URLRequest* request,
639 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20640 AuthCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30641 AuthCredentials* credentials) {
David Benjamind1f287bf2018-06-12 01:57:20642 // TestNetworkDelegate always completes synchronously.
643 CHECK_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING,
644 TestNetworkDelegate::OnAuthRequired(
645 request, auth_info, base::NullCallback(), credentials));
[email protected]dc5a5cf2012-09-26 02:49:30646 // Check that the user has provided callback for the previous blocked stage.
647 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
648
649 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
650 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
651 }
652
653 target_auth_credentials_ = credentials;
654
655 switch (block_mode_) {
656 case SYNCHRONOUS:
657 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
658 *target_auth_credentials_ = auth_credentials_;
659 return auth_retval_;
660
661 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45662 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20663 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunAuthCallback,
664 weak_factory_.GetWeakPtr(), auth_retval_,
665 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30666 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
667
668 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20669 auth_callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30670 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
Wez2a31b222018-06-07 22:07:15671 // We may reach here via a callback prior to RunUntilBlocked(), so post
672 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45673 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15674 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
675 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30676 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
677 }
678 NOTREACHED();
679 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
680}
681
682void BlockingNetworkDelegate::Reset() {
683 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
684 stage_blocked_for_callback_ = NOT_BLOCKED;
685 callback_.Reset();
686 auth_callback_.Reset();
687}
688
689int BlockingNetworkDelegate::MaybeBlockStage(
690 BlockingNetworkDelegate::Stage stage,
David Benjamind1f287bf2018-06-12 01:57:20691 CompletionOnceCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30692 // Check that the user has provided callback for the previous blocked stage.
693 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
694
695 if ((block_on_ & stage) == 0) {
696 return OK;
697 }
698
699 switch (block_mode_) {
700 case SYNCHRONOUS:
701 EXPECT_NE(OK, retval_);
702 return retval_;
703
704 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45705 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20706 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
707 weak_factory_.GetWeakPtr(), retval_,
708 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30709 return ERR_IO_PENDING;
710
711 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20712 callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30713 stage_blocked_for_callback_ = stage;
Wez2a31b222018-06-07 22:07:15714 // We may reach here via a callback prior to RunUntilBlocked(), so post
715 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45716 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15717 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
718 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30719 return ERR_IO_PENDING;
720 }
721 NOTREACHED();
722 return 0;
723}
724
[email protected]d5a4dd62012-05-23 01:41:04725class TestURLRequestContextWithProxy : public TestURLRequestContext {
726 public:
727 // Does not own |delegate|.
728 TestURLRequestContextWithProxy(const std::string& proxy,
729 NetworkDelegate* delegate)
730 : TestURLRequestContext(true) {
Lily Houghton8c2f97d2018-01-22 05:06:59731 context_storage_.set_proxy_resolution_service(
Ramin Halavatica8d5252018-03-12 05:33:49732 ProxyResolutionService::CreateFixed(proxy,
733 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]d5a4dd62012-05-23 01:41:04734 set_network_delegate(delegate);
735 Init();
736 }
Chris Watkins7a41d3552017-12-01 02:13:27737 ~TestURLRequestContextWithProxy() override = default;
[email protected]d5a4dd62012-05-23 01:41:04738};
739
stefanocsbd5be5202016-06-10 03:37:55740// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01741// URI and report to be sent.
742class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55743 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01744 public:
Chris Watkins7a41d3552017-12-01 02:13:27745 MockCertificateReportSender() = default;
746 ~MockCertificateReportSender() override = default;
estark06e0dac2015-08-07 21:56:01747
meacer5d4dc5a2017-04-27 20:37:48748 void Send(const GURL& report_uri,
749 base::StringPiece content_type,
750 base::StringPiece report,
751 const base::Callback<void()>& success_callback,
752 const base::Callback<void(const GURL&, int, int)>& error_callback)
753 override {
estark06e0dac2015-08-07 21:56:01754 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44755 report.CopyToString(&latest_report_);
756 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01757 }
estark06e0dac2015-08-07 21:56:01758 const GURL& latest_report_uri() { return latest_report_uri_; }
759 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44760 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01761
762 private:
763 GURL latest_report_uri_;
764 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44765 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01766};
767
dadrian612337a2016-07-20 22:36:58768// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
769// This is needed because after the certificate failure, the URLRequest will
770// retry the connection, and return a partial SSLInfo with a cached cert status.
771// The partial SSLInfo does not have the OCSP information filled out.
772class OCSPErrorTestDelegate : public TestDelegate {
773 public:
774 void OnSSLCertificateError(URLRequest* request,
Emily Stark79fba5842019-04-25 04:59:36775 int net_error,
dadrian612337a2016-07-20 22:36:58776 const SSLInfo& ssl_info,
777 bool fatal) override {
778 ssl_info_ = ssl_info;
779 on_ssl_certificate_error_called_ = true;
Emily Stark79fba5842019-04-25 04:59:36780 TestDelegate::OnSSLCertificateError(request, net_error, ssl_info, fatal);
dadrian612337a2016-07-20 22:36:58781 }
782
783 bool on_ssl_certificate_error_called() {
784 return on_ssl_certificate_error_called_;
785 }
786
787 SSLInfo ssl_info() { return ssl_info_; }
788
789 private:
790 bool on_ssl_certificate_error_called_ = false;
791 SSLInfo ssl_info_;
792};
793
[email protected]d5a4dd62012-05-23 01:41:04794} // namespace
795
[email protected]a592c0432012-12-01 18:10:29796// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
Bence Béky98447b12018-05-08 03:14:01797class URLRequestTest : public PlatformTest, public WithScopedTaskEnvironment {
[email protected]abb26092010-11-11 22:19:00798 public:
Ryan Sleevib8449e02018-07-15 04:31:07799 URLRequestTest()
800 : default_context_(std::make_unique<TestURLRequestContext>(true)) {
801 default_context_->set_network_delegate(&default_network_delegate_);
802 default_context_->set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50803 job_factory_impl_ = new URLRequestJobFactoryImpl();
804 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50805 }
bengr1bf8e942014-11-07 01:36:50806
dcheng67be2b1f2014-10-27 21:47:29807 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18808 // URLRequestJobs may post clean-up tasks on destruction.
809 base::RunLoop().RunUntilIdle();
Martijn Croonenb1383da2017-10-11 11:56:35810
811 SetTransportSecurityStateSourceForTesting(nullptr);
[email protected]e4034ad2013-09-20 08:36:18812 }
[email protected]87a09a92011-07-14 15:50:50813
dcheng2339883c2014-12-23 00:23:05814 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50815 SetUpFactory();
Ryan Sleevib8449e02018-07-15 04:31:07816 default_context_->set_job_factory(job_factory_.get());
817 default_context_->Init();
bengr1bf8e942014-11-07 01:36:50818 PlatformTest::SetUp();
819 }
820
Ryan Sleevib8449e02018-07-15 04:31:07821 void TearDown() override { default_context_.reset(); }
822
bengr1bf8e942014-11-07 01:36:50823 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20824 job_factory_impl_->SetProtocolHandler(
Bence Béky8f9d7d3952017-10-09 19:58:04825 "data", std::make_unique<DataProtocolHandler>());
brettwa1228ebb2016-10-28 03:51:34826#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50827 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19828 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07829 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50830#endif
831 }
832
833 TestNetworkDelegate* default_network_delegate() {
834 return &default_network_delegate_;
835 }
836
Ryan Sleevib8449e02018-07-15 04:31:07837 TestURLRequestContext& default_context() const { return *default_context_; }
bengr1bf8e942014-11-07 01:36:50838
[email protected]3c5ca8c2011-09-29 01:14:51839 // Adds the TestJobInterceptor to the default context.
840 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23841 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20842 job_factory_impl_->SetProtocolHandler("http", nullptr);
843 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36844 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23845 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51846 }
847
Sergey Ulanov2e49f492017-09-14 19:37:51848 // Creates a temp test file and writes |data| to the file. The file will be
849 // deleted after the test completes.
850 void CreateTestFile(const char* data,
851 size_t data_size,
852 base::FilePath* test_file) {
853 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
854 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
855 // now, Mac and Android bots return a path with a symbolic link.
856 base::FilePath absolute_temp_dir =
857 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
858
859 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
860 ASSERT_EQ(static_cast<int>(data_size),
861 base::WriteFile(*test_file, data, data_size));
862 }
863
[email protected]87a09a92011-07-14 15:50:50864 protected:
vishal.b62985ca92015-04-17 08:45:51865 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24866 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50867 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36868 std::unique_ptr<URLRequestJobFactory> job_factory_;
Ryan Sleevib8449e02018-07-15 04:31:07869 std::unique_ptr<TestURLRequestContext> default_context_;
Sergey Ulanov2e49f492017-09-14 19:37:51870 base::ScopedTempDir temp_dir_;
[email protected]7a0bb4bf2008-11-19 21:41:48871};
872
satoruxddac0442017-05-29 06:06:18873// This NetworkDelegate is picky about what files are accessible. Only
874// whitelisted files are allowed.
875class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
876 public:
Chris Watkins7a41d3552017-12-01 02:13:27877 CookieBlockingNetworkDelegate() = default;
satoruxddac0442017-05-29 06:06:18878
879 // Adds |directory| to the access white list.
880 void AddToWhitelist(const base::FilePath& directory) {
881 whitelist_.insert(directory);
882 }
883
884 private:
885 // Returns true if |path| matches the white list.
886 bool OnCanAccessFileInternal(const base::FilePath& path) const {
887 for (const auto& directory : whitelist_) {
888 if (directory == path || directory.IsParent(path))
889 return true;
890 }
891 return false;
892 }
893
894 // Returns true only if both |original_path| and |absolute_path| match the
895 // white list.
896 bool OnCanAccessFile(const URLRequest& request,
897 const base::FilePath& original_path,
898 const base::FilePath& absolute_path) const override {
899 return (OnCanAccessFileInternal(original_path) &&
900 OnCanAccessFileInternal(absolute_path));
901 }
902
903 std::set<base::FilePath> whitelist_;
904
905 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
906};
907
[email protected]316c1e5e2012-09-12 15:17:44908TEST_F(URLRequestTest, AboutBlankTest) {
909 TestDelegate d;
910 {
rhalavatib7bd7c792017-04-27 05:25:16911 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:07912 default_context().CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
913 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44914
[email protected]f7022f32014-08-21 16:32:19915 r->Start();
916 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44917
Wez2a31b222018-06-07 22:07:15918 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44919
[email protected]f7022f32014-08-21 16:32:19920 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44921 EXPECT_FALSE(d.received_data_before_response());
922 EXPECT_EQ(d.bytes_received(), 0);
Tsuyoshi Horo01faed62019-02-20 22:11:37923 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
924 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04925
926 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19927 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44928 }
929}
930
931TEST_F(URLRequestTest, DataURLImageTest) {
932 TestDelegate d;
933 {
934 // Use our nice little Chrome logo.
Ryan Sleevib8449e02018-07-15 04:31:07935 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
danakj8522a25b2016-04-16 00:17:36936 GURL("data:image/png;base64,"
937 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
938 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
939 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
940 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
941 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
942 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
943 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
944 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
945 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
946 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
947 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
948 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
949 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
950 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
951 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
952 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
953 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
954 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
955 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16956 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44957
[email protected]f7022f32014-08-21 16:32:19958 r->Start();
959 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44960
Wez2a31b222018-06-07 22:07:15961 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44962
[email protected]f7022f32014-08-21 16:32:19963 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44964 EXPECT_FALSE(d.received_data_before_response());
965 EXPECT_EQ(d.bytes_received(), 911);
Tsuyoshi Horo01faed62019-02-20 22:11:37966 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
967 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04968
969 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19970 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44971 }
972}
973
brettwa1228ebb2016-10-28 03:51:34974#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44975TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51976 const char kTestFileContent[] = "Hello";
977 base::FilePath test_file;
978 ASSERT_NO_FATAL_FAILURE(
979 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04980
Sergey Ulanov2e49f492017-09-14 19:37:51981 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:44982
983 TestDelegate d;
984 {
Ryan Sleevib8449e02018-07-15 04:31:07985 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:51986 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44987
[email protected]f7022f32014-08-21 16:32:19988 r->Start();
989 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44990
Wez2a31b222018-06-07 22:07:15991 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44992
[email protected]f7022f32014-08-21 16:32:19993 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44994 EXPECT_EQ(1, d.response_started_count());
995 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:51996 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
Tsuyoshi Horo01faed62019-02-20 22:11:37997 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
998 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04999
1000 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:191001 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:441002 }
1003}
1004
[email protected]ba40bb762012-12-17 07:11:041005TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:511006 const char kTestFileContent[] = "Hello";
1007 base::FilePath test_file;
1008 ASSERT_NO_FATAL_FAILURE(
1009 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
1010
1011 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:041012
1013 TestDelegate d;
1014 {
Ryan Sleevib8449e02018-07-15 04:31:071015 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511016 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:041017
[email protected]f7022f32014-08-21 16:32:191018 r->Start();
1019 EXPECT_TRUE(r->is_pending());
1020 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:041021 }
[email protected]79e1fd62013-06-20 06:50:041022 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:041023 // destroyed.
[email protected]255620da2013-08-19 13:14:291024 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041025}
1026
[email protected]316c1e5e2012-09-12 15:17:441027TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1028 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361029 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441030 FillBuffer(buffer.get(), buffer_size);
1031
Sergey Ulanov2e49f492017-09-14 19:37:511032 base::FilePath test_file;
1033 ASSERT_NO_FATAL_FAILURE(
1034 CreateTestFile(buffer.get(), buffer_size, &test_file));
1035 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441036
1037 const size_t first_byte_position = 500;
1038 const size_t last_byte_position = buffer_size - first_byte_position;
1039 const size_t content_length = last_byte_position - first_byte_position + 1;
1040 std::string partial_buffer_string(buffer.get() + first_byte_position,
1041 buffer.get() + last_byte_position + 1);
1042
1043 TestDelegate d;
1044 {
Ryan Sleevib8449e02018-07-15 04:31:071045 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161046 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441047
1048 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381049 headers.SetHeader(
1050 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591051 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381052 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191053 r->SetExtraRequestHeaders(headers);
1054 r->Start();
1055 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441056
Wez2a31b222018-06-07 22:07:151057 d.RunUntilComplete();
1058
[email protected]f7022f32014-08-21 16:32:191059 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441060 EXPECT_EQ(1, d.response_started_count());
1061 EXPECT_FALSE(d.received_data_before_response());
1062 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1063 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1064 EXPECT_TRUE(partial_buffer_string == d.data_received());
1065 }
[email protected]316c1e5e2012-09-12 15:17:441066}
1067
1068TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1069 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361070 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441071 FillBuffer(buffer.get(), buffer_size);
1072
Sergey Ulanov2e49f492017-09-14 19:37:511073 base::FilePath test_file;
1074 ASSERT_NO_FATAL_FAILURE(
1075 CreateTestFile(buffer.get(), buffer_size, &test_file));
1076 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441077
1078 const size_t first_byte_position = 500;
1079 const size_t last_byte_position = buffer_size - 1;
1080 const size_t content_length = last_byte_position - first_byte_position + 1;
1081 std::string partial_buffer_string(buffer.get() + first_byte_position,
1082 buffer.get() + last_byte_position + 1);
1083
1084 TestDelegate d;
1085 {
Ryan Sleevib8449e02018-07-15 04:31:071086 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161087 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441088
1089 HttpRequestHeaders headers;
1090 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591091 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381092 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191093 r->SetExtraRequestHeaders(headers);
1094 r->Start();
1095 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441096
[email protected]255620da2013-08-19 13:14:291097 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191098 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441099 EXPECT_EQ(1, d.response_started_count());
1100 EXPECT_FALSE(d.received_data_before_response());
1101 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1102 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1103 EXPECT_TRUE(partial_buffer_string == d.data_received());
1104 }
[email protected]316c1e5e2012-09-12 15:17:441105}
1106
1107TEST_F(URLRequestTest, FileTestMultipleRanges) {
1108 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361109 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441110 FillBuffer(buffer.get(), buffer_size);
1111
Sergey Ulanov2e49f492017-09-14 19:37:511112 base::FilePath test_file;
1113 ASSERT_NO_FATAL_FAILURE(
1114 CreateTestFile(buffer.get(), buffer_size, &test_file));
1115 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441116
1117 TestDelegate d;
1118 {
Ryan Sleevib8449e02018-07-15 04:31:071119 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161120 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441121
1122 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381123 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191124 r->SetExtraRequestHeaders(headers);
1125 r->Start();
1126 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441127
Wez2a31b222018-06-07 22:07:151128 d.RunUntilComplete();
1129
[email protected]316c1e5e2012-09-12 15:17:441130 EXPECT_TRUE(d.request_failed());
1131 }
[email protected]316c1e5e2012-09-12 15:17:441132}
1133
[email protected]3ca8b362013-11-11 22:18:071134TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511135 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071136 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511137 ASSERT_NO_FATAL_FAILURE(
1138 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1139
satoruxddac0442017-05-29 06:06:181140 // The directory part of the path returned from CreateTemporaryFileInDir()
1141 // can be slightly different from |absolute_temp_dir| on Windows.
1142 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1143 // Hence the test should use the directory name of |test_file|, rather than
1144 // |absolute_temp_dir|, for whitelisting.
1145 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591146 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071147 {
1148 TestDelegate d;
satoruxddac0442017-05-29 06:06:181149 CookieBlockingNetworkDelegate network_delegate;
1150 network_delegate.AddToWhitelist(real_temp_dir);
Ryan Sleevib8449e02018-07-15 04:31:071151 default_context().set_network_delegate(&network_delegate);
1152 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161153 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191154 r->Start();
Wez2a31b222018-06-07 22:07:151155 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181156 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071157 EXPECT_FALSE(d.request_failed());
1158 EXPECT_EQ(test_data, d.data_received());
1159 }
1160
1161 {
1162 TestDelegate d;
satoruxddac0442017-05-29 06:06:181163 CookieBlockingNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:071164 default_context().set_network_delegate(&network_delegate);
1165 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161166 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191167 r->Start();
Wez2a31b222018-06-07 22:07:151168 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181169 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071170 EXPECT_TRUE(d.request_failed());
1171 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181172 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071173 }
1174}
1175
Wez35539132018-07-17 11:26:051176#if defined(OS_POSIX) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181177
1178TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511179 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181180 // Get an absolute path since temp_dir can contain a symbolic link.
1181 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511182 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181183
1184 // Create a good directory (will be whitelisted) and a good file.
1185 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1186 ASSERT_TRUE(base::CreateDirectory(good_dir));
1187 base::FilePath good_file;
1188 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1189 std::string good_data("good");
1190 base::WriteFile(good_file, good_data.data(), good_data.size());
1191 // See the comment in AllowFileURLs() for why this is done.
1192 base::FilePath real_good_dir = good_file.DirName();
1193
1194 // Create a bad directory (will not be whitelisted) and a bad file.
1195 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1196 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1197 base::FilePath bad_file;
1198 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1199 std::string bad_data("bad");
1200 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1201
1202 // This symlink will point to the good file. Access to the symlink will be
1203 // allowed as both the symlink and the destination file are in the same
1204 // good directory.
1205 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1206 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1207 GURL good_file_url = FilePathToFileURL(good_symlink);
1208 // This symlink will point to the bad file. Even though the symlink is in
1209 // the good directory, access to the symlink will be rejected since it
1210 // points to the bad file.
1211 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1212 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1213 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1214
1215 CookieBlockingNetworkDelegate network_delegate;
1216 network_delegate.AddToWhitelist(real_good_dir);
1217 {
1218 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071219 default_context().set_network_delegate(&network_delegate);
1220 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371221 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181222 r->Start();
Wez2a31b222018-06-07 22:07:151223 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181224 // good_file_url should be allowed.
1225 EXPECT_FALSE(d.request_failed());
1226 EXPECT_EQ(good_data, d.data_received());
1227 }
1228
1229 {
1230 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071231 default_context().set_network_delegate(&network_delegate);
1232 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371233 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181234 r->Start();
Wez2a31b222018-06-07 22:07:151235 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181236 // bad_file_url should be rejected.
1237 EXPECT_TRUE(d.request_failed());
1238 EXPECT_EQ("", d.data_received());
1239 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1240 }
1241}
1242
1243TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511244 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181245 // Get an absolute path since temp_dir can contain a symbolic link.
1246 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511247 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181248
1249 // Create a good directory (will be whitelisted).
1250 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1251 ASSERT_TRUE(base::CreateDirectory(good_dir));
1252
1253 // Create a bad directory (will not be whitelisted).
1254 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1255 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1256
1257 // This symlink will point to the good directory. Access to the symlink
1258 // will be allowed as the symlink is in the good dir that'll be white
1259 // listed.
1260 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1261 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1262 GURL good_file_url = FilePathToFileURL(good_symlink);
1263 // This symlink will point to the bad directory. Even though the symlink is
1264 // in the good directory, access to the symlink will be rejected since it
1265 // points to the bad directory.
1266 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1267 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1268 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1269
1270 CookieBlockingNetworkDelegate network_delegate;
1271 network_delegate.AddToWhitelist(good_dir);
1272 {
1273 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071274 default_context().set_network_delegate(&network_delegate);
1275 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371276 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181277 r->Start();
Wez2a31b222018-06-07 22:07:151278 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181279 // good_file_url should be allowed.
1280 EXPECT_FALSE(d.request_failed());
1281 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1282 }
1283
1284 {
1285 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071286 default_context().set_network_delegate(&network_delegate);
1287 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371288 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181289 r->Start();
Wez2a31b222018-06-07 22:07:151290 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181291 // bad_file_url should be rejected.
1292 EXPECT_TRUE(d.request_failed());
1293 EXPECT_EQ("", d.data_received());
1294 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1295 }
1296}
1297
Wez35539132018-07-17 11:26:051298#endif // defined(OS_POSIX)
[email protected]316c1e5e2012-09-12 15:17:441299
1300TEST_F(URLRequestTest, FileDirCancelTest) {
1301 // Put in mock resource provider.
1302 NetModule::SetResourceProvider(TestNetResourceProvider);
1303
1304 TestDelegate d;
1305 {
[email protected]6cdfd7f2013-02-08 20:40:151306 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:191307 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
[email protected]316c1e5e2012-09-12 15:17:441308 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1309 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1310
Ryan Sleevib8449e02018-07-15 04:31:071311 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161312 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1313 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191314 req->Start();
1315 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441316
1317 d.set_cancel_in_received_data_pending(true);
1318
Wez2a31b222018-06-07 22:07:151319 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441320 }
1321
1322 // Take out mock resource provider.
Raul Tambre94493c652019-03-11 17:18:351323 NetModule::SetResourceProvider(nullptr);
[email protected]316c1e5e2012-09-12 15:17:441324}
1325
[email protected]5f9581402013-10-30 13:08:321326TEST_F(URLRequestTest, FileDirOutputSanity) {
1327 // Verify the general sanity of the the output of the file:
1328 // directory lister by checking for the output of a known existing
1329 // file.
1330 const char sentinel_name[] = "filedir-sentinel";
1331
1332 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191333 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471334 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321335
1336 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161337 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071338 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1339 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191340 req->Start();
Wez2a31b222018-06-07 22:07:151341 d.RunUntilComplete();
[email protected]5f9581402013-10-30 13:08:321342
1343 // Generate entry for the sentinel file.
1344 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581345 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491346 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321347 EXPECT_GT(info.size, 0);
1348 std::string sentinel_output = GetDirectoryListingEntry(
1349 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181350 std::string(sentinel_name), false /* is_dir */, info.size,
1351
[email protected]5f9581402013-10-30 13:08:321352 info.last_modified);
1353
1354 ASSERT_LT(0, d.bytes_received());
1355 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501356 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321357 // Check for the entry generated for the "sentinel" file.
1358 const std::string& data = d.data_received();
1359 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1360}
1361
[email protected]316c1e5e2012-09-12 15:17:441362TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1363 // There is an implicit redirect when loading a file path that matches a
1364 // directory and does not end with a slash. Ensure that following such
1365 // redirects does not crash. See http://crbug.com/18686.
1366
[email protected]6cdfd7f2013-02-08 20:40:151367 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191368 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471369 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441370
1371 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161372 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071373 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1374 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191375 req->Start();
Wez2a31b222018-06-07 22:07:151376 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441377
1378 ASSERT_EQ(1, d.received_redirect_count());
1379 ASSERT_LT(0, d.bytes_received());
1380 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501381 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441382}
1383
1384#if defined(OS_WIN)
1385// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1386TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1387 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071388 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161389 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191390 req->Start();
Wez2a31b222018-06-07 22:07:151391 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441392
1393 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501394 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441395}
[email protected]5ecf7cb282014-05-11 01:49:551396#endif // defined(OS_WIN)
1397
brettwa1228ebb2016-10-28 03:51:341398#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551399
1400TEST_F(URLRequestTest, InvalidUrlTest) {
1401 TestDelegate d;
1402 {
rhalavatib7bd7c792017-04-27 05:25:161403 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:071404 default_context().CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1405 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551406
[email protected]f7022f32014-08-21 16:32:191407 r->Start();
1408 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551409
Wez2a31b222018-06-07 22:07:151410 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551411 EXPECT_TRUE(d.request_failed());
1412 }
1413}
1414
jochen0e3b3a62014-09-16 18:31:231415TEST_F(URLRequestTest, InvalidReferrerTest) {
1416 TestURLRequestContext context;
1417 TestNetworkDelegate network_delegate;
1418 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1419 context.set_network_delegate(&network_delegate);
1420 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361421 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161422 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1423 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231424 req->SetReferrer("https://somewhere.com/");
1425
1426 req->Start();
Wez2a31b222018-06-07 22:07:151427 d.RunUntilComplete();
jochen0e3b3a62014-09-16 18:31:231428 EXPECT_TRUE(d.request_failed());
1429}
1430
[email protected]5ecf7cb282014-05-11 01:49:551431#if defined(OS_WIN)
1432TEST_F(URLRequestTest, ResolveShortcutTest) {
1433 base::FilePath app_path;
Avi Drissman5c80d832018-05-01 17:01:191434 base::PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471435 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551436 app_path = app_path.AppendASCII("with-headers.html");
1437
jdoerrie6312bf62019-02-01 22:03:421438 base::string16 lnk_path = app_path.value() + FILE_PATH_LITERAL(".lnk");
[email protected]5ecf7cb282014-05-11 01:49:551439
1440 base::win::ScopedCOMInitializer com_initializer;
1441
1442 // Temporarily create a shortcut for test
1443 {
Robert Liaoc88f99d12017-10-17 21:48:331444 Microsoft::WRL::ComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161445 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
Raul Tambre94493c652019-03-11 17:18:351446 CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
Robert Liaoc88f99d12017-10-17 21:48:331447 Microsoft::WRL::ComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001448 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
jdoerriebacc1962019-02-07 13:39:221449 EXPECT_TRUE(SUCCEEDED(shell->SetPath(base::as_wcstr(app_path.value()))));
[email protected]5ecf7cb282014-05-11 01:49:551450 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
jdoerriebacc1962019-02-07 13:39:221451 EXPECT_TRUE(SUCCEEDED(persist->Save(base::as_wcstr(lnk_path), TRUE)));
[email protected]5ecf7cb282014-05-11 01:49:551452 }
1453
1454 TestDelegate d;
1455 {
Ryan Sleevib8449e02018-07-15 04:31:071456 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161457 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1458 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551459
[email protected]f7022f32014-08-21 16:32:191460 r->Start();
1461 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551462
Wez2a31b222018-06-07 22:07:151463 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551464
1465 WIN32_FILE_ATTRIBUTE_DATA data;
jdoerriebacc1962019-02-07 13:39:221466 GetFileAttributesEx(base::as_wcstr(app_path.value()), GetFileExInfoStandard,
jdoerrie6312bf62019-02-01 22:03:421467 &data);
jdoerriebacc1962019-02-07 13:39:221468 HANDLE file = CreateFile(base::as_wcstr(app_path.value()), GENERIC_READ,
Raul Tambre94493c652019-03-11 17:18:351469 FILE_SHARE_READ, nullptr, OPEN_EXISTING,
1470 FILE_ATTRIBUTE_NORMAL, nullptr);
[email protected]5ecf7cb282014-05-11 01:49:551471 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361472 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551473 DWORD read_size;
1474 BOOL result;
Raul Tambre94493c652019-03-11 17:18:351475 result =
1476 ReadFile(file, buffer.get(), data.nFileSizeLow, &read_size, nullptr);
[email protected]5ecf7cb282014-05-11 01:49:551477 std::string content(buffer.get(), read_size);
1478 CloseHandle(file);
1479
[email protected]f7022f32014-08-21 16:32:191480 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551481 EXPECT_EQ(1, d.received_redirect_count());
1482 EXPECT_EQ(content, d.data_received());
1483 }
1484
1485 // Clean the shortcut
jdoerriebacc1962019-02-07 13:39:221486 DeleteFile(base::as_wcstr(lnk_path));
[email protected]5ecf7cb282014-05-11 01:49:551487}
1488#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441489
1490// Custom URLRequestJobs for use with interceptor tests
1491class RestartTestJob : public URLRequestTestJob {
1492 public:
1493 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1494 : URLRequestTestJob(request, network_delegate, true) {}
1495 protected:
dchengb03027d2014-10-21 12:00:201496 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441497 private:
Chris Watkins7a41d3552017-12-01 02:13:271498 ~RestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441499};
1500
1501class CancelTestJob : public URLRequestTestJob {
1502 public:
1503 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1504 : URLRequestTestJob(request, network_delegate, true) {}
1505 protected:
dchengb03027d2014-10-21 12:00:201506 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441507 private:
Chris Watkins7a41d3552017-12-01 02:13:271508 ~CancelTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441509};
1510
1511class CancelThenRestartTestJob : public URLRequestTestJob {
1512 public:
1513 explicit CancelThenRestartTestJob(URLRequest* request,
1514 NetworkDelegate* network_delegate)
1515 : URLRequestTestJob(request, network_delegate, true) {
1516 }
1517 protected:
dchengb03027d2014-10-21 12:00:201518 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441519 request_->Cancel();
1520 this->NotifyRestartRequired();
1521 }
1522 private:
Chris Watkins7a41d3552017-12-01 02:13:271523 ~CancelThenRestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441524};
1525
bengr1bf8e942014-11-07 01:36:501526// An Interceptor for use with interceptor tests.
1527class MockURLRequestInterceptor : public URLRequestInterceptor {
1528 public:
1529 // Static getters for canned response header and data strings.
1530 static std::string ok_data() {
1531 return URLRequestTestJob::test_data_1();
1532 }
1533
1534 static std::string ok_headers() {
1535 return URLRequestTestJob::test_headers();
1536 }
1537
1538 static std::string redirect_data() {
1539 return std::string();
1540 }
1541
1542 static std::string redirect_headers() {
1543 return URLRequestTestJob::test_redirect_headers();
1544 }
1545
1546 static std::string error_data() {
1547 return std::string("ohhh nooooo mr. bill!");
1548 }
1549
1550 static std::string error_headers() {
1551 return URLRequestTestJob::test_error_headers();
1552 }
1553
1554 MockURLRequestInterceptor()
1555 : intercept_main_request_(false), restart_main_request_(false),
1556 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1557 simulate_main_network_error_(false),
1558 intercept_redirect_(false), cancel_redirect_request_(false),
1559 intercept_final_response_(false), cancel_final_request_(false),
1560 use_url_request_http_job_(false),
1561 did_intercept_main_(false), did_restart_main_(false),
1562 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1563 did_simulate_error_main_(false),
1564 did_intercept_redirect_(false), did_cancel_redirect_(false),
1565 did_intercept_final_(false), did_cancel_final_(false) {
1566 }
1567
Chris Watkins7a41d3552017-12-01 02:13:271568 ~MockURLRequestInterceptor() override = default;
bengr1bf8e942014-11-07 01:36:501569
1570 // URLRequestInterceptor implementation:
1571 URLRequestJob* MaybeInterceptRequest(
1572 URLRequest* request,
1573 NetworkDelegate* network_delegate) const override {
1574 if (restart_main_request_) {
1575 restart_main_request_ = false;
1576 did_restart_main_ = true;
1577 return new RestartTestJob(request, network_delegate);
1578 }
1579 if (cancel_main_request_) {
1580 cancel_main_request_ = false;
1581 did_cancel_main_ = true;
1582 return new CancelTestJob(request, network_delegate);
1583 }
1584 if (cancel_then_restart_main_request_) {
1585 cancel_then_restart_main_request_ = false;
1586 did_cancel_then_restart_main_ = true;
1587 return new CancelThenRestartTestJob(request, network_delegate);
1588 }
1589 if (simulate_main_network_error_) {
1590 simulate_main_network_error_ = false;
1591 did_simulate_error_main_ = true;
1592 if (use_url_request_http_job_) {
1593 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1594 }
1595 // This job will result in error since the requested URL is not one of the
1596 // URLs supported by these tests.
1597 return new URLRequestTestJob(request, network_delegate, true);
1598 }
1599 if (!intercept_main_request_)
1600 return nullptr;
1601 intercept_main_request_ = false;
1602 did_intercept_main_ = true;
1603 URLRequestTestJob* job = new URLRequestTestJob(request,
1604 network_delegate,
1605 main_headers_,
1606 main_data_,
1607 true);
1608 job->set_load_timing_info(main_request_load_timing_info_);
1609 return job;
1610 }
1611
1612 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1613 NetworkDelegate* network_delegate,
1614 const GURL& location) const override {
1615 if (cancel_redirect_request_) {
1616 cancel_redirect_request_ = false;
1617 did_cancel_redirect_ = true;
1618 return new CancelTestJob(request, network_delegate);
1619 }
1620 if (!intercept_redirect_)
1621 return nullptr;
1622 intercept_redirect_ = false;
1623 did_intercept_redirect_ = true;
1624 if (use_url_request_http_job_) {
1625 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1626 }
1627 return new URLRequestTestJob(request,
1628 network_delegate,
1629 redirect_headers_,
1630 redirect_data_,
1631 true);
1632 }
1633
1634 URLRequestJob* MaybeInterceptResponse(
1635 URLRequest* request,
1636 NetworkDelegate* network_delegate) const override {
1637 if (cancel_final_request_) {
1638 cancel_final_request_ = false;
1639 did_cancel_final_ = true;
1640 return new CancelTestJob(request, network_delegate);
1641 }
1642 if (!intercept_final_response_)
1643 return nullptr;
1644 intercept_final_response_ = false;
1645 did_intercept_final_ = true;
1646 if (use_url_request_http_job_) {
1647 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1648 }
1649 return new URLRequestTestJob(request,
1650 network_delegate,
1651 final_headers_,
1652 final_data_,
1653 true);
1654 }
1655
1656 void set_intercept_main_request(bool intercept_main_request) {
1657 intercept_main_request_ = intercept_main_request;
1658 }
1659
1660 void set_main_headers(const std::string& main_headers) {
1661 main_headers_ = main_headers;
1662 }
1663
1664 void set_main_data(const std::string& main_data) {
1665 main_data_ = main_data;
1666 }
1667
1668 void set_main_request_load_timing_info(
1669 const LoadTimingInfo& main_request_load_timing_info) {
1670 main_request_load_timing_info_ = main_request_load_timing_info;
1671 }
1672
1673 void set_restart_main_request(bool restart_main_request) {
1674 restart_main_request_ = restart_main_request;
1675 }
1676
1677 void set_cancel_main_request(bool cancel_main_request) {
1678 cancel_main_request_ = cancel_main_request;
1679 }
1680
1681 void set_cancel_then_restart_main_request(
1682 bool cancel_then_restart_main_request) {
1683 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1684 }
1685
1686 void set_simulate_main_network_error(bool simulate_main_network_error) {
1687 simulate_main_network_error_ = simulate_main_network_error;
1688 }
1689
1690 void set_intercept_redirect(bool intercept_redirect) {
1691 intercept_redirect_ = intercept_redirect;
1692 }
1693
1694 void set_redirect_headers(const std::string& redirect_headers) {
1695 redirect_headers_ = redirect_headers;
1696 }
1697
1698 void set_redirect_data(const std::string& redirect_data) {
1699 redirect_data_ = redirect_data;
1700 }
1701
1702 void set_cancel_redirect_request(bool cancel_redirect_request) {
1703 cancel_redirect_request_ = cancel_redirect_request;
1704 }
1705
1706 void set_intercept_final_response(bool intercept_final_response) {
1707 intercept_final_response_ = intercept_final_response;
1708 }
1709
1710 void set_final_headers(const std::string& final_headers) {
1711 final_headers_ = final_headers;
1712 }
1713
1714 void set_final_data(const std::string& final_data) {
1715 final_data_ = final_data;
1716 }
1717
1718 void set_cancel_final_request(bool cancel_final_request) {
1719 cancel_final_request_ = cancel_final_request;
1720 }
1721
1722 void set_use_url_request_http_job(bool use_url_request_http_job) {
1723 use_url_request_http_job_ = use_url_request_http_job;
1724 }
1725
1726 bool did_intercept_main() const {
1727 return did_intercept_main_;
1728 }
1729
1730 bool did_restart_main() const {
1731 return did_restart_main_;
1732 }
1733
1734 bool did_cancel_main() const {
1735 return did_cancel_main_;
1736 }
1737
1738 bool did_cancel_then_restart_main() const {
1739 return did_cancel_then_restart_main_;
1740 }
1741
1742 bool did_simulate_error_main() const {
1743 return did_simulate_error_main_;
1744 }
1745
1746 bool did_intercept_redirect() const {
1747 return did_intercept_redirect_;
1748 }
1749
1750 bool did_cancel_redirect() const {
1751 return did_cancel_redirect_;
1752 }
1753
1754 bool did_intercept_final() const {
1755 return did_intercept_final_;
1756 }
1757
1758 bool did_cancel_final() const {
1759 return did_cancel_final_;
1760 }
1761
1762 private:
1763 // Indicate whether to intercept the main request, and if so specify the
1764 // response to return and the LoadTimingInfo to use.
1765 mutable bool intercept_main_request_;
1766 mutable std::string main_headers_;
1767 mutable std::string main_data_;
1768 mutable LoadTimingInfo main_request_load_timing_info_;
1769
1770 // These indicate actions that can be taken within MaybeInterceptRequest.
1771 mutable bool restart_main_request_;
1772 mutable bool cancel_main_request_;
1773 mutable bool cancel_then_restart_main_request_;
1774 mutable bool simulate_main_network_error_;
1775
1776 // Indicate whether to intercept redirects, and if so specify the response to
1777 // return.
1778 mutable bool intercept_redirect_;
1779 mutable std::string redirect_headers_;
1780 mutable std::string redirect_data_;
1781
1782 // Cancel the request within MaybeInterceptRedirect.
1783 mutable bool cancel_redirect_request_;
1784
1785 // Indicate whether to intercept the final response, and if so specify the
1786 // response to return.
1787 mutable bool intercept_final_response_;
1788 mutable std::string final_headers_;
1789 mutable std::string final_data_;
1790
1791 // Cancel the final request within MaybeInterceptResponse.
1792 mutable bool cancel_final_request_;
1793
1794 // Instruct the interceptor to use a real URLRequestHTTPJob.
1795 mutable bool use_url_request_http_job_;
1796
1797 // These indicate if the interceptor did something or not.
1798 mutable bool did_intercept_main_;
1799 mutable bool did_restart_main_;
1800 mutable bool did_cancel_main_;
1801 mutable bool did_cancel_then_restart_main_;
1802 mutable bool did_simulate_error_main_;
1803 mutable bool did_intercept_redirect_;
1804 mutable bool did_cancel_redirect_;
1805 mutable bool did_intercept_final_;
1806 mutable bool did_cancel_final_;
1807};
1808
1809// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1810class URLRequestInterceptorTest : public URLRequestTest {
1811 public:
Raul Tambre94493c652019-03-11 17:18:351812 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:501813
1814 ~URLRequestInterceptorTest() override {
1815 // URLRequestJobs may post clean-up tasks on destruction.
1816 base::RunLoop().RunUntilIdle();
1817 }
1818
1819 void SetUpFactory() override {
1820 interceptor_ = new MockURLRequestInterceptor();
1821 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361822 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501823 }
1824
1825 MockURLRequestInterceptor* interceptor() const {
1826 return interceptor_;
1827 }
1828
1829 private:
1830 MockURLRequestInterceptor* interceptor_;
1831};
1832
1833TEST_F(URLRequestInterceptorTest, Intercept) {
1834 // Intercept the main request and respond with a simple response.
1835 interceptor()->set_intercept_main_request(true);
1836 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1837 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591838 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361839 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161840 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1841 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501842 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1843 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1844 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091845 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041846 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1847 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501848 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191849 req->Start();
Wez2a31b222018-06-07 22:07:151850 d.RunUntilComplete();
[email protected]2bba3252013-04-08 19:50:591851
bengr1bf8e942014-11-07 01:36:501852 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091853 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501854 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1855 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591856
bengr1bf8e942014-11-07 01:36:501857 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501858 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501859 EXPECT_EQ(200, req->response_headers()->response_code());
1860 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1861 EXPECT_EQ(1, d.response_started_count());
1862 EXPECT_EQ(0, d.received_redirect_count());
1863}
[email protected]2bba3252013-04-08 19:50:591864
bengr1bf8e942014-11-07 01:36:501865TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1866 // Intercept the main request and respond with a redirect.
1867 interceptor()->set_intercept_main_request(true);
1868 interceptor()->set_main_headers(
1869 MockURLRequestInterceptor::redirect_headers());
1870 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1871
1872 // Intercept that redirect and respond with a final OK response.
1873 interceptor()->set_intercept_redirect(true);
1874 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1875 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1876
1877 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361878 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161879 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1880 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501881 req->set_method("GET");
1882 req->Start();
Wez2a31b222018-06-07 22:07:151883 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501884
1885 // Check that the interceptor got called as expected.
1886 EXPECT_TRUE(interceptor()->did_intercept_main());
1887 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1888
1889 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501890 int status = d.request_status();
1891 EXPECT_EQ(OK, status);
1892 if (status == OK)
bengr1bf8e942014-11-07 01:36:501893 EXPECT_EQ(200, req->response_headers()->response_code());
1894
1895 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1896 EXPECT_EQ(1, d.response_started_count());
1897 EXPECT_EQ(0, d.received_redirect_count());
1898}
1899
1900TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1901 // Intercept the main request to generate a server error response.
1902 interceptor()->set_intercept_main_request(true);
1903 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1904 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1905
1906 // Intercept that error and respond with an OK response.
1907 interceptor()->set_intercept_final_response(true);
1908 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1909 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1910
1911 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361912 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161913 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1914 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501915 req->set_method("GET");
1916 req->Start();
Wez2a31b222018-06-07 22:07:151917 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501918
1919 // Check that the interceptor got called as expected.
1920 EXPECT_TRUE(interceptor()->did_intercept_main());
1921 EXPECT_TRUE(interceptor()->did_intercept_final());
1922
1923 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501924 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501925 EXPECT_EQ(200, req->response_headers()->response_code());
1926 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1927 EXPECT_EQ(1, d.response_started_count());
1928 EXPECT_EQ(0, d.received_redirect_count());
1929}
1930
1931TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1932 // Intercept the main request to simulate a network error.
1933 interceptor()->set_simulate_main_network_error(true);
1934
1935 // Intercept that error and respond with an OK response.
1936 interceptor()->set_intercept_final_response(true);
1937 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1938 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1939
1940 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361941 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161942 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1943 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501944 req->set_method("GET");
1945 req->Start();
Wez2a31b222018-06-07 22:07:151946 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501947
1948 // Check that the interceptor got called as expected.
1949 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1950 EXPECT_TRUE(interceptor()->did_intercept_final());
1951
1952 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501953 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501954 EXPECT_EQ(200, req->response_headers()->response_code());
1955 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1956 EXPECT_EQ(1, d.response_started_count());
1957 EXPECT_EQ(0, d.received_redirect_count());
1958}
1959
1960TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1961 // Restart the main request.
1962 interceptor()->set_restart_main_request(true);
1963
1964 // then intercept the new main request and respond with an OK response
1965 interceptor()->set_intercept_main_request(true);
1966 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1967 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1968
1969 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361970 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161971 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1972 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501973 req->set_method("GET");
1974 req->Start();
Wez2a31b222018-06-07 22:07:151975 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501976
1977 // Check that the interceptor got called as expected.
1978 EXPECT_TRUE(interceptor()->did_restart_main());
1979 EXPECT_TRUE(interceptor()->did_intercept_main());
1980
1981 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501982 int status = d.request_status();
1983 EXPECT_EQ(OK, status);
1984 if (status == OK)
bengr1bf8e942014-11-07 01:36:501985 EXPECT_EQ(200, req->response_headers()->response_code());
1986
1987 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1988 EXPECT_EQ(1, d.response_started_count());
1989 EXPECT_EQ(0, d.received_redirect_count());
1990}
1991
1992TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1993 // Intercept the main request and cancel from within the restarted job.
1994 interceptor()->set_cancel_main_request(true);
1995
1996 // Set up to intercept the final response and override it with an OK response.
1997 interceptor()->set_intercept_final_response(true);
1998 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1999 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2000
2001 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362002 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162003 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2004 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502005 req->set_method("GET");
2006 req->Start();
Wez2a31b222018-06-07 22:07:152007 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502008
2009 // Check that the interceptor got called as expected.
2010 EXPECT_TRUE(interceptor()->did_cancel_main());
2011 EXPECT_FALSE(interceptor()->did_intercept_final());
2012
2013 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502014 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502015}
2016
2017TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2018 // Intercept the main request and respond with a redirect.
2019 interceptor()->set_intercept_main_request(true);
2020 interceptor()->set_main_headers(
2021 MockURLRequestInterceptor::redirect_headers());
2022 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2023
2024 // Intercept the redirect and cancel from within that job.
2025 interceptor()->set_cancel_redirect_request(true);
2026
2027 // Set up to intercept the final response and override it with an OK response.
2028 interceptor()->set_intercept_final_response(true);
2029 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2030 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2031
2032 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362033 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162034 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2035 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502036 req->set_method("GET");
2037 req->Start();
Wez2a31b222018-06-07 22:07:152038 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502039
2040 // Check that the interceptor got called as expected.
2041 EXPECT_TRUE(interceptor()->did_intercept_main());
2042 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2043 EXPECT_FALSE(interceptor()->did_intercept_final());
2044
2045 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502046 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502047}
2048
2049TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2050 // Intercept the main request to simulate a network error.
2051 interceptor()->set_simulate_main_network_error(true);
2052
2053 // Set up to intercept final the response and cancel from within that job.
2054 interceptor()->set_cancel_final_request(true);
2055
2056 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362057 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162058 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2059 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502060 req->set_method("GET");
2061 req->Start();
Wez2a31b222018-06-07 22:07:152062 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502063
2064 // Check that the interceptor got called as expected.
2065 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2066 EXPECT_TRUE(interceptor()->did_cancel_final());
2067
2068 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502069 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502070}
2071
2072TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2073 // Intercept the main request and cancel then restart from within that job.
2074 interceptor()->set_cancel_then_restart_main_request(true);
2075
2076 // Set up to intercept the final response and override it with an OK response.
2077 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502078 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2079 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502080
2081 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362082 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162083 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2084 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502085 req->set_method("GET");
2086 req->Start();
Wez2a31b222018-06-07 22:07:152087 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502088
2089 // Check that the interceptor got called as expected.
2090 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2091 EXPECT_FALSE(interceptor()->did_intercept_final());
2092
2093 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502094 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592095}
2096
2097// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2098// reused. |connect_time_flags| is used to indicate if there should be dns
2099// or SSL times, and |used_proxy| is used for proxy times.
2100LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2101 int connect_time_flags,
2102 bool used_proxy) {
2103 LoadTimingInfo load_timing;
2104 load_timing.socket_log_id = 1;
2105
2106 if (used_proxy) {
2107 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2108 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2109 }
2110
2111 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2112 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2113 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2114 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2115 }
2116 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2117 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2118 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2119 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2120 }
2121 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2122
2123 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2124 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382125 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2126 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592127 return load_timing;
2128}
2129
2130// Same as above, but in the case of a reused socket.
2131LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2132 bool used_proxy) {
2133 LoadTimingInfo load_timing;
2134 load_timing.socket_log_id = 1;
2135 load_timing.socket_reused = true;
2136
2137 if (used_proxy) {
2138 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2139 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2140 }
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
bengr1bf8e942014-11-07 01:36:502149LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2150 const LoadTimingInfo& job_load_timing,
2151 const URLRequestContext& context,
2152 MockURLRequestInterceptor* interceptor) {
2153 interceptor->set_intercept_main_request(true);
2154 interceptor->set_main_request_load_timing_info(job_load_timing);
2155 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162156 std::unique_ptr<URLRequest> req(
2157 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2158 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502159 req->Start();
Wez2a31b222018-06-07 22:07:152160 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502161
2162 LoadTimingInfo resulting_load_timing;
2163 req->GetLoadTimingInfo(&resulting_load_timing);
2164
2165 // None of these should be modified by the URLRequest.
2166 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2167 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2168 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2169 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382170 EXPECT_EQ(job_load_timing.receive_headers_start,
2171 resulting_load_timing.receive_headers_start);
bengr1bf8e942014-11-07 01:36:502172 EXPECT_EQ(job_load_timing.receive_headers_end,
2173 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572174 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2175 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502176
2177 return resulting_load_timing;
2178}
2179
[email protected]2bba3252013-04-08 19:50:592180// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502181TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592182 base::TimeTicks now = base::TimeTicks::Now();
2183 LoadTimingInfo job_load_timing =
2184 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2185
[email protected]2ca01e52013-10-31 22:05:192186 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502187 RunURLRequestInterceptorLoadTimingTest(
2188 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592189
2190 // Nothing should have been changed by the URLRequest.
2191 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2192 load_timing_result.proxy_resolve_start);
2193 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2194 load_timing_result.proxy_resolve_end);
2195 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2196 load_timing_result.connect_timing.dns_start);
2197 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2198 load_timing_result.connect_timing.dns_end);
2199 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2200 load_timing_result.connect_timing.connect_start);
2201 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2202 load_timing_result.connect_timing.connect_end);
2203 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2204 load_timing_result.connect_timing.ssl_start);
2205 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2206 load_timing_result.connect_timing.ssl_end);
2207
2208 // Redundant sanity check.
2209 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2210}
2211
2212// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502213TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592214 base::TimeTicks now = base::TimeTicks::Now();
2215 LoadTimingInfo job_load_timing =
2216 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2217
[email protected]2ca01e52013-10-31 22:05:192218 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502219 RunURLRequestInterceptorLoadTimingTest(
2220 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592221
2222 // Nothing should have been changed by the URLRequest.
2223 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2224 load_timing_result.proxy_resolve_start);
2225 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2226 load_timing_result.proxy_resolve_end);
2227 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2228 load_timing_result.connect_timing.dns_start);
2229 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2230 load_timing_result.connect_timing.dns_end);
2231 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2232 load_timing_result.connect_timing.connect_start);
2233 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2234 load_timing_result.connect_timing.connect_end);
2235 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2236 load_timing_result.connect_timing.ssl_start);
2237 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2238 load_timing_result.connect_timing.ssl_end);
2239
2240 // Redundant sanity check.
2241 TestLoadTimingNotReusedWithProxy(load_timing_result,
2242 CONNECT_TIMING_HAS_SSL_TIMES);
2243}
2244
2245// Make sure that URLRequest correctly adjusts proxy times when they're before
2246// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102247// the case of reusing a SPDY session. The connected socket is not considered
2248// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592249//
2250// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502251TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592252 base::TimeTicks now = base::TimeTicks::Now();
2253 LoadTimingInfo job_load_timing =
2254 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2255 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2256 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2257 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2258 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2259 job_load_timing.connect_timing.connect_start =
2260 now - base::TimeDelta::FromDays(2);
2261 job_load_timing.connect_timing.connect_end =
2262 now - base::TimeDelta::FromDays(1);
2263
[email protected]2ca01e52013-10-31 22:05:192264 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502265 RunURLRequestInterceptorLoadTimingTest(
2266 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592267
2268 // Proxy times, connect times, and DNS times should all be replaced with
2269 // request_start.
2270 EXPECT_EQ(load_timing_result.request_start,
2271 load_timing_result.proxy_resolve_start);
2272 EXPECT_EQ(load_timing_result.request_start,
2273 load_timing_result.proxy_resolve_end);
2274 EXPECT_EQ(load_timing_result.request_start,
2275 load_timing_result.connect_timing.dns_start);
2276 EXPECT_EQ(load_timing_result.request_start,
2277 load_timing_result.connect_timing.dns_end);
2278 EXPECT_EQ(load_timing_result.request_start,
2279 load_timing_result.connect_timing.connect_start);
2280 EXPECT_EQ(load_timing_result.request_start,
2281 load_timing_result.connect_timing.connect_end);
2282
2283 // Other times should have been left null.
2284 TestLoadTimingNotReusedWithProxy(load_timing_result,
2285 CONNECT_TIMING_HAS_DNS_TIMES);
2286}
2287
2288// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502289TEST_F(URLRequestInterceptorTest,
2290 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592291 base::TimeTicks now = base::TimeTicks::Now();
2292 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2293 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2294 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2295
[email protected]2ca01e52013-10-31 22:05:192296 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502297 RunURLRequestInterceptorLoadTimingTest(
2298 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592299
2300 // Proxy times and connect times should all be replaced with request_start.
2301 EXPECT_EQ(load_timing_result.request_start,
2302 load_timing_result.proxy_resolve_start);
2303 EXPECT_EQ(load_timing_result.request_start,
2304 load_timing_result.proxy_resolve_end);
2305
2306 // Other times should have been left null.
2307 TestLoadTimingReusedWithProxy(load_timing_result);
2308}
2309
2310// Make sure that URLRequest correctly adjusts connect times when they're before
2311// |request_start|, due to reusing a connected socket. The connected socket is
2312// not considered reused in this test (May be a preconnect).
2313//
2314// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502315TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592316 base::TimeTicks now = base::TimeTicks::Now();
2317 LoadTimingInfo job_load_timing =
2318 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2319 job_load_timing.connect_timing.connect_start =
2320 now - base::TimeDelta::FromDays(1);
2321 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2322 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2323 job_load_timing.connect_timing.connect_end =
2324 now - base::TimeDelta::FromDays(4);
2325
[email protected]2ca01e52013-10-31 22:05:192326 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502327 RunURLRequestInterceptorLoadTimingTest(
2328 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592329
2330 // Connect times, and SSL times should be replaced with request_start.
2331 EXPECT_EQ(load_timing_result.request_start,
2332 load_timing_result.connect_timing.connect_start);
2333 EXPECT_EQ(load_timing_result.request_start,
2334 load_timing_result.connect_timing.ssl_start);
2335 EXPECT_EQ(load_timing_result.request_start,
2336 load_timing_result.connect_timing.ssl_end);
2337 EXPECT_EQ(load_timing_result.request_start,
2338 load_timing_result.connect_timing.connect_end);
2339
2340 // Other times should have been left null.
2341 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2342}
2343
2344// Make sure that URLRequest correctly adjusts connect times when they're before
2345// |request_start|, due to reusing a connected socket in the case that there
2346// are also proxy times. The connected socket is not considered reused in this
2347// test (May be a preconnect).
2348//
2349// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502350TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592351 base::TimeTicks now = base::TimeTicks::Now();
2352 LoadTimingInfo job_load_timing =
2353 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2354 job_load_timing.connect_timing.connect_start =
2355 now - base::TimeDelta::FromDays(1);
2356 job_load_timing.connect_timing.connect_end =
2357 now - base::TimeDelta::FromDays(2);
2358
[email protected]2ca01e52013-10-31 22:05:192359 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502360 RunURLRequestInterceptorLoadTimingTest(
2361 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592362
2363 // Connect times should be replaced with proxy_resolve_end.
2364 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2365 load_timing_result.connect_timing.connect_start);
2366 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2367 load_timing_result.connect_timing.connect_end);
2368
2369 // Other times should have been left null.
2370 TestLoadTimingNotReusedWithProxy(load_timing_result,
2371 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2372}
2373
[email protected]316c1e5e2012-09-12 15:17:442374// Check that two different URL requests have different identifiers.
2375TEST_F(URLRequestTest, Identifiers) {
2376 TestDelegate d;
2377 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362378 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162379 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2380 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362381 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162382 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2383 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442384
mmenke19378d22014-09-09 04:12:592385 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442386}
2387
blundellb8163592f2015-12-16 14:22:422388#if defined(OS_IOS)
2389// TODO(droger): Check that a failure to connect to the proxy is reported to
2390// the network delegate. crbug.com/496743
2391#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2392#else
2393#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2394#endif
2395TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442396 MockHostResolver host_resolver;
2397 host_resolver.rules()->AddSimulatedFailure("*");
2398
[email protected]ceefd7fd2012-11-29 00:36:242399 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442400 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2401
2402 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362403 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162404 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2405 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192406 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442407
[email protected]f7022f32014-08-21 16:32:192408 req->Start();
Wez2a31b222018-06-07 22:07:152409 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442410
2411 // Check we see a failed request.
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:222412 // The proxy server should be set before failure.
2413 EXPECT_EQ(ProxyServer::FromPacString("PROXY myproxy:70"),
2414 req->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:502415 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442416
2417 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012418 EXPECT_THAT(network_delegate.last_error(),
2419 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442420 EXPECT_EQ(1, network_delegate.completed_requests());
2421}
2422
[email protected]cba24642014-08-15 20:49:592423// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442424// content is empty.
2425TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2426 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072427 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162428 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192429 req->Start();
Wez2a31b222018-06-07 22:07:152430 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442431 EXPECT_EQ("", d.data_received());
2432 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2433}
2434
[email protected]5033ab82013-03-22 20:17:462435// Make sure that SetPriority actually sets the URLRequest's priority
2436// correctly, both before and after start.
2437TEST_F(URLRequestTest, SetPriorityBasic) {
2438 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072439 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162440 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2441 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192442 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462443
[email protected]f7022f32014-08-21 16:32:192444 req->SetPriority(LOW);
2445 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462446
[email protected]f7022f32014-08-21 16:32:192447 req->Start();
2448 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462449
[email protected]f7022f32014-08-21 16:32:192450 req->SetPriority(MEDIUM);
2451 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462452}
2453
2454// Make sure that URLRequest calls SetPriority on a job before calling
2455// Start on it.
2456TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
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
mmenkeed0498b2015-12-08 23:20:422463 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362464 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422465 req.get(), &default_network_delegate_, &job_priority));
2466 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2467 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462468
[email protected]f7022f32014-08-21 16:32:192469 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462470
[email protected]f7022f32014-08-21 16:32:192471 req->Start();
mmenkeed0498b2015-12-08 23:20:422472 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462473}
2474
2475// Make sure that URLRequest passes on its priority updates to its
2476// job.
2477TEST_F(URLRequestTest, SetJobPriority) {
2478 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072479 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162480 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2481 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462482
mmenkeed0498b2015-12-08 23:20:422483 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362484 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422485 req.get(), &default_network_delegate_, &job_priority));
2486 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462487
[email protected]f7022f32014-08-21 16:32:192488 req->SetPriority(LOW);
2489 req->Start();
mmenkeed0498b2015-12-08 23:20:422490 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462491
[email protected]f7022f32014-08-21 16:32:192492 req->SetPriority(MEDIUM);
2493 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422494 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462495}
2496
[email protected]bb1c4662013-11-14 00:00:072497// Setting the IGNORE_LIMITS load flag should be okay if the priority
2498// is MAXIMUM_PRIORITY.
2499TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2500 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072501 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162502 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2503 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192504 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072505
mmenkeed0498b2015-12-08 23:20:422506 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362507 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422508 req.get(), &default_network_delegate_, &job_priority));
2509 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072510
[email protected]f7022f32014-08-21 16:32:192511 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2512 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072513
[email protected]f7022f32014-08-21 16:32:192514 req->SetPriority(MAXIMUM_PRIORITY);
2515 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072516
[email protected]f7022f32014-08-21 16:32:192517 req->Start();
2518 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422519 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072520}
2521
nick5d570de92015-05-04 20:16:162522namespace {
2523
2524// Less verbose way of running a simple testserver for the tests below.
David Benjamin42116f62017-11-20 21:45:392525class HttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442526 public:
David Benjamin42116f62017-11-20 21:45:392527 explicit HttpTestServer(const base::FilePath& document_root) {
tommycli59a63432015-11-06 00:10:552528 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272529 }
tommycli59a63432015-11-06 00:10:552530
David Benjamin42116f62017-11-20 21:45:392531 HttpTestServer() { AddDefaultHandlers(base::FilePath()); }
tommycli59a63432015-11-06 00:10:552532};
tommyclieae5f75f2015-11-05 19:07:272533
nick5d570de92015-05-04 20:16:162534} // namespace
2535
[email protected]f2f31b32013-01-16 23:24:092536TEST_F(URLRequestTest, DelayedCookieCallback) {
David Benjamin42116f62017-11-20 21:45:392537 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442538 ASSERT_TRUE(test_server.Start());
2539
2540 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362541 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502542 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442543
2544 // Set up a cookie.
2545 {
2546 TestNetworkDelegate network_delegate;
2547 context.set_network_delegate(&network_delegate);
2548 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362549 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552550 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162551 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192552 req->Start();
Wez2a31b222018-06-07 22:07:152553 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442554 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2555 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2556 EXPECT_EQ(1, network_delegate.set_cookie_count());
2557 }
2558
2559 // Verify that the cookie is set.
2560 {
2561 TestNetworkDelegate network_delegate;
2562 context.set_network_delegate(&network_delegate);
2563 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362564 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162565 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2566 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192567 req->Start();
Wez2a31b222018-06-07 22:07:152568 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442569
2570 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2571 != std::string::npos);
2572 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2573 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2574 }
2575}
2576
Aaron Tagliaboschi028009e2019-03-07 16:28:062577class FilteringTestLayeredNetworkDelegate : public LayeredNetworkDelegate {
2578 public:
2579 FilteringTestLayeredNetworkDelegate(
2580 std::unique_ptr<NetworkDelegate> network_delegate)
2581 : LayeredNetworkDelegate(std::move((network_delegate))),
2582 set_cookie_called_count_(0),
Aaron Tagliaboschifd4f3f012019-05-30 23:05:542583 blocked_set_cookie_count_(0),
2584 block_get_cookies_(false),
2585 get_cookie_called_count_(0),
2586 blocked_get_cookie_count_(0) {}
Aaron Tagliaboschi028009e2019-03-07 16:28:062587 ~FilteringTestLayeredNetworkDelegate() override = default;
2588
2589 bool OnCanSetCookieInternal(const URLRequest& request,
2590 const net::CanonicalCookie& cookie,
2591 CookieOptions* options,
2592 bool allowed_from_caller) override {
2593 // Filter out cookies with the same name as |cookie_name_filter_| and
2594 // combine with |allowed_from_caller|.
2595 bool allowed =
2596 allowed_from_caller && !(cookie.Name() == cookie_name_filter_);
2597
2598 ++set_cookie_called_count_;
2599
2600 if (!allowed)
2601 ++blocked_set_cookie_count_;
2602
2603 return allowed;
2604 }
2605
2606 void SetCookieFilter(std::string filter) {
2607 cookie_name_filter_ = std::move(filter);
2608 }
2609
2610 int set_cookie_called_count() { return set_cookie_called_count_; }
2611
2612 int blocked_set_cookie_count() { return blocked_set_cookie_count_; }
2613
2614 void ResetSetCookieCalledCount() { set_cookie_called_count_ = 0; }
2615
2616 void ResetBlockedSetCookieCount() { blocked_set_cookie_count_ = 0; }
2617
Aaron Tagliaboschifd4f3f012019-05-30 23:05:542618 bool OnCanGetCookiesInternal(const URLRequest& request,
2619 const net::CookieList& cookie,
2620 bool allowed_from_caller) override {
2621 // Filter out cookies if |block_get_cookies_| is set and
2622 // combine with |allowed_from_caller|.
2623 bool allowed = allowed_from_caller && !block_get_cookies_;
2624
2625 ++get_cookie_called_count_;
2626
2627 if (!allowed)
2628 ++blocked_get_cookie_count_;
2629
2630 return allowed;
2631 }
2632
2633 void set_block_get_cookies() { block_get_cookies_ = true; }
2634
2635 void unset_block_get_cookies() { block_get_cookies_ = false; }
2636
2637 int get_cookie_called_count() const { return get_cookie_called_count_; }
2638
2639 int blocked_get_cookie_count() const { return blocked_get_cookie_count_; }
2640
2641 void ResetGetCookieCalledCount() { get_cookie_called_count_ = 0; }
2642
2643 void ResetBlockedGetCookieCount() { blocked_get_cookie_count_ = 0; }
2644
Aaron Tagliaboschi028009e2019-03-07 16:28:062645 private:
2646 std::string cookie_name_filter_;
2647 int set_cookie_called_count_;
2648 int blocked_set_cookie_count_;
Aaron Tagliaboschifd4f3f012019-05-30 23:05:542649
2650 bool block_get_cookies_;
2651 int get_cookie_called_count_;
2652 int blocked_get_cookie_count_;
Aaron Tagliaboschi028009e2019-03-07 16:28:062653};
2654
2655TEST_F(URLRequestTest, DelayedCookieCallbackAsync) {
2656 HttpTestServer test_server;
2657 ASSERT_TRUE(test_server.Start());
2658
2659 TestURLRequestContext async_context;
2660 std::unique_ptr<DelayedCookieMonster> delayed_cm =
2661 std::make_unique<DelayedCookieMonster>();
2662 async_context.set_cookie_store(delayed_cm.get());
2663 FilteringTestLayeredNetworkDelegate async_filter_network_delegate(
2664 std::make_unique<TestNetworkDelegate>());
2665 async_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
2666 async_context.set_network_delegate(&async_filter_network_delegate);
2667 TestDelegate async_delegate;
2668
2669 TestURLRequestContext sync_context;
2670 std::unique_ptr<CookieMonster> cm =
Nick Harper57142b1c2019-03-14 21:03:592671 std::make_unique<CookieMonster>(nullptr, nullptr);
Aaron Tagliaboschi028009e2019-03-07 16:28:062672 sync_context.set_cookie_store(cm.get());
2673 FilteringTestLayeredNetworkDelegate sync_filter_network_delegate(
2674 std::make_unique<TestNetworkDelegate>());
2675 sync_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
2676 sync_context.set_network_delegate(&sync_filter_network_delegate);
2677 TestDelegate sync_delegate;
2678
2679 // Add a secure cookie so we can try to set an insecure cookie and have
2680 // SetCanonicalCookie (and therefore SetCookieWithOptions) fail.
2681 GURL::Replacements replace_scheme;
2682 replace_scheme.SetSchemeStr("https");
2683 GURL url = test_server.base_url().ReplaceComponents(replace_scheme);
2684
2685 delayed_cm->SetCookieWithOptionsAsync(url, "AlreadySetCookie=1;Secure",
2686 CookieOptions(),
2687 CookieStore::SetCookiesCallback());
2688 cm->SetCookieWithOptionsAsync(url, "AlreadySetCookie=1;Secure",
2689 CookieOptions(),
2690 CookieStore::SetCookiesCallback());
2691
2692 std::vector<std::string> cookie_lines(
2693 {// Fails on CanonicalCookie::Create for trying to create a secure cookie
2694 // on an insecure host.
2695 "CookieNotSet=1;Secure",
2696 // Fail in FilteringTestLayeredNetworkDelegate::CanGetCookie.
2697 "CookieBlockedOnCanGetCookie=1",
2698 // Fails in SetCanonicalCookie for trying to overwrite a secure cookie
2699 // with an insecure cookie.
2700 "AlreadySetCookie=1",
2701 // Succeeds and added cookie to store. Delayed (which makes the callback
2702 // run asynchronously) in DelayedCookieMonster.
2703 "CookieSet=1"});
2704
2705 for (auto first_cookie_line : cookie_lines) {
2706 for (auto second_cookie_line : cookie_lines) {
2707 // Run with the delayed cookie monster.
2708 std::unique_ptr<URLRequest> request = async_context.CreateRequest(
2709 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2710 second_cookie_line),
2711 DEFAULT_PRIORITY, &async_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2712
2713 request->Start();
2714 async_delegate.RunUntilComplete();
2715 EXPECT_THAT(async_delegate.request_status(), IsOk());
2716
2717 // Run with the regular cookie monster.
2718 request = sync_context.CreateRequest(
2719 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2720 second_cookie_line),
2721 DEFAULT_PRIORITY, &sync_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2722
2723 request->Start();
2724 sync_delegate.RunUntilComplete();
2725 EXPECT_THAT(sync_delegate.request_status(), IsOk());
2726
2727 int expected_set_cookie_count = 0;
2728 int expected_blocked_cookie_count = 0;
2729
2730 if (first_cookie_line != "CookieNotSet=1;Secure")
2731 ++expected_set_cookie_count;
2732 if (second_cookie_line != "CookieNotSet=1;Secure")
2733 ++expected_set_cookie_count;
2734
2735 if (first_cookie_line == "CookieBlockedOnCanGetCookie=1")
2736 ++expected_blocked_cookie_count;
2737 if (second_cookie_line == "CookieBlockedOnCanGetCookie=1")
2738 ++expected_blocked_cookie_count;
2739
2740 EXPECT_EQ(expected_set_cookie_count,
2741 async_filter_network_delegate.set_cookie_called_count());
2742 EXPECT_EQ(expected_blocked_cookie_count,
2743 async_filter_network_delegate.blocked_set_cookie_count());
2744
2745 EXPECT_EQ(expected_set_cookie_count,
2746 sync_filter_network_delegate.set_cookie_called_count());
2747 EXPECT_EQ(expected_blocked_cookie_count,
2748 sync_filter_network_delegate.blocked_set_cookie_count());
2749
2750 async_filter_network_delegate.ResetSetCookieCalledCount();
2751 async_filter_network_delegate.ResetBlockedSetCookieCount();
2752
2753 sync_filter_network_delegate.ResetSetCookieCalledCount();
2754 sync_filter_network_delegate.ResetBlockedSetCookieCount();
2755 }
2756 }
2757}
2758
[email protected]f2f31b32013-01-16 23:24:092759TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392760 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442761 ASSERT_TRUE(test_server.Start());
2762
2763 // Set up a cookie.
2764 {
2765 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072766 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442767 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072768 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552769 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162770 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192771 req->Start();
Wez2a31b222018-06-07 22:07:152772 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442773 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2774 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2775 }
2776
2777 // Verify that the cookie is set.
2778 {
2779 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072780 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442781 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072782 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162783 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2784 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192785 req->Start();
Wez2a31b222018-06-07 22:07:152786 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442787
2788 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2789 != std::string::npos);
2790 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2791 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2792 }
2793
2794 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2795 {
2796 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072797 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442798 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072799 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162800 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2801 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192802 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2803 req->Start();
Wez2a31b222018-06-07 22:07:152804 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442805
2806 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2807 == std::string::npos);
2808
2809 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2810 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2811 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2812 }
2813}
2814
2815TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392816 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442817 ASSERT_TRUE(test_server.Start());
2818
2819 // Set up a cookie.
2820 {
2821 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072822 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442823 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072824 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552825 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162826 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192827 req->Start();
Wez2a31b222018-06-07 22:07:152828 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442829
2830 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2831 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2832 EXPECT_EQ(1, network_delegate.set_cookie_count());
2833 }
2834
2835 // Try to set-up another cookie and update the previous cookie.
2836 {
2837 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072838 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442839 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072840 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552841 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162842 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192843 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2844 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442845
Wez2a31b222018-06-07 22:07:152846 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442847
2848 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2849 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2850 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2851 EXPECT_EQ(0, network_delegate.set_cookie_count());
2852 }
2853
2854 // Verify the cookies weren't saved or updated.
2855 {
2856 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072857 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442858 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072859 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162860 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2861 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192862 req->Start();
Wez2a31b222018-06-07 22:07:152863 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442864
2865 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2866 == std::string::npos);
2867 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2868 != std::string::npos);
2869
2870 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2871 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2872 EXPECT_EQ(0, network_delegate.set_cookie_count());
2873 }
2874}
2875
2876TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392877 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442878 ASSERT_TRUE(test_server.Start());
2879
2880 // Set up a cookie.
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(
tommycli59a63432015-11-06 00:10:552886 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162887 &d, 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_EQ(0, network_delegate.blocked_get_cookies_count());
2892 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2893 }
2894
2895 // Verify that the cookie is set.
2896 {
2897 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072898 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442899 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072900 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162901 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2902 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192903 req->Start();
Wez2a31b222018-06-07 22:07:152904 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442905
2906 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2907 != std::string::npos);
2908
2909 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2910 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182911 TestNetLogEntry::List entries;
2912 net_log_.GetEntries(&entries);
2913 for (const auto& entry : entries) {
2914 EXPECT_NE(entry.type,
2915 NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE);
2916 }
[email protected]316c1e5e2012-09-12 15:17:442917 }
2918
2919 // Verify that the cookie isn't sent.
2920 {
2921 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072922 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442923 TestDelegate d;
2924 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:072925 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162926 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2927 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192928 req->Start();
Wez2a31b222018-06-07 22:07:152929 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442930
2931 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2932 == std::string::npos);
2933
[email protected]22e045f2013-09-20 03:54:032934 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442935 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182936 TestNetLogEntry::List entries;
2937 net_log_.GetEntries(&entries);
2938 ExpectLogContainsSomewhereAfter(
2939 entries, 0, NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE,
2940 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442941 }
2942}
2943
marqf14fff8d2015-12-02 15:52:292944// TODO(crbug.com/564656) This test is flaky on iOS.
2945#if defined(OS_IOS)
2946#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2947#else
2948#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2949#endif
[email protected]316c1e5e2012-09-12 15:17:442950TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392951 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442952 ASSERT_TRUE(test_server.Start());
2953
2954 // Set up a cookie.
2955 {
2956 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072957 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442958 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072959 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552960 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162961 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192962 req->Start();
Wez2a31b222018-06-07 22:07:152963 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442964
2965 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2966 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182967 TestNetLogEntry::List entries;
2968 net_log_.GetEntries(&entries);
2969 for (const auto& entry : entries) {
2970 EXPECT_NE(entry.type,
2971 NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE);
2972 }
[email protected]316c1e5e2012-09-12 15:17:442973 }
2974
2975 // Try to set-up another cookie and update the previous cookie.
2976 {
2977 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072978 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442979 TestDelegate d;
2980 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:072981 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552982 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162983 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192984 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442985
Wez2a31b222018-06-07 22:07:152986 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442987
2988 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2989 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182990 TestNetLogEntry::List entries;
2991 net_log_.GetEntries(&entries);
2992 ExpectLogContainsSomewhereAfter(
2993 entries, 0, NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE,
2994 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442995 }
2996
2997 // Verify the cookies weren't saved or updated.
2998 {
2999 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073000 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443001 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073002 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163003 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3004 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193005 req->Start();
Wez2a31b222018-06-07 22:07:153006 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443007
3008 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
3009 == std::string::npos);
3010 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
3011 != std::string::npos);
3012
3013 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3014 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3015 }
3016}
3017
3018TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:393019 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443020 ASSERT_TRUE(test_server.Start());
3021
3022 // Set up an empty cookie.
3023 {
3024 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073025 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443026 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073027 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163028 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
3029 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193030 req->Start();
Wez2a31b222018-06-07 22:07:153031 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443032
3033 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3034 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3035 EXPECT_EQ(0, network_delegate.set_cookie_count());
3036 }
3037}
3038
3039TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393040 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443041 ASSERT_TRUE(test_server.Start());
3042
3043 // Set up a cookie.
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(
tommycli59a63432015-11-06 00:10:553049 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163050 &d, 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_EQ(0, network_delegate.blocked_get_cookies_count());
3055 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3056 }
3057
3058 // Verify that the cookie is set.
3059 {
3060 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073061 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443062 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073063 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163064 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3065 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193066 req->Start();
Wez2a31b222018-06-07 22:07:153067 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443068
3069 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
3070 != std::string::npos);
3071
3072 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3073 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3074 }
3075
3076 // Verify that the cookie isn't sent.
3077 {
3078 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073079 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443080 TestDelegate d;
3081 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:073082 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163083 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3084 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193085 req->Start();
Wez2a31b222018-06-07 22:07:153086 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443087
3088 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
3089 == std::string::npos);
3090
[email protected]22e045f2013-09-20 03:54:033091 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:443092 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3093 }
3094}
3095
3096TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393097 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443098 ASSERT_TRUE(test_server.Start());
3099
3100 // Set up a 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;
Ryan Sleevib8449e02018-07-15 04:31:073105 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553106 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163107 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193108 req->Start();
Wez2a31b222018-06-07 22:07:153109 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443110
3111 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3112 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3113 }
3114
3115 // Try to set-up another cookie and update the previous cookie.
3116 {
3117 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073118 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443119 TestDelegate d;
3120 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:073121 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553122 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:163123 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193124 req->Start();
[email protected]316c1e5e2012-09-12 15:17:443125
Wez2a31b222018-06-07 22:07:153126 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443127
3128 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3129 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
3130 }
3131
3132 // Verify the cookies weren't saved or updated.
3133 {
3134 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073135 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443136 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073137 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163138 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3139 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193140 req->Start();
Wez2a31b222018-06-07 22:07:153141 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443142
3143 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
3144 == std::string::npos);
3145 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
3146 != std::string::npos);
3147
3148 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3149 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3150 }
3151}
3152
mkwstc5fa7762016-03-28 09:28:233153TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:393154 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:263155 ASSERT_TRUE(test_server.Start());
3156
mkwst202534e32016-01-15 16:07:153157 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073158 default_context().set_network_delegate(&network_delegate);
mkwst202534e32016-01-15 16:07:153159
mkwstf71d0bd2016-03-21 14:15:243160 const std::string kHost = "example.test";
3161 const std::string kSubHost = "subdomain.example.test";
3162 const std::string kCrossHost = "cross-origin.test";
3163
3164 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:263165 {
mkwst3f3daac2015-02-26 20:15:263166 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073167 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
mkwstf71d0bd2016-03-21 14:15:243168 test_server.GetURL(kHost,
3169 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3170 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:163171 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Maks Orlovich8a3e4132019-04-23 16:59:243172 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3173 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 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3177 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:243178 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:263179 }
3180
mkwstf71d0bd2016-03-21 14:15:243181 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:263182 {
mkwst3f3daac2015-02-26 20:15:263183 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073184 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163185 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3186 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463187 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463188 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263189 req->Start();
Wez2a31b222018-06-07 22:07:153190 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263191
mkwstf71d0bd2016-03-21 14:15:243192 EXPECT_NE(std::string::npos,
3193 d.data_received().find("StrictSameSiteCookie=1"));
3194 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263195 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3196 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3197 }
3198
clamyfd58ca072016-12-21 17:18:323199 // Verify that both cookies are sent when the request has no initiator (can
3200 // happen for main frame browser-initiated navigations).
3201 {
3202 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073203 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163204 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3205 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463206 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:323207 req->Start();
Wez2a31b222018-06-07 22:07:153208 d.RunUntilComplete();
clamyfd58ca072016-12-21 17:18:323209
3210 EXPECT_NE(std::string::npos,
3211 d.data_received().find("StrictSameSiteCookie=1"));
3212 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3213 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3214 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3215 }
3216
mkwstf71d0bd2016-03-21 14:15:243217 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263218 {
mkwst3f3daac2015-02-26 20:15:263219 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073220 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163221 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3222 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463223 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463224 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153225 req->Start();
Wez2a31b222018-06-07 22:07:153226 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153227
mkwstf71d0bd2016-03-21 14:15:243228 EXPECT_NE(std::string::npos,
3229 d.data_received().find("StrictSameSiteCookie=1"));
3230 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153231 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3232 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3233 }
3234
mkwstf71d0bd2016-03-21 14:15:243235 // Verify that neither cookie is not sent for cross-site requests.
3236 {
3237 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073238 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163239 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3240 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463241 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463242 req->set_initiator(
3243 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243244 req->Start();
Wez2a31b222018-06-07 22:07:153245 d.RunUntilComplete();
mkwstf71d0bd2016-03-21 14:15:243246
3247 EXPECT_EQ(std::string::npos,
3248 d.data_received().find("StrictSameSiteCookie=1"));
3249 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3250 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3251 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3252 }
3253
3254 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153255 // method is "safe".
3256 {
3257 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073258 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163259 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3260 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463261 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463262 req->set_initiator(
3263 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243264 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153265 req->Start();
Wez2a31b222018-06-07 22:07:153266 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153267
mkwstf71d0bd2016-03-21 14:15:243268 EXPECT_EQ(std::string::npos,
3269 d.data_received().find("StrictSameSiteCookie=1"));
3270 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153271 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3272 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3273 }
3274
mkwstf71d0bd2016-03-21 14:15:243275 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153276 // method is unsafe (e.g. POST).
3277 {
3278 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073279 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163280 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3281 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463282 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463283 req->set_initiator(
3284 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153285 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263286 req->Start();
Wez2a31b222018-06-07 22:07:153287 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263288
mkwstf71d0bd2016-03-21 14:15:243289 EXPECT_EQ(std::string::npos,
3290 d.data_received().find("StrictSameSiteCookie=1"));
3291 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263292 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3293 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3294 }
3295}
3296
Maks Orlovich8a3e4132019-04-23 16:59:243297TEST_F(URLRequestTest, SettingSameSiteCookies) {
3298 HttpTestServer test_server;
3299 ASSERT_TRUE(test_server.Start());
3300
3301 TestNetworkDelegate network_delegate;
3302 default_context().set_network_delegate(&network_delegate);
3303
3304 const std::string kHost = "example.test";
3305 const std::string kSubHost = "subdomain.example.test";
3306 const std::string kCrossHost = "cross-origin.test";
3307
3308 int expected_cookies = 0;
3309
3310 {
3311 TestDelegate d;
3312 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3313 test_server.GetURL(kHost,
3314 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3315 "LaxSameSiteCookie=1;SameSite=Lax"),
3316 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3317 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3318 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
3319
3320 // 'SameSite' cookies are settable from strict same-site contexts
3321 // (same-origin site_for_cookies, same-origin initiator), so this request
3322 // should result in two cookies being created.
3323 expected_cookies += 2;
3324
3325 req->Start();
3326 d.RunUntilComplete();
3327 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3328 }
3329
3330 {
3331 TestDelegate d;
3332 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3333 test_server.GetURL(kHost,
3334 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3335 "LaxSameSiteCookie=1;SameSite=Lax"),
3336 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3337 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3338 req->set_initiator(
3339 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3340
3341 // 'SameSite' cookies are settable from lax same-site contexts (same-origin
3342 // site_for_cookies, cross-site initiator), so this request should result in
3343 // two cookies being created.
3344 expected_cookies += 2;
3345
3346 req->Start();
3347 d.RunUntilComplete();
3348 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3349 }
3350
3351 {
3352 TestDelegate d;
3353 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3354 test_server.GetURL(kHost,
3355 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3356 "LaxSameSiteCookie=1;SameSite=Lax"),
3357 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3358 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
3359 req->set_initiator(
3360 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3361
3362 // 'SameSite' cookies are settable from lax same-site contexts (same-site
3363 // site_for_cookies, cross-site initiator), so this request should result in
3364 // two cookies being created.
3365 expected_cookies += 2;
3366
3367 req->Start();
3368 d.RunUntilComplete();
3369 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3370 }
3371
3372 {
3373 TestDelegate d;
3374 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3375 test_server.GetURL(kHost,
3376 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3377 "LaxSameSiteCookie=1;SameSite=Lax"),
3378 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3379 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
3380
3381 // 'SameSite' cookies are settable from strict same-site contexts (same-site
3382 // site_for_cookies, no initiator), so this request should result in two
3383 // cookies being created.
3384 expected_cookies += 2;
3385
3386 req->Start();
3387 d.RunUntilComplete();
3388 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3389 }
3390
3391 {
3392 TestDelegate d;
3393 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3394 test_server.GetURL(kHost,
3395 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3396 "LaxSameSiteCookie=1;SameSite=Lax"),
3397 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3398 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
3399 req->set_initiator(
3400 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3401
3402 // 'SameSite' cookies are not settable from cross-site contexts, so this
3403 // should not result in any new cookies being created.
3404 expected_cookies += 0;
3405
3406 req->Start();
3407 d.RunUntilComplete();
3408 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3409 }
3410}
3411
estark557a5eb82015-12-01 22:57:103412// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363413TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553414 EmbeddedTestServer http_server;
3415 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363416 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553417 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3418 https_server.AddDefaultHandlers(
3419 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3420 ASSERT_TRUE(http_server.Start());
3421 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363422
estarkb15166b2015-12-18 16:56:383423 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363424 TestURLRequestContext context(true);
3425 context.set_network_delegate(&network_delegate);
3426 context.Init();
3427
estarkb15166b2015-12-18 16:56:383428 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363429 {
3430 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363431 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103432 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163433 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363434 req->Start();
Wez2a31b222018-06-07 22:07:153435 d.RunUntilComplete();
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 // Verify that the cookie is not set.
3441 {
3442 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363443 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163444 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3445 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363446 req->Start();
Wez2a31b222018-06-07 22:07:153447 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363448
jww79aceda2015-12-07 01:56:343449 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3450 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363451 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3452 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3453 }
3454}
3455
estarkb15166b2015-12-18 16:56:383456TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553457 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3458 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363459 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553460 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363461
3462 TestNetworkDelegate network_delegate;
3463 TestURLRequestContext context(true);
3464 context.set_network_delegate(&network_delegate);
3465 context.Init();
3466
estarkb15166b2015-12-18 16:56:383467 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363468 {
3469 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163470 std::unique_ptr<URLRequest> req(context.CreateRequest(
3471 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3472 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363473 req->Start();
Wez2a31b222018-06-07 22:07:153474 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583475 EXPECT_EQ(0, network_delegate.set_cookie_count());
estarkcd39c11f2015-10-19 19:46:363476 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3477 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3478 }
3479
3480 // Verify that the cookie is not set.
3481 {
3482 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363483 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163484 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3485 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363486 req->Start();
Wez2a31b222018-06-07 22:07:153487 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363488
jww79aceda2015-12-07 01:56:343489 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363490 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3491 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3492 }
3493}
3494
estarkb15166b2015-12-18 16:56:383495TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553496 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3497 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363498 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553499 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363500
estarkb15166b2015-12-18 16:56:383501 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363502 TestURLRequestContext context(true);
3503 context.set_network_delegate(&network_delegate);
3504 context.Init();
3505
estarkb15166b2015-12-18 16:56:383506 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363507 {
3508 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363509 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103510 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163511 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363512 req->Start();
Wez2a31b222018-06-07 22:07:153513 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363514 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3515 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3516 }
3517
3518 // Verify that the cookie is set.
3519 {
3520 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363521 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163522 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3523 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363524 req->Start();
Wez2a31b222018-06-07 22:07:153525 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363526
jww79aceda2015-12-07 01:56:343527 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3528 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3529 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3530 }
3531}
3532
3533// Tests that secure cookies can't be set on non-secure origins if strict secure
3534// cookies are enabled.
3535TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3536 EmbeddedTestServer http_server;
3537 http_server.AddDefaultHandlers(
3538 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3539 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3540 https_server.AddDefaultHandlers(
3541 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3542 ASSERT_TRUE(http_server.Start());
3543 ASSERT_TRUE(https_server.Start());
3544
Matt Menkebe9b6eb2018-10-18 12:11:443545 TestNetworkDelegate network_delegate;
jww79aceda2015-12-07 01:56:343546 TestURLRequestContext context(true);
3547 context.set_network_delegate(&network_delegate);
3548 context.Init();
3549
3550 // Try to set a Secure cookie, with experimental features enabled.
3551 {
3552 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363553 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343554 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163555 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343556 req->Start();
Wez2a31b222018-06-07 22:07:153557 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343558 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3559 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3560 }
3561
3562 // Verify that the cookie is not set.
3563 {
3564 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363565 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163566 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3567 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343568 req->Start();
Wez2a31b222018-06-07 22:07:153569 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343570
3571 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3572 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3573 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3574 }
3575}
3576
Thiemo Nagel0793b9c532018-04-18 16:57:583577// The parameter is true for same-site and false for cross-site requests.
3578class URLRequestTestParameterizedSameSite
3579 : public URLRequestTest,
3580 public ::testing::WithParamInterface<bool> {
3581 protected:
3582 URLRequestTestParameterizedSameSite() {
3583 auto params = std::make_unique<HttpNetworkSession::Params>();
3584 params->ignore_certificate_errors = true;
3585 context_.set_http_network_session_params(std::move(params));
3586 context_.set_network_delegate(&network_delegate_);
3587 https_server_.AddDefaultHandlers(
3588 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3589 EXPECT_TRUE(https_server_.Start());
3590 }
3591
3592 // To be called after configuration of |context_| has been finalized.
3593 void InitContext() { context_.Init(); }
3594
3595 const std::string kHost_ = "example.test";
3596 const std::string kCrossHost_ = "cross-site.test";
3597 TestURLRequestContext context_{true};
3598 TestNetworkDelegate network_delegate_;
3599 base::HistogramTester histograms_;
3600 EmbeddedTestServer https_server_{EmbeddedTestServer::TYPE_HTTPS};
3601};
3602
Victor Costan8fb98f6f2019-02-01 17:08:293603INSTANTIATE_TEST_SUITE_P(URLRequestTest,
3604 URLRequestTestParameterizedSameSite,
3605 ::testing::Bool());
Thiemo Nagel0793b9c532018-04-18 16:57:583606
3607TEST_P(URLRequestTestParameterizedSameSite, CookieAgeMetrics) {
3608 const bool same_site = GetParam();
3609 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3610 InitContext();
3611
Mike West86149882017-07-28 10:41:493612 EmbeddedTestServer http_server;
3613 http_server.AddDefaultHandlers(
3614 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
Thiemo Nagel23e0b322018-04-18 12:46:543615 ASSERT_TRUE(http_server.Start());
3616
Thiemo Nagel0793b9c532018-04-18 16:57:583617 // Set two test cookies.
Thiemo Nagel23e0b322018-04-18 12:46:543618 {
3619 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583620 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3621 http_server.GetURL(kHost_, "/set-cookie?cookie=value&cookie2=value2"),
Thiemo Nagel23e0b322018-04-18 12:46:543622 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3623 req->Start();
Wez2a31b222018-06-07 22:07:153624 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583625 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3626 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3627 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3628 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3629 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 0);
3630 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3631 0);
3632 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3633 0);
3634 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3635 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 0);
Thiemo Nagel23e0b322018-04-18 12:46:543636 }
3637
Thiemo Nagel0793b9c532018-04-18 16:57:583638 // Make a secure request.
Thiemo Nagel23e0b322018-04-18 12:46:543639 {
3640 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583641 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3642 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3643 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3644 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103645 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583646 url::Origin::Create(https_server_.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103647 req->Start();
Wez2a31b222018-06-07 22:07:153648 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583649 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3650 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3651 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3652 !same_site);
3653 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3654 same_site);
3655 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3656 0);
3657 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3658 0);
3659 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3660 same_site ? 0 : 2);
3661 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3662 same_site ? 2 : 0);
3663 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3664 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
Mohsen Izadiad6f7592018-04-18 15:57:103665 }
3666
Thiemo Nagel0793b9c532018-04-18 16:57:583667 // Make a non-secure request.
Mohsen Izadiad6f7592018-04-18 15:57:103668 {
3669 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583670 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3671 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
Mohsen Izadiad6f7592018-04-18 15:57:103672 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel0793b9c532018-04-18 16:57:583673 req->set_site_for_cookies(http_server.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103674 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583675 url::Origin::Create(http_server.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103676 req->Start();
Wez2a31b222018-06-07 22:07:153677 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583678 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest",
3679 !same_site);
3680 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest",
3681 same_site);
3682 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3683 !same_site);
3684 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3685 same_site);
3686 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3687 same_site ? 0 : 2);
3688 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3689 same_site ? 2 : 0);
3690 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3691 same_site ? 0 : 2);
3692 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3693 same_site ? 2 : 0);
3694 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3695 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
3696 }
3697}
3698
3699// Cookies with secure attribute (no HSTS) --> k1pSecureAttribute
3700TEST_P(URLRequestTestParameterizedSameSite,
3701 CookieNetworkSecurityMetricSecureAttribute) {
3702 const bool same_site = GetParam();
3703 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3704 InitContext();
3705
3706 // Set cookies.
3707 {
3708 TestDelegate d;
3709 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3710 https_server_.GetURL(kHost_,
3711 "/set-cookie?session-cookie=value;Secure&"
3712 "longlived-cookie=value;Secure;domain=" +
3713 kHost_ + ";Max-Age=360000"),
3714 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3715 req->Start();
Wez2a31b222018-06-07 22:07:153716 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583717 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3718 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3719 }
3720
3721 // Verify that the cookies fall into the correct metrics bucket.
3722 {
3723 TestDelegate d;
3724 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3725 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3726 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3727 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3728 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3729 req->Start();
Wez2a31b222018-06-07 22:07:153730 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583731 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3732 // Static cast of boolean required for MSVC 1911.
3733 histograms_.ExpectBucketCount(
3734 "Cookie.NetworkSecurity",
3735 static_cast<int>(CookieNetworkSecurity::k1pSecureAttribute) |
3736 static_cast<int>(!same_site),
3737 2);
3738 }
3739}
3740
3741// Short-lived host cookie --> k1pHSTSHostCookie
3742TEST_P(URLRequestTestParameterizedSameSite,
3743 CookieNetworkSecurityMetricShortlivedHostCookie) {
3744 const bool same_site = GetParam();
3745 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3746
3747 TransportSecurityState transport_security_state;
3748 transport_security_state.AddHSTS(
3749 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3750 false /* include_subdomains */);
3751 context_.set_transport_security_state(&transport_security_state);
3752 InitContext();
3753
3754 // Set cookie.
3755 {
3756 TestDelegate d;
3757 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3758 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;Max-Age=3600"),
3759 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3760 req->Start();
Wez2a31b222018-06-07 22:07:153761 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583762 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3763 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3764 }
3765
3766 // Verify that the cookie falls into the correct metrics bucket.
3767 {
3768 TestDelegate d;
3769 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3770 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3771 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3772 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3773 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3774 req->Start();
Wez2a31b222018-06-07 22:07:153775 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583776 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3777 // Static cast of boolean required for MSVC 1911.
3778 histograms_.ExpectBucketCount(
3779 "Cookie.NetworkSecurity",
3780 static_cast<int>(CookieNetworkSecurity::k1pHSTSHostCookie) |
3781 static_cast<int>(!same_site),
3782 1);
3783 }
3784}
3785
3786// Long-lived (either due to expiry or due to being a session cookie) host
3787// cookies --> k1pExpiringHSTSHostCookie
3788TEST_P(URLRequestTestParameterizedSameSite,
3789 CookieNetworkSecurityMetricLonglivedHostCookie) {
3790 const bool same_site = GetParam();
3791 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3792
3793 TransportSecurityState transport_security_state;
3794 transport_security_state.AddHSTS(
3795 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3796 false /* include_subdomains */);
3797 context_.set_transport_security_state(&transport_security_state);
3798 InitContext();
3799
3800 // Set cookies.
3801 {
3802 TestDelegate d;
3803 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3804 https_server_.GetURL(kHost_,
3805 "/set-cookie?session-cookie=value&"
3806 "longlived-cookie=value;Max-Age=360000"),
3807 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3808 req->Start();
Wez2a31b222018-06-07 22:07:153809 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583810 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3811 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3812 }
3813
3814 // Verify that the cookies fall into the correct metrics bucket.
3815 {
3816 TestDelegate d;
3817 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3818 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3819 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3820 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3821 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3822 req->Start();
Wez2a31b222018-06-07 22:07:153823 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583824 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3825 // Static cast of boolean required for MSVC 1911.
3826 histograms_.ExpectBucketCount(
3827 "Cookie.NetworkSecurity",
3828 static_cast<int>(CookieNetworkSecurity::k1pExpiringHSTSHostCookie) |
3829 static_cast<int>(!same_site),
3830 2);
3831 }
3832}
3833
3834// Domain cookie with HSTS subdomains with cookie expiry before HSTS expiry -->
3835// k1pHSTSSubdomainsIncluded
3836TEST_P(URLRequestTestParameterizedSameSite,
3837 CookieNetworkSecurityMetricShortlivedDomainCookie) {
3838 const bool same_site = GetParam();
3839 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3840
3841 TransportSecurityState transport_security_state;
3842 transport_security_state.AddHSTS(
3843 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3844 true /* include_subdomains */);
3845 context_.set_transport_security_state(&transport_security_state);
3846 InitContext();
3847
3848 // Set cookie.
3849 {
3850 TestDelegate d;
3851 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3852 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3853 kHost_ + ";Max-Age=3600"),
3854 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3855 req->Start();
Wez2a31b222018-06-07 22:07:153856 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583857 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3858 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3859 }
3860
3861 // Verify that the cookie falls into the correct metrics bucket.
3862 {
3863 TestDelegate d;
3864 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3865 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3866 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3867 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3868 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3869 req->Start();
Wez2a31b222018-06-07 22:07:153870 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583871 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3872 // Static cast of boolean required for MSVC 1911.
3873 histograms_.ExpectBucketCount(
3874 "Cookie.NetworkSecurity",
3875 static_cast<int>(CookieNetworkSecurity::k1pHSTSSubdomainsIncluded) |
3876 static_cast<int>(!same_site),
3877 1);
3878 }
3879}
3880
3881// Long-lived (either due to expiry or due to being a session cookie) domain
3882// cookies with HSTS subdomains --> k1pExpiringHSTSSubdomainsIncluded
3883TEST_P(URLRequestTestParameterizedSameSite,
3884 CookieNetworkSecurityMetricLonglivedDomainCookie) {
3885 const bool same_site = GetParam();
3886 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3887
3888 TransportSecurityState transport_security_state;
3889 transport_security_state.AddHSTS(
3890 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3891 true /* include_subdomains */);
3892 context_.set_transport_security_state(&transport_security_state);
3893 InitContext();
3894
3895 // Set cookies.
3896 {
3897 TestDelegate d;
3898 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3899 https_server_.GetURL(
3900 kHost_, "/set-cookie?session-cookie=value;domain=" + kHost_ + "&" +
3901 "longlived-cookie=value;domain=" + kHost_ +
3902 ";Max-Age=360000"),
3903 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3904 req->Start();
Wez2a31b222018-06-07 22:07:153905 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583906 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3907 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3908 }
3909
3910 // Verify that the cookies fall into the correct metrics bucket.
3911 {
3912 TestDelegate d;
3913 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3914 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3915 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3916 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3917 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3918 req->Start();
Wez2a31b222018-06-07 22:07:153919 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583920 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3921 // Static cast of boolean required for MSVC 1911.
3922 histograms_.ExpectBucketCount(
3923 "Cookie.NetworkSecurity",
3924 static_cast<int>(
3925 CookieNetworkSecurity::k1pExpiringHSTSSubdomainsIncluded) |
3926 static_cast<int>(!same_site),
3927 2);
3928 }
3929}
3930
3931// Domain cookie with HSTS subdomains not included --> k1pHSTSSpoofable
3932TEST_P(URLRequestTestParameterizedSameSite,
3933 CookieNetworkSecurityMetricSpoofableDomainCookie) {
3934 const bool same_site = GetParam();
3935 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3936
3937 TransportSecurityState transport_security_state;
3938 transport_security_state.AddHSTS(
3939 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3940 false /* include_subdomains */);
3941 context_.set_transport_security_state(&transport_security_state);
3942 InitContext();
3943
3944 // Set cookie.
3945 {
3946 TestDelegate d;
3947 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3948 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3949 kHost_ + ";Max-Age=3600"),
3950 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3951 req->Start();
Wez2a31b222018-06-07 22:07:153952 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583953 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3954 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3955 }
3956
3957 // Verify that the cookie falls into the correct metrics bucket.
3958 {
3959 TestDelegate d;
3960 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3961 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3962 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3963 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3964 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3965 req->Start();
Wez2a31b222018-06-07 22:07:153966 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583967 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3968 // Static cast of boolean required for MSVC 1911.
3969 histograms_.ExpectBucketCount(
3970 "Cookie.NetworkSecurity",
3971 static_cast<int>(CookieNetworkSecurity::k1pHSTSSpoofable) |
3972 static_cast<int>(!same_site),
3973 1);
3974 }
3975}
3976
3977// Cookie without HSTS --> k1p(Non)SecureConnection
3978TEST_P(URLRequestTestParameterizedSameSite, CookieNetworkSecurityMetricNoHSTS) {
3979 const bool same_site = GetParam();
3980 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3981 InitContext();
3982
3983 EmbeddedTestServer http_server;
3984 http_server.AddDefaultHandlers(
3985 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3986 ASSERT_TRUE(http_server.Start());
3987
3988 // Set cookies.
3989 {
3990 TestDelegate d;
3991 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3992 https_server_.GetURL(kHost_,
3993 "/set-cookie?cookie=value;domain=" + kHost_ +
3994 ";Max-Age=3600&host-cookie=value"),
3995 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3996 req->Start();
Wez2a31b222018-06-07 22:07:153997 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583998 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3999 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
4000 }
4001
4002 // Verify that the cookie falls into the correct metrics bucket.
4003 {
4004 TestDelegate d;
4005 std::unique_ptr<URLRequest> req(context_.CreateRequest(
4006 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
4007 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4008 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
4009 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
4010 req->Start();
Wez2a31b222018-06-07 22:07:154011 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:584012 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
4013 // Static cast of boolean required for MSVC 1911.
4014 histograms_.ExpectBucketCount(
4015 "Cookie.NetworkSecurity",
4016 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
4017 static_cast<int>(!same_site),
4018 2);
4019 }
4020
4021 // Verify that the cookie falls into the correct metrics bucket.
4022 {
4023 TestDelegate d;
4024 std::unique_ptr<URLRequest> req(context_.CreateRequest(
4025 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4026 TRAFFIC_ANNOTATION_FOR_TESTS));
4027 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
4028 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
4029 req->Start();
Wez2a31b222018-06-07 22:07:154030 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:584031 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 4);
4032 // Static cast of boolean required for MSVC 1911.
4033 histograms_.ExpectBucketCount(
4034 "Cookie.NetworkSecurity",
4035 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
4036 static_cast<int>(!same_site),
4037 2);
4038 // Static cast of boolean required for MSVC 1911.
4039 histograms_.ExpectBucketCount(
4040 "Cookie.NetworkSecurity",
4041 static_cast<int>(CookieNetworkSecurity::k1pNonsecureConnection) |
4042 static_cast<int>(!same_site),
4043 2);
Mike West86149882017-07-28 10:41:494044 }
4045}
4046
[email protected]5095cd72012-11-01 10:29:164047// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
4048// value for the |fixed_date| argument given to the constructor.
4049class FixedDateNetworkDelegate : public TestNetworkDelegate {
4050 public:
4051 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
4052 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:274053 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:164054
[email protected]cba24642014-08-15 20:49:594055 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:204056 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:594057 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:204058 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:594059 const HttpResponseHeaders* original_response_headers,
4060 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134061 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:164062
4063 private:
4064 std::string fixed_date_;
4065
4066 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
4067};
4068
4069int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:594070 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:204071 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:594072 const HttpResponseHeaders* original_response_headers,
4073 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:164074 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:594075 HttpResponseHeaders* new_response_headers =
4076 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:164077
4078 new_response_headers->RemoveHeader("Date");
4079 new_response_headers->AddHeader("Date: " + fixed_date_);
4080
4081 *override_response_headers = new_response_headers;
David Benjamind1f287bf2018-06-12 01:57:204082 return TestNetworkDelegate::OnHeadersReceived(
4083 request, std::move(callback), original_response_headers,
4084 override_response_headers, allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:164085}
4086
4087// Test that cookie expiration times are adjusted for server/client clock
4088// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
4089// headers by defaulting to GMT. (crbug.com/135131)
4090TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:394091 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:164092 ASSERT_TRUE(test_server.Start());
4093
4094 // Set up an expired cookie.
4095 {
4096 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074097 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164098 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074099 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194100 test_server.GetURL(
tommycli59a63432015-11-06 00:10:554101 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:164102 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194103 req->Start();
Wez2a31b222018-06-07 22:07:154104 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164105 }
4106 // Verify that the cookie is not set.
4107 {
4108 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074109 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164110 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074111 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164112 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4113 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194114 req->Start();
Wez2a31b222018-06-07 22:07:154115 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164116
4117 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
4118 }
4119 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
4120 {
4121 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
Ryan Sleevib8449e02018-07-15 04:31:074122 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164123 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074124 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194125 test_server.GetURL(
tommycli59a63432015-11-06 00:10:554126 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:164127 DEFAULT_PRIORITY, &d, 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 // Verify that the cookie is set.
4132 {
4133 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074134 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164135 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074136 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164137 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4138 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194139 req->Start();
Wez2a31b222018-06-07 22:07:154140 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164141
4142 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
4143 }
4144}
4145
4146
[email protected]316c1e5e2012-09-12 15:17:444147// Check that it is impossible to change the referrer in the extra headers of
4148// an URLRequest.
4149TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:394150 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:444151 ASSERT_TRUE(test_server.Start());
4152
4153 // If extra headers contain referer and the request contains a referer,
4154 // only the latter shall be respected.
4155 {
4156 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074157 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164158 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4159 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194160 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:444161
4162 HttpRequestHeaders headers;
4163 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194164 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:444165
[email protected]f7022f32014-08-21 16:32:194166 req->Start();
Wez2a31b222018-06-07 22:07:154167 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444168
4169 EXPECT_EQ("http://foo.com/", d.data_received());
4170 }
4171
4172 // If extra headers contain a referer but the request does not, no referer
4173 // shall be sent in the header.
4174 {
4175 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074176 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164177 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4178 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:444179
4180 HttpRequestHeaders headers;
4181 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194182 req->SetExtraRequestHeaders(headers);
4183 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:444184
[email protected]f7022f32014-08-21 16:32:194185 req->Start();
Wez2a31b222018-06-07 22:07:154186 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444187
4188 EXPECT_EQ("None", d.data_received());
4189 }
4190}
4191
[email protected]b89290212009-08-14 22:37:354192class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:114193 public:
mmenke9f2ec60c2015-06-01 20:59:474194 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:114195
[email protected]b89290212009-08-14 22:37:354196 protected:
[email protected]21184962011-10-26 00:50:304197 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
4198 // |request_method| is the method to use for the initial request.
4199 // |redirect_method| is the method that is expected to be used for the second
4200 // request, after redirection.
4201 // If |include_data| is true, data is uploaded with the request. The
4202 // response body is expected to match it exactly, if and only if
4203 // |request_method| == |redirect_method|.
4204 void HTTPRedirectMethodTest(const GURL& redirect_url,
4205 const std::string& request_method,
4206 const std::string& redirect_method,
4207 bool include_data) {
4208 static const char kData[] = "hello world";
4209 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074210 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164211 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194212 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:304213 if (include_data) {
mmenkecbc2b712014-10-09 20:29:074214 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:304215 HttpRequestHeaders headers;
4216 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244217 base::NumberToString(base::size(kData) - 1));
svaldez5b3a8972015-10-09 23:23:544218 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:194219 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:304220 }
[email protected]f7022f32014-08-21 16:32:194221 req->Start();
Wez2a31b222018-06-07 22:07:154222 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194223 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:504224 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:304225 if (include_data) {
4226 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:544227 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4228 HttpRequestHeaders::kContentLength));
4229 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4230 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304231 EXPECT_EQ(kData, d.data_received());
4232 } else {
svaldez5b3a8972015-10-09 23:23:544233 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4234 HttpRequestHeaders::kContentLength));
4235 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4236 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304237 EXPECT_NE(kData, d.data_received());
4238 }
4239 }
4240 if (HasFailure())
4241 LOG(WARNING) << "Request method was: " << request_method;
4242 }
4243
Alex Clarke1e08882b32017-10-06 14:22:404244 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
4245 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:514246 // |request_method| is the method to use for the initial request.
4247 // |redirect_method| is the method that is expected to be used for the second
4248 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:404249 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:514250 // redirection. If empty, expects that there will be no Origin header.
4251 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
4252 const std::string& request_method,
4253 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:404254 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:514255 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074256 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164257 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:514258 req->set_method(request_method);
4259 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
4260 redirect_url.GetOrigin().spec(), false);
4261 req->Start();
4262
Wez2a31b222018-06-07 22:07:154263 d.RunUntilComplete();
jww5fe460ff2015-03-28 00:22:514264
4265 EXPECT_EQ(redirect_method, req->method());
4266 // Note that there is no check for request success here because, for
4267 // purposes of testing, the request very well may fail. For example, if the
4268 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
4269 // origin, there is not an HTTPS server in this unit test framework, so the
4270 // request would fail. However, that's fine, as long as the request headers
4271 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:404272 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:514273 EXPECT_FALSE(
4274 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
4275 } else {
4276 std::string origin_header;
4277 EXPECT_TRUE(req->extra_request_headers().GetHeader(
4278 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:404279 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:514280 }
4281 }
4282
[email protected]762d2db2010-01-11 19:03:014283 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:014284 const int kMsgSize = 20000; // multiple of 10
4285 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:484286 char* uploadBytes = new char[kMsgSize+1];
4287 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:014288 char marker = 'a';
4289 for (int idx = 0; idx < kMsgSize/10; idx++) {
4290 memcpy(ptr, "----------", 10);
4291 ptr += 10;
4292 if (idx % 100 == 0) {
4293 ptr--;
4294 *ptr++ = marker;
4295 if (++marker > 'z')
4296 marker = 'a';
4297 }
4298 }
4299 uploadBytes[kMsgSize] = '\0';
4300
[email protected]762d2db2010-01-11 19:03:014301 for (int i = 0; i < kIterations; ++i) {
4302 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074303 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164304 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
4305 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194306 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:014307
mmenkecbc2b712014-10-09 20:29:074308 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:014309
[email protected]f7022f32014-08-21 16:32:194310 r->Start();
4311 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:014312
Wez2a31b222018-06-07 22:07:154313 d.RunUntilComplete();
[email protected]762d2db2010-01-11 19:03:014314
maksim.sisovb53724b52016-09-16 05:30:504315 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
4316 << d.request_status();
[email protected]762d2db2010-01-11 19:03:014317
4318 EXPECT_FALSE(d.received_data_before_response());
4319 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:014320 }
4321 delete[] uploadBytes;
4322 }
4323
[email protected]ede03212012-09-07 12:52:264324 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:344325 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074326 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:554327 test_server_.GetURL("/set-many-cookies?" +
Raul Tambre8c1981d2019-02-08 02:22:264328 base::NumberToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:164329 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:344330
[email protected]f7022f32014-08-21 16:32:194331 r->Start();
4332 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:344333
Wez2a31b222018-06-07 22:07:154334 d.RunUntilComplete();
[email protected]263163f2012-06-14 22:40:344335
maksim.sisovb53724b52016-09-16 05:30:504336 if (d.request_status() != OK) {
4337 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
4338 return false;
4339 }
[email protected]263163f2012-06-14 22:40:344340
maksim.sisovb53724b52016-09-16 05:30:504341 return true;
[email protected]263163f2012-06-14 22:40:344342 }
4343
David Benjamin42116f62017-11-20 21:45:394344 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:504345
tommycli59a63432015-11-06 00:10:554346 private:
David Benjamin42116f62017-11-20 21:45:394347 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:354348};
4349
tommycli59a63432015-11-06 00:10:554350namespace {
4351
danakj8522a25b2016-04-16 00:17:364352std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:554353 const test_server::HttpRequest& request) {
4354 if (request.headers.find("Host") == request.headers.end() ||
4355 request.headers.at("Host") != "www.redirect.com" ||
4356 request.method != test_server::METHOD_CONNECT) {
4357 return nullptr;
4358 }
4359
danakj8522a25b2016-04-16 00:17:364360 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554361 new test_server::BasicHttpResponse);
4362 http_response->set_code(HTTP_FOUND);
4363 http_response->AddCustomHeader("Location",
4364 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:484365 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554366}
4367
nharperb7441ef2016-01-25 23:54:144368class TestSSLConfigService : public SSLConfigService {
4369 public:
Nick Harper2243e8002018-09-28 20:33:264370 TestSSLConfigService()
4371 : min_version_(kDefaultSSLVersionMin),
davidben095ebb52017-04-12 22:23:344372 max_version_(kDefaultSSLVersionMax) {}
Ryan Sleevib8449e02018-07-15 04:31:074373 ~TestSSLConfigService() override = default;
nharperb7441ef2016-01-25 23:54:144374
davidben095ebb52017-04-12 22:23:344375 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:144376 void set_min_version(uint16_t version) { min_version_ = version; }
4377
nharperb7441ef2016-01-25 23:54:144378 // SSLConfigService:
4379 void GetSSLConfig(SSLConfig* config) override {
4380 *config = SSLConfig();
davidben095ebb52017-04-12 22:23:344381 config->version_min = min_version_;
4382 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:144383 }
4384
Nick Harper89bc7212018-07-31 19:07:574385 bool CanShareConnectionWithClientCerts(
4386 const std::string& hostname) const override {
4387 return false;
4388 }
4389
nharperb7441ef2016-01-25 23:54:144390 private:
nharperb7441ef2016-01-25 23:54:144391 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:344392 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:144393};
4394
Nick Harper89bc7212018-07-31 19:07:574395} // namespace
4396
nharperb7441ef2016-01-25 23:54:144397// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114398// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:554399// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:114400// follow.
[email protected]f2f31b32013-01-16 23:24:094401TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:554402 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124403 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:554404 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114405
[email protected]ceefd7fd2012-11-29 00:36:244406 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044407 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554408 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504409
[email protected]d1ec59082009-02-11 02:48:154410 TestDelegate d;
4411 {
danakj8522a25b2016-04-16 00:17:364412 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164413 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4414 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194415 r->Start();
4416 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:154417
Wez2a31b222018-06-07 22:07:154418 d.RunUntilComplete();
[email protected]d1ec59082009-02-11 02:48:154419
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:224420 // The proxy server should be set before failure.
4421 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4422 http_test_server()->host_port_pair()),
4423 r->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:504424 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084425 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:154426 // We should not have followed the redirect.
4427 EXPECT_EQ(0, d.received_redirect_count());
4428 }
4429}
4430
[email protected]8202d0c2011-02-23 08:31:144431// This is the same as the previous test, but checks that the network delegate
4432// registers the error.
[email protected]c044616e2013-02-20 02:01:264433TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554434 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144435
[email protected]ceefd7fd2012-11-29 00:36:244436 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044437 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554438 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504439
[email protected]8202d0c2011-02-23 08:31:144440 TestDelegate d;
4441 {
danakj8522a25b2016-04-16 00:17:364442 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164443 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4444 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194445 r->Start();
4446 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144447
Wez2a31b222018-06-07 22:07:154448 d.RunUntilComplete();
[email protected]8202d0c2011-02-23 08:31:144449
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:224450 // The proxy server should be set before failure.
4451 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4452 http_test_server()->host_port_pair()),
4453 r->proxy_server());
[email protected]8202d0c2011-02-23 08:31:144454 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504455 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144456 // We should not have followed the redirect.
4457 EXPECT_EQ(0, d.received_redirect_count());
4458
4459 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014460 EXPECT_THAT(network_delegate.last_error(),
4461 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144462 }
4463}
4464
[email protected]dc5a5cf2012-09-26 02:49:304465// Tests that we can block and asynchronously return OK in various stages.
4466TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4467 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4468 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4469 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4470 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4471 };
Avi Drissman4365a4782018-12-28 19:26:244472 static const size_t blocking_stages_length = base::size(blocking_stages);
[email protected]dc5a5cf2012-09-26 02:49:304473
tommycli59a63432015-11-06 00:10:554474 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304475
4476 TestDelegate d;
4477 BlockingNetworkDelegate network_delegate(
4478 BlockingNetworkDelegate::USER_CALLBACK);
4479 network_delegate.set_block_on(
4480 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4481 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4482 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4483
4484 TestURLRequestContext context(true);
4485 context.set_network_delegate(&network_delegate);
4486 context.Init();
4487
4488 {
danakj8522a25b2016-04-16 00:17:364489 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164490 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4491 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304492
[email protected]f7022f32014-08-21 16:32:194493 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304494 for (size_t i = 0; i < blocking_stages_length; ++i) {
Wez2a31b222018-06-07 22:07:154495 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304496 EXPECT_EQ(blocking_stages[i],
4497 network_delegate.stage_blocked_for_callback());
4498 network_delegate.DoCallback(OK);
4499 }
Wez2a31b222018-06-07 22:07:154500 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194501 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504502 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304503 EXPECT_EQ(1, network_delegate.created_requests());
4504 EXPECT_EQ(0, network_delegate.destroyed_requests());
4505 }
4506 EXPECT_EQ(1, network_delegate.destroyed_requests());
4507}
4508
[email protected]4c76d7c2011-04-15 19:14:124509// Tests that the network delegate can block and cancel a request.
4510TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554511 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124512
4513 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304514 BlockingNetworkDelegate network_delegate(
4515 BlockingNetworkDelegate::AUTO_CALLBACK);
4516 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4517 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124518
[email protected]d5a4dd62012-05-23 01:41:044519 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554520 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504521
[email protected]4c76d7c2011-04-15 19:14:124522 {
rhalavatib7bd7c792017-04-27 05:25:164523 std::unique_ptr<URLRequest> r(
4524 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4525 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124526
[email protected]f7022f32014-08-21 16:32:194527 r->Start();
Wez2a31b222018-06-07 22:07:154528 d.RunUntilComplete();
[email protected]4c76d7c2011-04-15 19:14:124529
[email protected]d8fc4722014-06-13 13:17:154530 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474531 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504532 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124533 EXPECT_EQ(1, network_delegate.created_requests());
4534 EXPECT_EQ(0, network_delegate.destroyed_requests());
4535 }
4536 EXPECT_EQ(1, network_delegate.destroyed_requests());
4537}
4538
[email protected]b4438d32012-09-27 06:15:304539// Helper function for NetworkDelegateCancelRequestAsynchronously and
4540// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4541// delegate operating in |block_mode| and a request for |url|. It blocks the
4542// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4543void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4544 BlockingNetworkDelegate::Stage stage,
4545 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364546 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304547 BlockingNetworkDelegate network_delegate(block_mode);
4548 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4549 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364550
[email protected]b4438d32012-09-27 06:15:304551 TestURLRequestContext context(true);
4552 context.set_network_delegate(&network_delegate);
4553 context.Init();
[email protected]3cd384c602011-08-31 16:12:364554
4555 {
rhalavatib7bd7c792017-04-27 05:25:164556 std::unique_ptr<URLRequest> r(context.CreateRequest(
4557 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364558
[email protected]f7022f32014-08-21 16:32:194559 r->Start();
Wez2a31b222018-06-07 22:07:154560 d.RunUntilComplete();
[email protected]3cd384c602011-08-31 16:12:364561
[email protected]d8fc4722014-06-13 13:17:154562 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474563 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4564 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4565 EXPECT_FALSE(r->proxy_server().is_valid());
4566 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4567 EXPECT_TRUE(r->proxy_server().is_direct());
4568 } else {
4569 NOTREACHED();
4570 }
maksim.sisovb53724b52016-09-16 05:30:504571 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364572 EXPECT_EQ(1, network_delegate.created_requests());
4573 EXPECT_EQ(0, network_delegate.destroyed_requests());
4574 }
4575 EXPECT_EQ(1, network_delegate.destroyed_requests());
4576}
4577
[email protected]b4438d32012-09-27 06:15:304578// The following 3 tests check that the network delegate can cancel a request
4579// synchronously in various stages of the request.
4580TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554581 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304582 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4583 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554584 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304585}
4586
4587TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554588 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304589 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4590 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554591 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304592}
4593
4594TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
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_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554598 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304599}
4600
4601// The following 3 tests check that the network delegate can cancel a request
4602// asynchronously in various stages of the request.
4603TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554604 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304605 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4606 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554607 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304608}
4609
4610TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554611 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304612 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4613 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554614 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304615}
4616
4617TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
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_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554621 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304622}
4623
[email protected]4c76d7c2011-04-15 19:14:124624// Tests that the network delegate can block and redirect a request to a new
4625// URL.
4626TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554627 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124628
4629 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304630 BlockingNetworkDelegate network_delegate(
4631 BlockingNetworkDelegate::AUTO_CALLBACK);
4632 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
Eric Romanda790f92018-11-07 19:17:154633 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]4c76d7c2011-04-15 19:14:124634 network_delegate.set_redirect_url(redirect_url);
4635
[email protected]d5a4dd62012-05-23 01:41:044636 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554637 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504638
[email protected]4c76d7c2011-04-15 19:14:124639 {
Eric Romanda790f92018-11-07 19:17:154640 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164641 std::unique_ptr<URLRequest> r(context.CreateRequest(
4642 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124643
[email protected]6be6fa92014-08-06 23:44:564644 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194645 r->Start();
Wez0e717112018-06-18 23:09:224646 d.RunUntilRedirect();
[email protected]4c76d7c2011-04-15 19:14:124647
[email protected]6be6fa92014-08-06 23:44:564648 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194649 EXPECT_EQ(307, r->GetResponseCode());
4650 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564651 std::string location;
Raul Tambre94493c652019-03-11 17:18:354652 ASSERT_TRUE(
4653 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564654 EXPECT_EQ(redirect_url, GURL(location));
4655
4656 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354657 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4658 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154659 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:504660 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474661 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4662 http_test_server()->host_port_pair()),
4663 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094664 // before_send_headers_with_proxy_count only increments for headers sent
4665 // through an untunneled proxy.
4666 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554667 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4668 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274669
maksim.sisovb53724b52016-09-16 05:30:504670 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194671 EXPECT_EQ(redirect_url, r->url());
4672 EXPECT_EQ(original_url, r->original_url());
4673 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124674 EXPECT_EQ(1, network_delegate.created_requests());
4675 EXPECT_EQ(0, network_delegate.destroyed_requests());
4676 }
4677 EXPECT_EQ(1, network_delegate.destroyed_requests());
4678}
4679
[email protected]b813ed72012-04-05 08:21:364680// Tests that the network delegate can block and redirect a request to a new
4681// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4682TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554683 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364684
4685 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304686 BlockingNetworkDelegate network_delegate(
4687 BlockingNetworkDelegate::SYNCHRONOUS);
Eric Romanda790f92018-11-07 19:17:154688 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]b813ed72012-04-05 08:21:364689 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364690
[email protected]d5a4dd62012-05-23 01:41:044691 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554692 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364693
4694 {
Eric Romanda790f92018-11-07 19:17:154695 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164696 std::unique_ptr<URLRequest> r(context.CreateRequest(
4697 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364698
[email protected]6be6fa92014-08-06 23:44:564699 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194700 r->Start();
Wez0e717112018-06-18 23:09:224701 d.RunUntilRedirect();
[email protected]b813ed72012-04-05 08:21:364702
[email protected]6be6fa92014-08-06 23:44:564703 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194704 EXPECT_EQ(307, r->GetResponseCode());
4705 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564706 std::string location;
Raul Tambre94493c652019-03-11 17:18:354707 ASSERT_TRUE(
4708 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564709 EXPECT_EQ(redirect_url, GURL(location));
4710
4711 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354712 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4713 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154714 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564715
maksim.sisovb53724b52016-09-16 05:30:504716 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474717 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4718 http_test_server()->host_port_pair()),
4719 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094720 // before_send_headers_with_proxy_count only increments for headers sent
4721 // through an untunneled proxy.
4722 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554723 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4724 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504725 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194726 EXPECT_EQ(redirect_url, r->url());
4727 EXPECT_EQ(original_url, r->original_url());
4728 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364729 EXPECT_EQ(1, network_delegate.created_requests());
4730 EXPECT_EQ(0, network_delegate.destroyed_requests());
4731 }
4732 EXPECT_EQ(1, network_delegate.destroyed_requests());
4733}
4734
[email protected]3c5ca8c2011-09-29 01:14:514735// Tests that redirects caused by the network delegate preserve POST data.
4736TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554737 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514738
4739 const char kData[] = "hello world";
4740
4741 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304742 BlockingNetworkDelegate network_delegate(
4743 BlockingNetworkDelegate::AUTO_CALLBACK);
4744 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554745 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514746 network_delegate.set_redirect_url(redirect_url);
4747
[email protected]ef2bf422012-05-11 03:27:094748 TestURLRequestContext context(true);
4749 context.set_network_delegate(&network_delegate);
4750 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514751
4752 {
tommycli59a63432015-11-06 00:10:554753 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164754 std::unique_ptr<URLRequest> r(context.CreateRequest(
4755 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194756 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074757 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514758 HttpRequestHeaders headers;
4759 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244760 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194761 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564762
4763 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194764 r->Start();
Wez0e717112018-06-18 23:09:224765 d.RunUntilRedirect();
[email protected]3c5ca8c2011-09-29 01:14:514766
[email protected]6be6fa92014-08-06 23:44:564767 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194768 EXPECT_EQ(307, r->GetResponseCode());
4769 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564770 std::string location;
Raul Tambre94493c652019-03-11 17:18:354771 ASSERT_TRUE(
4772 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564773 EXPECT_EQ(redirect_url, GURL(location));
4774
4775 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354776 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4777 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154778 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564779
maksim.sisovb53724b52016-09-16 05:30:504780 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194781 EXPECT_EQ(redirect_url, r->url());
4782 EXPECT_EQ(original_url, r->original_url());
4783 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514784 EXPECT_EQ(1, network_delegate.created_requests());
4785 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194786 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514787 EXPECT_EQ(kData, d.data_received());
4788 }
4789 EXPECT_EQ(1, network_delegate.destroyed_requests());
4790}
4791
[email protected]5f714132014-03-26 10:41:164792// Tests that the network delegate can block and redirect a request to a new
4793// URL during OnHeadersReceived.
4794TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554795 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164796
4797 TestDelegate d;
4798 BlockingNetworkDelegate network_delegate(
4799 BlockingNetworkDelegate::AUTO_CALLBACK);
4800 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
Eric Romanda790f92018-11-07 19:17:154801 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]5f714132014-03-26 10:41:164802 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4803
4804 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554805 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164806
4807 {
Eric Romanda790f92018-11-07 19:17:154808 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164809 std::unique_ptr<URLRequest> r(context.CreateRequest(
4810 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164811
[email protected]f7022f32014-08-21 16:32:194812 r->Start();
Wez2a31b222018-06-07 22:07:154813 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:164814
maksim.sisovb53724b52016-09-16 05:30:504815 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474816 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4817 http_test_server()->host_port_pair()),
4818 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094819 // before_send_headers_with_proxy_count only increments for headers sent
4820 // through an untunneled proxy.
4821 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554822 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4823 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194824
maksim.sisovb53724b52016-09-16 05:30:504825 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194826 EXPECT_EQ(redirect_url, r->url());
4827 EXPECT_EQ(original_url, r->original_url());
4828 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164829 EXPECT_EQ(2, network_delegate.created_requests());
4830 EXPECT_EQ(0, network_delegate.destroyed_requests());
4831 }
4832 EXPECT_EQ(1, network_delegate.destroyed_requests());
4833}
4834
[email protected]c2911d72011-10-03 22:16:364835// Tests that the network delegate can synchronously complete OnAuthRequired
4836// by taking no action. This indicates that the NetworkDelegate does not want to
4837// handle the challenge, and is passing the buck along to the
4838// URLRequest::Delegate.
4839TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554840 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364841
4842 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304843 BlockingNetworkDelegate network_delegate(
4844 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364845
[email protected]ef2bf422012-05-11 03:27:094846 TestURLRequestContext context(true);
4847 context.set_network_delegate(&network_delegate);
4848 context.Init();
[email protected]c2911d72011-10-03 22:16:364849
[email protected]f3cf9802011-10-28 18:44:584850 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364851
4852 {
tommycli59a63432015-11-06 00:10:554853 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164854 std::unique_ptr<URLRequest> r(context.CreateRequest(
4855 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194856 r->Start();
[email protected]79e1fd62013-06-20 06:50:044857
Wez2a31b222018-06-07 22:07:154858 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044859
maksim.sisovb53724b52016-09-16 05:30:504860 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194861 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044862 EXPECT_TRUE(d.auth_required_called());
4863 EXPECT_EQ(1, network_delegate.created_requests());
4864 EXPECT_EQ(0, network_delegate.destroyed_requests());
4865 }
4866 EXPECT_EQ(1, network_delegate.destroyed_requests());
4867}
4868
4869TEST_F(URLRequestTestHTTP,
4870 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554871 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044872
4873 TestDelegate d;
4874 BlockingNetworkDelegate network_delegate(
4875 BlockingNetworkDelegate::SYNCHRONOUS);
4876
4877 TestURLRequestContext context(true);
4878 context.set_network_delegate(&network_delegate);
4879 context.Init();
4880
4881 d.set_credentials(AuthCredentials(kUser, kSecret));
4882
4883 {
tommycli59a63432015-11-06 00:10:554884 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164885 std::unique_ptr<URLRequest> r(context.CreateRequest(
4886 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194887 r->Start();
[email protected]79e1fd62013-06-20 06:50:044888
Wez2a31b222018-06-07 22:07:154889 d.RunUntilComplete();
shivanisha8061c4202017-06-13 23:35:524890
[email protected]79e1fd62013-06-20 06:50:044891 {
4892 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194893 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524894 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044895 }
4896
maksim.sisovb53724b52016-09-16 05:30:504897 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194898 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364899 EXPECT_TRUE(d.auth_required_called());
4900 EXPECT_EQ(1, network_delegate.created_requests());
4901 EXPECT_EQ(0, network_delegate.destroyed_requests());
4902 }
4903 EXPECT_EQ(1, network_delegate.destroyed_requests());
4904}
4905
4906// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404907// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364908TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554909 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364910
4911 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304912 BlockingNetworkDelegate network_delegate(
4913 BlockingNetworkDelegate::SYNCHRONOUS);
4914 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364915 network_delegate.set_auth_retval(
4916 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4917
[email protected]f3cf9802011-10-28 18:44:584918 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364919
[email protected]ef2bf422012-05-11 03:27:094920 TestURLRequestContext context(true);
4921 context.set_network_delegate(&network_delegate);
4922 context.Init();
[email protected]c2911d72011-10-03 22:16:364923
4924 {
tommycli59a63432015-11-06 00:10:554925 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164926 std::unique_ptr<URLRequest> r(context.CreateRequest(
4927 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194928 r->Start();
Wez2a31b222018-06-07 22:07:154929 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364930
maksim.sisovb53724b52016-09-16 05:30:504931 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194932 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364933 EXPECT_FALSE(d.auth_required_called());
4934 EXPECT_EQ(1, network_delegate.created_requests());
4935 EXPECT_EQ(0, network_delegate.destroyed_requests());
4936 }
4937 EXPECT_EQ(1, network_delegate.destroyed_requests());
4938}
4939
[email protected]79e1fd62013-06-20 06:50:044940// Same as above, but also tests that GetFullRequestHeaders returns the proper
4941// headers (for the first or second request) when called at the proper times.
4942TEST_F(URLRequestTestHTTP,
4943 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554944 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044945
4946 TestDelegate d;
4947 BlockingNetworkDelegate network_delegate(
4948 BlockingNetworkDelegate::SYNCHRONOUS);
4949 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4950 network_delegate.set_auth_retval(
4951 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4952
4953 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4954
4955 TestURLRequestContext context(true);
4956 context.set_network_delegate(&network_delegate);
4957 context.Init();
4958
4959 {
tommycli59a63432015-11-06 00:10:554960 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164961 std::unique_ptr<URLRequest> r(context.CreateRequest(
4962 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194963 r->Start();
Wez2a31b222018-06-07 22:07:154964 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044965
maksim.sisovb53724b52016-09-16 05:30:504966 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194967 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044968 EXPECT_FALSE(d.auth_required_called());
4969 EXPECT_EQ(1, network_delegate.created_requests());
4970 EXPECT_EQ(0, network_delegate.destroyed_requests());
4971
4972 {
4973 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194974 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044975 EXPECT_TRUE(headers.HasHeader("Authorization"));
4976 }
4977 }
4978 EXPECT_EQ(1, network_delegate.destroyed_requests());
4979}
4980
[email protected]c2911d72011-10-03 22:16:364981// Tests that the network delegate can synchronously complete OnAuthRequired
4982// by cancelling authentication.
4983TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554984 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364985
4986 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304987 BlockingNetworkDelegate network_delegate(
4988 BlockingNetworkDelegate::SYNCHRONOUS);
4989 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364990 network_delegate.set_auth_retval(
4991 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4992
[email protected]ef2bf422012-05-11 03:27:094993 TestURLRequestContext context(true);
4994 context.set_network_delegate(&network_delegate);
4995 context.Init();
[email protected]c2911d72011-10-03 22:16:364996
4997 {
tommycli59a63432015-11-06 00:10:554998 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164999 std::unique_ptr<URLRequest> r(context.CreateRequest(
5000 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195001 r->Start();
Wez2a31b222018-06-07 22:07:155002 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365003
maksim.sisovb53724b52016-09-16 05:30:505004 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195005 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365006 EXPECT_FALSE(d.auth_required_called());
5007 EXPECT_EQ(1, network_delegate.created_requests());
5008 EXPECT_EQ(0, network_delegate.destroyed_requests());
5009 }
5010 EXPECT_EQ(1, network_delegate.destroyed_requests());
5011}
5012
5013// Tests that the network delegate can asynchronously complete OnAuthRequired
5014// by taking no action. This indicates that the NetworkDelegate does not want
5015// to handle the challenge, and is passing the buck along to the
5016// URLRequest::Delegate.
5017TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:555018 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365019
5020 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305021 BlockingNetworkDelegate network_delegate(
5022 BlockingNetworkDelegate::AUTO_CALLBACK);
5023 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365024
[email protected]ef2bf422012-05-11 03:27:095025 TestURLRequestContext context(true);
5026 context.set_network_delegate(&network_delegate);
5027 context.Init();
[email protected]c2911d72011-10-03 22:16:365028
[email protected]f3cf9802011-10-28 18:44:585029 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:365030
5031 {
tommycli59a63432015-11-06 00:10:555032 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165033 std::unique_ptr<URLRequest> r(context.CreateRequest(
5034 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195035 r->Start();
Wez2a31b222018-06-07 22:07:155036 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365037
maksim.sisovb53724b52016-09-16 05:30:505038 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195039 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365040 EXPECT_TRUE(d.auth_required_called());
5041 EXPECT_EQ(1, network_delegate.created_requests());
5042 EXPECT_EQ(0, network_delegate.destroyed_requests());
5043 }
5044 EXPECT_EQ(1, network_delegate.destroyed_requests());
5045}
5046
5047// Tests that the network delegate can asynchronously complete OnAuthRequired
5048// by setting credentials.
5049TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:555050 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365051
5052 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305053 BlockingNetworkDelegate network_delegate(
5054 BlockingNetworkDelegate::AUTO_CALLBACK);
5055 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365056 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365057 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5058
[email protected]f3cf9802011-10-28 18:44:585059 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:365060 network_delegate.set_auth_credentials(auth_credentials);
5061
[email protected]ef2bf422012-05-11 03:27:095062 TestURLRequestContext context(true);
5063 context.set_network_delegate(&network_delegate);
5064 context.Init();
[email protected]c2911d72011-10-03 22:16:365065
5066 {
tommycli59a63432015-11-06 00:10:555067 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165068 std::unique_ptr<URLRequest> r(context.CreateRequest(
5069 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195070 r->Start();
Wez2a31b222018-06-07 22:07:155071 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365072
maksim.sisovb53724b52016-09-16 05:30:505073 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195074 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365075 EXPECT_FALSE(d.auth_required_called());
5076 EXPECT_EQ(1, network_delegate.created_requests());
5077 EXPECT_EQ(0, network_delegate.destroyed_requests());
5078 }
5079 EXPECT_EQ(1, network_delegate.destroyed_requests());
5080}
5081
5082// Tests that the network delegate can asynchronously complete OnAuthRequired
5083// by cancelling authentication.
5084TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:555085 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365086
5087 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305088 BlockingNetworkDelegate network_delegate(
5089 BlockingNetworkDelegate::AUTO_CALLBACK);
5090 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365091 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365092 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
5093
[email protected]ef2bf422012-05-11 03:27:095094 TestURLRequestContext context(true);
5095 context.set_network_delegate(&network_delegate);
5096 context.Init();
[email protected]c2911d72011-10-03 22:16:365097
5098 {
tommycli59a63432015-11-06 00:10:555099 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165100 std::unique_ptr<URLRequest> r(context.CreateRequest(
5101 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195102 r->Start();
Wez2a31b222018-06-07 22:07:155103 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365104
maksim.sisovb53724b52016-09-16 05:30:505105 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195106 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365107 EXPECT_FALSE(d.auth_required_called());
5108 EXPECT_EQ(1, network_delegate.created_requests());
5109 EXPECT_EQ(0, network_delegate.destroyed_requests());
5110 }
5111 EXPECT_EQ(1, network_delegate.destroyed_requests());
5112}
5113
David Benjamin0bda12f2018-02-07 19:58:455114// Tests that NetworkDelegate header overrides from the 401 response do not
5115// affect the 200 response. This is a regression test for
5116// https://crbug.com/801237.
5117TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
5118 ASSERT_TRUE(http_test_server()->Start());
5119
5120 TestDelegate d;
5121 d.set_credentials(AuthCredentials(kUser, kSecret));
5122 default_network_delegate_.set_add_header_to_first_response(true);
5123
5124 {
5125 GURL url(http_test_server()->GetURL("/auth-basic"));
Ryan Sleevib8449e02018-07-15 04:31:075126 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455127 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5128 r->Start();
5129
Wez2a31b222018-06-07 22:07:155130 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455131
5132 EXPECT_EQ(OK, d.request_status());
5133 EXPECT_EQ(200, r->GetResponseCode());
5134 EXPECT_TRUE(d.auth_required_called());
5135 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
5136 }
5137
5138 {
5139 GURL url(http_test_server()->GetURL("/defaultresponse"));
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 // Check that set_add_header_to_first_response normally adds a header.
5147 EXPECT_EQ(OK, d.request_status());
5148 EXPECT_EQ(200, r->GetResponseCode());
5149 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
5150 }
5151}
5152
[email protected]9045b8822012-01-13 20:35:355153// Tests that we can handle when a network request was canceled while we were
5154// waiting for the network delegate.
5155// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
5156TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:555157 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355158
5159 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305160 BlockingNetworkDelegate network_delegate(
5161 BlockingNetworkDelegate::USER_CALLBACK);
5162 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:355163
[email protected]ef2bf422012-05-11 03:27:095164 TestURLRequestContext context(true);
5165 context.set_network_delegate(&network_delegate);
5166 context.Init();
[email protected]9045b8822012-01-13 20:35:355167
5168 {
rhalavatib7bd7c792017-04-27 05:25:165169 std::unique_ptr<URLRequest> r(
5170 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5171 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355172
[email protected]f7022f32014-08-21 16:32:195173 r->Start();
Wez2a31b222018-06-07 22:07:155174 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305175 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
5176 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355177 EXPECT_EQ(0, network_delegate.completed_requests());
5178 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195179 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355180 // Ensure that network delegate is notified.
5181 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505182 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355183 EXPECT_EQ(1, network_delegate.created_requests());
5184 EXPECT_EQ(0, network_delegate.destroyed_requests());
5185 }
5186 EXPECT_EQ(1, network_delegate.destroyed_requests());
5187}
5188
5189// Tests that we can handle when a network request was canceled while we were
5190// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:005191// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
5192// callback.
[email protected]9045b8822012-01-13 20:35:355193TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:555194 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355195
5196 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305197 BlockingNetworkDelegate network_delegate(
5198 BlockingNetworkDelegate::USER_CALLBACK);
5199 network_delegate.set_block_on(
5200 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:355201
[email protected]ef2bf422012-05-11 03:27:095202 TestURLRequestContext context(true);
5203 context.set_network_delegate(&network_delegate);
5204 context.Init();
[email protected]9045b8822012-01-13 20:35:355205
5206 {
rhalavatib7bd7c792017-04-27 05:25:165207 std::unique_ptr<URLRequest> r(
5208 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5209 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355210
[email protected]f7022f32014-08-21 16:32:195211 r->Start();
Wez2a31b222018-06-07 22:07:155212 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305213 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
5214 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355215 EXPECT_EQ(0, network_delegate.completed_requests());
5216 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195217 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355218 // Ensure that network delegate is notified.
5219 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505220 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355221 EXPECT_EQ(1, network_delegate.created_requests());
5222 EXPECT_EQ(0, network_delegate.destroyed_requests());
5223 }
5224 EXPECT_EQ(1, network_delegate.destroyed_requests());
5225}
5226
5227// Tests that we can handle when a network request was canceled while we were
5228// waiting for the network delegate.
5229// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
5230TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:555231 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355232
5233 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305234 BlockingNetworkDelegate network_delegate(
5235 BlockingNetworkDelegate::USER_CALLBACK);
5236 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:355237
[email protected]ef2bf422012-05-11 03:27:095238 TestURLRequestContext context(true);
5239 context.set_network_delegate(&network_delegate);
5240 context.Init();
[email protected]9045b8822012-01-13 20:35:355241
5242 {
rhalavatib7bd7c792017-04-27 05:25:165243 std::unique_ptr<URLRequest> r(
5244 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5245 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355246
[email protected]f7022f32014-08-21 16:32:195247 r->Start();
Wez2a31b222018-06-07 22:07:155248 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305249 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
5250 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355251 EXPECT_EQ(0, network_delegate.completed_requests());
5252 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195253 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355254 // Ensure that network delegate is notified.
5255 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505256 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355257 EXPECT_EQ(1, network_delegate.created_requests());
5258 EXPECT_EQ(0, network_delegate.destroyed_requests());
5259 }
5260 EXPECT_EQ(1, network_delegate.destroyed_requests());
5261}
5262
5263// Tests that we can handle when a network request was canceled while we were
5264// waiting for the network delegate.
5265// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:025266TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:555267 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355268
5269 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305270 BlockingNetworkDelegate network_delegate(
5271 BlockingNetworkDelegate::USER_CALLBACK);
5272 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:355273
[email protected]ef2bf422012-05-11 03:27:095274 TestURLRequestContext context(true);
5275 context.set_network_delegate(&network_delegate);
5276 context.Init();
[email protected]9045b8822012-01-13 20:35:355277
5278 {
danakj8522a25b2016-04-16 00:17:365279 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165280 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
5281 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355282
[email protected]f7022f32014-08-21 16:32:195283 r->Start();
Wez2a31b222018-06-07 22:07:155284 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305285 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
5286 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355287 EXPECT_EQ(0, network_delegate.completed_requests());
5288 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195289 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355290 // Ensure that network delegate is notified.
5291 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505292 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355293 EXPECT_EQ(1, network_delegate.created_requests());
5294 EXPECT_EQ(0, network_delegate.destroyed_requests());
5295 }
5296 EXPECT_EQ(1, network_delegate.destroyed_requests());
5297}
5298
tommycli59a63432015-11-06 00:10:555299namespace {
5300
danakj8522a25b2016-04-16 00:17:365301std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:555302 const test_server::HttpRequest& request) {
5303 if (request.headers.find("Host") == request.headers.end() ||
5304 request.headers.at("Host") != "www.server-auth.com" ||
5305 request.method != test_server::METHOD_CONNECT) {
5306 return nullptr;
5307 }
5308
danakj8522a25b2016-04-16 00:17:365309 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:555310 new test_server::BasicHttpResponse);
5311 http_response->set_code(HTTP_UNAUTHORIZED);
5312 http_response->AddCustomHeader("WWW-Authenticate",
5313 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:485314 return std::move(http_response);
tommycli59a63432015-11-06 00:10:555315}
5316
5317} // namespace
5318
5319// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:115320// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:555321// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:355322TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:555323 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:125324 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:555325 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115326
[email protected]ceefd7fd2012-11-29 00:36:245327 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:045328 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:555329 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:505330
[email protected]dc651782009-02-14 01:45:085331 TestDelegate d;
5332 {
danakj8522a25b2016-04-16 00:17:365333 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165334 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
5335 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:085336
[email protected]f7022f32014-08-21 16:32:195337 r->Start();
5338 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:085339
Wez2a31b222018-06-07 22:07:155340 d.RunUntilComplete();
[email protected]dc651782009-02-14 01:45:085341
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:225342 // The proxy server should be set before failure.
5343 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
5344 http_test_server()->host_port_pair()),
5345 r->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:505346 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:085347 }
5348}
5349
[email protected]b89290212009-08-14 22:37:355350TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:555351 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115352
initial.commit586acc5fe2008-07-26 22:42:525353 TestDelegate d;
5354 {
Ryan Sleevib8449e02018-07-15 04:31:075355 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165356 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5357 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525358
[email protected]f7022f32014-08-21 16:32:195359 r->Start();
5360 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525361
Wez2a31b222018-06-07 22:07:155362 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525363
5364 EXPECT_EQ(1, d.response_started_count());
5365 EXPECT_FALSE(d.received_data_before_response());
5366 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555367 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375368 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555369 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375370 r->GetResponseRemoteEndpoint().port());
[email protected]c31a54592009-09-04 02:36:165371
[email protected]9e743cd2010-03-16 07:03:535372 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:525373 }
initial.commit586acc5fe2008-07-26 22:42:525374}
5375
[email protected]263163f2012-06-14 22:40:345376// This test has the server send a large number of cookies to the client.
5377// To ensure that no number of cookies causes a crash, a galloping binary
5378// search is used to estimate that maximum number of cookies that are accepted
5379// by the browser. Beyond the maximum number, the request will fail with
5380// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:315381#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:305382// http://crbug.com/177916
5383#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
5384#else
5385#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
5386#endif // defined(OS_WIN)
5387TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:555388 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:345389
5390 int lower_bound = 0;
5391 int upper_bound = 1;
5392
5393 // Double the number of cookies until the response header limits are
5394 // exceeded.
5395 while (DoManyCookiesRequest(upper_bound)) {
5396 lower_bound = upper_bound;
5397 upper_bound *= 2;
5398 ASSERT_LT(upper_bound, 1000000);
5399 }
5400
pkasting6b68a162014-12-01 22:10:295401 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:345402 if (tolerance < 2)
5403 tolerance = 2;
5404
5405 // Perform a binary search to find the highest possible number of cookies,
5406 // within the desired tolerance.
5407 while (upper_bound - lower_bound >= tolerance) {
5408 int num_cookies = (lower_bound + upper_bound) / 2;
5409
5410 if (DoManyCookiesRequest(num_cookies))
5411 lower_bound = num_cookies;
5412 else
5413 upper_bound = num_cookies;
5414 }
5415 // Success: the test did not crash.
5416}
5417
[email protected]b89290212009-08-14 22:37:355418TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:555419 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115420
initial.commit586acc5fe2008-07-26 22:42:525421 TestDelegate d;
5422 {
Ryan Sleevib8449e02018-07-15 04:31:075423 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165424 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5425 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525426
[email protected]f7022f32014-08-21 16:32:195427 r->Start();
5428 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525429
Wez2a31b222018-06-07 22:07:155430 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525431
5432 EXPECT_EQ(1, d.response_started_count());
5433 EXPECT_FALSE(d.received_data_before_response());
5434 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555435 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375436 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555437 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375438 r->GetResponseRemoteEndpoint().port());
initial.commit586acc5fe2008-07-26 22:42:525439 }
[email protected]5d7b373e2009-09-02 07:19:035440}
5441
[email protected]79e1fd62013-06-20 06:50:045442TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555443 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045444
5445 TestDelegate d;
5446 {
tommycli59a63432015-11-06 00:10:555447 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075448 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165449 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045450
5451 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195452 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045453
[email protected]f7022f32014-08-21 16:32:195454 r->Start();
5455 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045456
Wez2a31b222018-06-07 22:07:155457 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:045458
5459 EXPECT_EQ(1, d.response_started_count());
5460 EXPECT_FALSE(d.received_data_before_response());
5461 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555462 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375463 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555464 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375465 r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:045466
5467 EXPECT_TRUE(d.have_full_request_headers());
5468 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5469 }
5470}
5471
[email protected]58e32bb2013-01-21 18:23:255472TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555473 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255474
5475 TestDelegate d;
5476 {
Ryan Sleevib8449e02018-07-15 04:31:075477 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165478 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5479 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255480
[email protected]f7022f32014-08-21 16:32:195481 r->Start();
5482 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255483
Wez2a31b222018-06-07 22:07:155484 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255485
5486 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195487 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255488 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5489
5490 EXPECT_EQ(1, d.response_started_count());
5491 EXPECT_FALSE(d.received_data_before_response());
5492 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555493 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375494 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555495 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375496 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:255497 }
5498}
5499
tommycli59a63432015-11-06 00:10:555500// TODO(svaldez): Update tests to use EmbeddedTestServer.
5501#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395502TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555503 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555504 base::FilePath(kTestFilePath));
5505
5506 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395507
5508 // Parameter that specifies the Content-Length field in the response:
5509 // C - Compressed length.
5510 // U - Uncompressed length.
5511 // L - Large length (larger than both C & U).
5512 // M - Medium length (between C & U).
5513 // S - Small length (smaller than both C & U).
5514 const char test_parameters[] = "CULMS";
Avi Drissman4365a4782018-12-28 19:26:245515 const int num_tests = base::size(test_parameters) - 1; // Skip NULL.
[email protected]aad63572011-05-24 20:14:395516 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445517 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395518 // S has too little data, but we seem to accept it.
5519 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375520 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395521
xunjielifb4da222016-07-14 18:38:595522 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:195523 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
xunjielifb4da222016-07-14 18:38:595524 file_path = file_path.Append(kTestFilePath);
5525 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5526 std::string expected_content;
5527 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5528
5529 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395530 TestDelegate d;
5531 {
tommycli59a63432015-11-06 00:10:555532 std::string test_file = base::StringPrintf(
5533 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395534
[email protected]ceefd7fd2012-11-29 00:36:245535 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095536 TestURLRequestContext context(true);
5537 context.set_network_delegate(&network_delegate);
5538 context.Init();
[email protected]87a09a92011-07-14 15:50:505539
rhalavatib7bd7c792017-04-27 05:25:165540 std::unique_ptr<URLRequest> r(
5541 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5542 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195543 r->Start();
5544 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395545
Wez2a31b222018-06-07 22:07:155546 d.RunUntilComplete();
[email protected]aad63572011-05-24 20:14:395547
5548 EXPECT_EQ(1, d.response_started_count());
5549 EXPECT_FALSE(d.received_data_before_response());
5550 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505551 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395552 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505553 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5554 << "\"";
xunjielifb4da222016-07-14 18:38:595555 if (test_parameters[i] == 'S') {
5556 // When content length is smaller than both compressed length and
5557 // uncompressed length, HttpStreamParser might not read the full
5558 // response body.
5559 continue;
5560 }
5561 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395562 } else {
maksim.sisovb53724b52016-09-16 05:30:505563 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395564 << " Parameter = \"" << test_file << "\"";
5565 }
5566 }
5567 }
5568}
tommycli59a63432015-11-06 00:10:555569#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395570
[email protected]58e32bb2013-01-21 18:23:255571TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555572 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255573
tommycli59a63432015-11-06 00:10:555574 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455575 GURL original_url =
tommycli59a63432015-11-06 00:10:555576 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255577 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075578 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165579 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195580 req->Start();
Wez2a31b222018-06-07 22:07:155581 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255582
5583 EXPECT_EQ(1, d.response_started_count());
5584 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195585 EXPECT_EQ(destination_url, req->url());
5586 EXPECT_EQ(original_url, req->original_url());
5587 ASSERT_EQ(2U, req->url_chain().size());
5588 EXPECT_EQ(original_url, req->url_chain()[0]);
5589 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255590
5591 LoadTimingInfo load_timing_info_before_redirect;
5592 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5593 &load_timing_info_before_redirect));
5594 TestLoadTimingNotReused(load_timing_info_before_redirect,
5595 CONNECT_TIMING_HAS_DNS_TIMES);
5596
5597 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195598 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255599 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5600
5601 // Check that a new socket was used on redirect, since the server does not
5602 // supposed keep-alive sockets, and that the times before the redirect are
5603 // before the ones recorded for the second request.
5604 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5605 load_timing_info.socket_log_id);
5606 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5607 load_timing_info.connect_timing.connect_start);
5608}
5609
[email protected]8f1ac082011-04-19 21:14:135610TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555611 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135612
tommycli59a63432015-11-06 00:10:555613 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455614 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555615 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5616 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5617 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135618 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075619 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165620 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195621 req->Start();
Wez2a31b222018-06-07 22:07:155622 d.RunUntilComplete();
[email protected]8f1ac082011-04-19 21:14:135623
5624 EXPECT_EQ(1, d.response_started_count());
5625 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195626 EXPECT_EQ(destination_url, req->url());
5627 EXPECT_EQ(original_url, req->original_url());
5628 ASSERT_EQ(3U, req->url_chain().size());
5629 EXPECT_EQ(original_url, req->url_chain()[0]);
5630 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5631 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135632}
5633
David Benjamina7fde612019-03-15 14:20:585634// This is a regression test for https://crbug.com/942073.
5635TEST_F(URLRequestTestHTTP, RedirectEscaping) {
5636 ASSERT_TRUE(http_test_server()->Start());
5637
5638 // Assemble the destination URL as a string so it is not escaped by GURL.
5639 GURL destination_base = http_test_server()->GetURL("/defaultresponse");
5640 // Add a URL fragment of U+2603 unescaped, U+2603 escaped, and then a UTF-8
5641 // encoding error.
5642 std::string destination_url =
5643 destination_base.spec() + "#\xE2\x98\x83_%E2%98%83_\xE0\xE0";
5644 // Redirect resolution should percent-escape bytes and preserve the UTF-8
5645 // error at the end.
5646 std::string destination_escaped =
5647 destination_base.spec() + "#%E2%98%83_%E2%98%83_%E0%E0";
5648 GURL original_url = http_test_server()->GetURL(
5649 "/server-redirect?" + EscapeQueryParamValue(destination_url, false));
5650 TestDelegate d;
5651 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
5652 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5653 req->Start();
5654 d.RunUntilComplete();
5655
5656 EXPECT_EQ(1, d.response_started_count());
5657 EXPECT_EQ(1, d.received_redirect_count());
5658 EXPECT_EQ(destination_escaped, req->url().spec());
5659 EXPECT_EQ(original_url, req->original_url());
5660 ASSERT_EQ(2U, req->url_chain().size());
5661 EXPECT_EQ(original_url, req->url_chain()[0]);
5662 EXPECT_EQ(destination_escaped, req->url_chain()[1].spec());
5663}
5664
[email protected]abe1c4a2013-10-25 19:28:515665// First and second pieces of information logged by delegates to URLRequests.
5666const char kFirstDelegateInfo[] = "Wonderful delegate";
5667const char kSecondDelegateInfo[] = "Exciting delegate";
5668
5669// Logs delegate information to a URLRequest. The first string is logged
5670// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5671// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5672// another asynchronous call is used to clear the delegate information
5673// before calling a callback. The object then deletes itself.
5674class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5675 public:
David Benjamind1f287bf2018-06-12 01:57:205676 using Callback = base::OnceCallback<void()>;
[email protected]abe1c4a2013-10-25 19:28:515677
5678 // Each time delegate information is added to the URLRequest, the resulting
5679 // load state is checked. The expected load state after each request is
5680 // passed in as an argument.
5681 static void Run(URLRequest* url_request,
5682 LoadState expected_first_load_state,
5683 LoadState expected_second_load_state,
5684 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205685 Callback callback) {
tzik38f920a2018-08-01 04:41:205686 // base::MakeRefCounted<AsyncDelegateLogger> is unavailable here, since the
5687 // constructor of AsyncDelegateLogger is private.
5688 auto logger = base::WrapRefCounted(new AsyncDelegateLogger(
David Benjamind1f287bf2018-06-12 01:57:205689 url_request, expected_first_load_state, expected_second_load_state,
tzik38f920a2018-08-01 04:41:205690 expected_third_load_state, std::move(callback)));
[email protected]abe1c4a2013-10-25 19:28:515691 logger->Start();
5692 }
5693
5694 // Checks that the log entries, starting with log_position, contain the
5695 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5696 // recorded. Returns the index of entry after the expected number of
5697 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465698 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515699 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515700 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5701 if (log_position + 3 >= entries.size()) {
5702 ADD_FAILURE() << "Not enough log entries";
5703 return entries.size();
5704 }
5705 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005706 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5707 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075708 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515709 &delegate_info));
5710 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5711
5712 ++log_position;
mikecirone8b85c432016-09-08 19:11:005713 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5714 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515715
5716 ++log_position;
mikecirone8b85c432016-09-08 19:11:005717 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5718 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075719 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515720 &delegate_info));
5721 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5722
5723 ++log_position;
mikecirone8b85c432016-09-08 19:11:005724 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5725 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515726
5727 return log_position + 1;
5728 }
5729
5730 private:
5731 friend class base::RefCounted<AsyncDelegateLogger>;
5732
5733 AsyncDelegateLogger(URLRequest* url_request,
5734 LoadState expected_first_load_state,
5735 LoadState expected_second_load_state,
5736 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205737 Callback callback)
[email protected]abe1c4a2013-10-25 19:28:515738 : url_request_(url_request),
5739 expected_first_load_state_(expected_first_load_state),
5740 expected_second_load_state_(expected_second_load_state),
5741 expected_third_load_state_(expected_third_load_state),
David Benjamind1f287bf2018-06-12 01:57:205742 callback_(std::move(callback)) {}
[email protected]abe1c4a2013-10-25 19:28:515743
Chris Watkins7a41d3552017-12-01 02:13:275744 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515745
5746 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535747 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515748 LoadStateWithParam load_state = url_request_->GetLoadState();
5749 EXPECT_EQ(expected_first_load_state_, load_state.state);
5750 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455751 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155752 FROM_HERE,
5753 base::BindOnce(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515754 }
5755
5756 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535757 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515758 LoadStateWithParam load_state = url_request_->GetLoadState();
5759 EXPECT_EQ(expected_second_load_state_, load_state.state);
5760 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5761 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5762 } else {
5763 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5764 }
skyostil4891b25b2015-06-11 11:43:455765 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155766 FROM_HERE, base::BindOnce(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515767 }
5768
5769 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535770 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515771 LoadStateWithParam load_state = url_request_->GetLoadState();
5772 EXPECT_EQ(expected_third_load_state_, load_state.state);
5773 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085774 EXPECT_EQ(base::string16(), load_state.param);
David Benjamind1f287bf2018-06-12 01:57:205775 std::move(callback_).Run();
[email protected]abe1c4a2013-10-25 19:28:515776 }
5777
5778 URLRequest* url_request_;
5779 const int expected_first_load_state_;
5780 const int expected_second_load_state_;
5781 const int expected_third_load_state_;
David Benjamind1f287bf2018-06-12 01:57:205782 Callback callback_;
[email protected]abe1c4a2013-10-25 19:28:515783
5784 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5785};
5786
5787// NetworkDelegate that logs delegate information before a request is started,
5788// before headers are sent, when headers are read, and when auth information
5789// is requested. Uses AsyncDelegateLogger.
5790class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5791 public:
Chris Watkins7a41d3552017-12-01 02:13:275792 AsyncLoggingNetworkDelegate() = default;
5793 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515794
5795 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205796 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205797 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:205798 GURL* new_url) override {
David Benjamind1f287bf2018-06-12 01:57:205799 // TestNetworkDelegate always completes synchronously.
5800 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
5801 request, base::NullCallback(), new_url));
5802 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515803 }
5804
ryansturm2343cb62016-06-15 01:09:005805 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205806 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:005807 HttpRequestHeaders* headers) override {
David Benjamind1f287bf2018-06-12 01:57:205808 // TestNetworkDelegate always completes synchronously.
5809 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
5810 request, base::NullCallback(), headers));
5811 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515812 }
5813
dchengb03027d2014-10-21 12:00:205814 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515815 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205816 CompletionOnceCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515817 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165818 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135819 GURL* allowed_unsafe_redirect_url) override {
David Benjamind1f287bf2018-06-12 01:57:205820 // TestNetworkDelegate always completes synchronously.
5821 CHECK_NE(ERR_IO_PENDING,
5822 TestNetworkDelegate::OnHeadersReceived(
5823 request, base::NullCallback(), original_response_headers,
5824 override_response_headers, allowed_unsafe_redirect_url));
5825 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515826 }
5827
dchengb03027d2014-10-21 12:00:205828 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515829 URLRequest* request,
5830 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:205831 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:135832 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515833 AsyncDelegateLogger::Run(
David Benjamind1f287bf2018-06-12 01:57:205834 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5835 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5836 base::BindOnce(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5837 std::move(callback), credentials));
[email protected]abe1c4a2013-10-25 19:28:515838 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5839 }
5840
5841 private:
David Benjamind1f287bf2018-06-12 01:57:205842 static int RunCallbackAsynchronously(URLRequest* request,
5843 CompletionOnceCallback callback) {
5844 AsyncDelegateLogger::Run(request, LOAD_STATE_WAITING_FOR_DELEGATE,
5845 LOAD_STATE_WAITING_FOR_DELEGATE,
5846 LOAD_STATE_WAITING_FOR_DELEGATE,
5847 base::BindOnce(std::move(callback), OK));
[email protected]abe1c4a2013-10-25 19:28:515848 return ERR_IO_PENDING;
5849 }
5850
David Benjamind1f287bf2018-06-12 01:57:205851 static void SetAuthAndResume(AuthCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515852 AuthCredentials* credentials) {
5853 *credentials = AuthCredentials(kUser, kSecret);
David Benjamind1f287bf2018-06-12 01:57:205854 std::move(callback).Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
[email protected]abe1c4a2013-10-25 19:28:515855 }
5856
5857 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5858};
5859
5860// URLRequest::Delegate that logs delegate information when the headers
5861// are received, when each read completes, and during redirects. Uses
5862// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5863//
5864// Inherits from TestDelegate to reuse the TestDelegate code to handle
5865// advancing to the next step in most cases, as well as cancellation.
5866class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5867 public:
5868 enum CancelStage {
5869 NO_CANCEL = 0,
5870 CANCEL_ON_RECEIVED_REDIRECT,
5871 CANCEL_ON_RESPONSE_STARTED,
5872 CANCEL_ON_READ_COMPLETED
5873 };
5874
5875 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5876 : cancel_stage_(cancel_stage) {
5877 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5878 set_cancel_in_received_redirect(true);
5879 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5880 set_cancel_in_response_started(true);
5881 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5882 set_cancel_in_received_data(true);
5883 }
Chris Watkins7a41d3552017-12-01 02:13:275884 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515885
5886 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205887 void OnReceivedRedirect(URLRequest* request,
5888 const RedirectInfo& redirect_info,
5889 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515890 *defer_redirect = true;
5891 AsyncDelegateLogger::Run(
5892 request,
5893 LOAD_STATE_WAITING_FOR_DELEGATE,
5894 LOAD_STATE_WAITING_FOR_DELEGATE,
5895 LOAD_STATE_WAITING_FOR_DELEGATE,
5896 base::Bind(
5897 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595898 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515899 }
5900
maksim.sisov0f4aa142016-09-05 05:55:285901 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515902 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285903 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5904 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5905 base::Bind(
5906 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5907 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515908 }
5909
dchengb03027d2014-10-21 12:00:205910 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515911 AsyncDelegateLogger::Run(
5912 request,
5913 LOAD_STATE_IDLE,
5914 LOAD_STATE_IDLE,
5915 LOAD_STATE_IDLE,
5916 base::Bind(
5917 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5918 base::Unretained(this), request, bytes_read));
5919 }
5920
5921 private:
5922 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595923 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515924 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595925 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515926 // FollowDeferredRedirect should not be called after cancellation.
5927 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5928 return;
Arthur Sonzognib8465ff72019-01-04 18:44:355929 if (!defer_redirect) {
5930 request->FollowDeferredRedirect(base::nullopt /* removed_headers */,
5931 base::nullopt /* modified_headers */);
5932 }
[email protected]abe1c4a2013-10-25 19:28:515933 }
5934
maksim.sisov0f4aa142016-09-05 05:55:285935 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515936 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285937 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515938 }
5939
5940 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5941 // The parent class continues the request.
5942 TestDelegate::OnReadCompleted(request, bytes_read);
5943 }
5944
5945 const CancelStage cancel_stage_;
5946
5947 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5948};
5949
5950// Tests handling of delegate info before a request starts.
5951TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555952 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515953
5954 TestDelegate request_delegate;
5955 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:355956 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:515957 context.set_net_log(&net_log_);
5958 context.Init();
5959
5960 {
rhalavatib7bd7c792017-04-27 05:25:165961 std::unique_ptr<URLRequest> r(context.CreateRequest(
5962 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5963 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195964 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515965 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085966 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515967
5968 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195969 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515970 LOAD_STATE_WAITING_FOR_DELEGATE,
5971 LOAD_STATE_WAITING_FOR_DELEGATE,
5972 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195973 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515974
Wez2a31b222018-06-07 22:07:155975 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515976
[email protected]f7022f32014-08-21 16:32:195977 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505978 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515979 }
5980
mmenke43758e62015-05-04 21:09:465981 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515982 net_log_.GetEntries(&entries);
5983 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005984 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515985
5986 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5987
5988 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005989 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5990 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515991}
5992
5993// Tests handling of delegate info from a network delegate.
5994TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555995 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515996
5997 TestDelegate request_delegate;
5998 AsyncLoggingNetworkDelegate network_delegate;
5999 TestURLRequestContext context(true);
6000 context.set_network_delegate(&network_delegate);
6001 context.set_net_log(&net_log_);
6002 context.Init();
6003
6004 {
rhalavatib7bd7c792017-04-27 05:25:166005 std::unique_ptr<URLRequest> r(context.CreateRequest(
6006 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
6007 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196008 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516009 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086010 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516011
[email protected]f7022f32014-08-21 16:32:196012 r->Start();
Wez2a31b222018-06-07 22:07:156013 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516014
[email protected]f7022f32014-08-21 16:32:196015 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506016 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516017 EXPECT_EQ(1, network_delegate.created_requests());
6018 EXPECT_EQ(0, network_delegate.destroyed_requests());
6019 }
6020 EXPECT_EQ(1, network_delegate.destroyed_requests());
6021
6022 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466023 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516024 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:156025 static const NetLogEventType kExpectedEvents[] = {
6026 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6027 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6028 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6029 };
6030 for (NetLogEventType event : kExpectedEvents) {
6031 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516032 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156033 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516034
6035 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6036 log_position + 1);
6037
6038 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156039 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006040 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516041 }
6042
mikecirone8b85c432016-09-08 19:11:006043 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6044 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516045}
6046
6047// Tests handling of delegate info from a network delegate in the case of an
6048// HTTP redirect.
6049TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:556050 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516051
6052 TestDelegate request_delegate;
6053 AsyncLoggingNetworkDelegate network_delegate;
6054 TestURLRequestContext context(true);
6055 context.set_network_delegate(&network_delegate);
6056 context.set_net_log(&net_log_);
6057 context.Init();
6058
6059 {
danakj8522a25b2016-04-16 00:17:366060 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556061 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166062 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196063 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516064 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086065 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516066
[email protected]f7022f32014-08-21 16:32:196067 r->Start();
Wez2a31b222018-06-07 22:07:156068 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516069
[email protected]f7022f32014-08-21 16:32:196070 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506071 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516072 EXPECT_EQ(2, network_delegate.created_requests());
6073 EXPECT_EQ(0, network_delegate.destroyed_requests());
6074 }
6075 EXPECT_EQ(1, network_delegate.destroyed_requests());
6076
6077 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466078 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516079 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:156080 static const NetLogEventType kExpectedEvents[] = {
6081 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6082 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6083 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6084 };
6085 for (NetLogEventType event : kExpectedEvents) {
6086 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516087 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156088 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516089
David Benjamin9776ca22018-06-13 00:00:156090 log_position =
6091 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516092
6093 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156094 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006095 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516096 }
6097
6098 // The URLRequest::Delegate then gets informed about the redirect.
6099 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156100 entries, log_position + 1,
6101 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
mikecirone8b85c432016-09-08 19:11:006102 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516103
6104 // The NetworkDelegate logged information in the same three events as before.
David Benjamin9776ca22018-06-13 00:00:156105 for (NetLogEventType event : kExpectedEvents) {
6106 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516107 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156108 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516109
6110 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6111 log_position + 1);
6112
6113 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156114 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006115 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516116 }
6117
mikecirone8b85c432016-09-08 19:11:006118 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6119 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516120}
6121
6122// Tests handling of delegate info from a network delegate in the case of HTTP
6123// AUTH.
6124TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:556125 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516126
6127 TestDelegate request_delegate;
6128 AsyncLoggingNetworkDelegate network_delegate;
6129 TestURLRequestContext context(true);
6130 context.set_network_delegate(&network_delegate);
6131 context.set_net_log(&net_log_);
6132 context.Init();
6133
6134 {
rhalavatib7bd7c792017-04-27 05:25:166135 std::unique_ptr<URLRequest> r(context.CreateRequest(
6136 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
6137 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196138 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516139 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086140 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516141
[email protected]f7022f32014-08-21 16:32:196142 r->Start();
Wez2a31b222018-06-07 22:07:156143 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516144
[email protected]f7022f32014-08-21 16:32:196145 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506146 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516147 EXPECT_EQ(1, network_delegate.created_requests());
6148 EXPECT_EQ(0, network_delegate.destroyed_requests());
6149 }
6150 EXPECT_EQ(1, network_delegate.destroyed_requests());
6151
6152 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466153 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516154 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:156155 static const NetLogEventType kExpectedEvents[] = {
6156 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6157 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6158 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6159 NetLogEventType::NETWORK_DELEGATE_AUTH_REQUIRED,
6160 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6161 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6162 };
6163 for (NetLogEventType event : kExpectedEvents) {
6164 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516165 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156166 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516167
David Benjamin9776ca22018-06-13 00:00:156168 log_position =
6169 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516170
6171 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156172 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006173 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516174 }
6175
mikecirone8b85c432016-09-08 19:11:006176 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6177 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516178}
6179
tommycli59a63432015-11-06 00:10:556180// TODO(svaldez): Update tests to use EmbeddedTestServer.
6181#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516182// Tests handling of delegate info from a URLRequest::Delegate.
6183TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:556184 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:556185 base::FilePath(kTestFilePath));
6186
6187 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:516188
6189 AsyncLoggingUrlRequestDelegate request_delegate(
6190 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6191 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356192 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516193 context.set_net_log(&net_log_);
6194 context.Init();
6195
6196 {
6197 // A chunked response with delays between chunks is used to make sure that
6198 // attempts by the URLRequest delegate to log information while reading the
6199 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:486200 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:516201 // that it occurs.
danakj8522a25b2016-04-16 00:17:366202 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556203 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166204 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196205 LoadStateWithParam load_state = r->GetLoadState();
6206 r->Start();
Wez2a31b222018-06-07 22:07:156207 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516208
[email protected]f7022f32014-08-21 16:32:196209 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506210 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516211 }
6212
mmenke43758e62015-05-04 21:09:466213 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516214 net_log_.GetEntries(&entries);
6215
[email protected]1826a402014-01-08 15:40:486216 size_t log_position = 0;
6217
[email protected]abe1c4a2013-10-25 19:28:516218 // The delegate info should only have been logged on header complete. Other
6219 // times it should silently be ignored.
David Benjamin9776ca22018-06-13 00:00:156220 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
6221 entries, 0, NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST));
mikecirone8b85c432016-09-08 19:11:006222 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156223 entries, log_position + 1,
6224 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
mikecirone8b85c432016-09-08 19:11:006225 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516226
David Benjamin9776ca22018-06-13 00:00:156227 log_position =
6228 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516229
6230 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156231 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6232 entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006233 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516234
mikecirone8b85c432016-09-08 19:11:006235 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6236 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516237 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
David Benjamin9776ca22018-06-13 00:00:156238 entries, log_position + 1,
6239 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED));
[email protected]abe1c4a2013-10-25 19:28:516240}
tommycli59a63432015-11-06 00:10:556241#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516242
6243// Tests handling of delegate info from a URLRequest::Delegate in the case of
6244// an HTTP redirect.
6245TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:556246 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516247
6248 AsyncLoggingUrlRequestDelegate request_delegate(
6249 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6250 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356251 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516252 context.set_net_log(&net_log_);
6253 context.Init();
6254
6255 {
danakj8522a25b2016-04-16 00:17:366256 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556257 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166258 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196259 LoadStateWithParam load_state = r->GetLoadState();
6260 r->Start();
Wez2a31b222018-06-07 22:07:156261 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516262
[email protected]f7022f32014-08-21 16:32:196263 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506264 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516265 }
6266
mmenke43758e62015-05-04 21:09:466267 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516268 net_log_.GetEntries(&entries);
6269
6270 // Delegate info should only have been logged in OnReceivedRedirect and
6271 // OnResponseStarted.
6272 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156273 static const NetLogEventType kExpectedEvents[] = {
6274 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6275 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6276 };
6277 for (NetLogEventType event : kExpectedEvents) {
6278 SCOPED_TRACE(NetLog::EventTypeToString(event));
6279 log_position = ExpectLogContainsSomewhereAfter(entries, log_position, event,
6280 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516281
David Benjamin9776ca22018-06-13 00:00:156282 log_position =
6283 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516284
6285 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156286 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006287 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516288 }
6289
mikecirone8b85c432016-09-08 19:11:006290 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6291 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516292}
6293
6294// Tests handling of delegate info from a URLRequest::Delegate in the case of
6295// an HTTP redirect, with cancellation at various points.
6296TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:556297 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516298
6299 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
6300 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
6301 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
6302 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
6303 };
6304
David Benjamin9776ca22018-06-13 00:00:156305 for (auto cancel_stage : kCancelStages) {
6306 AsyncLoggingUrlRequestDelegate request_delegate(cancel_stage);
vishal.b62985ca92015-04-17 08:45:516307 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046308 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356309 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516310 context.set_net_log(&net_log);
6311 context.Init();
6312
6313 {
danakj8522a25b2016-04-16 00:17:366314 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556315 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166316 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196317 LoadStateWithParam load_state = r->GetLoadState();
6318 r->Start();
Wez2a31b222018-06-07 22:07:156319 request_delegate.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506320 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
Wez2a31b222018-06-07 22:07:156321
6322 // Spin the message loop to run AsyncDelegateLogger task(s) posted after
6323 // the |request_delegate| completion task.
6324 base::RunLoop().RunUntilIdle();
[email protected]abe1c4a2013-10-25 19:28:516325 }
6326
mmenke43758e62015-05-04 21:09:466327 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516328 net_log.GetEntries(&entries);
6329
6330 // Delegate info is always logged in both OnReceivedRedirect and
6331 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6332 // OnResponseStarted delegate call is after cancellation, but logging is
6333 // still currently supported in that call.
6334 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156335 static const NetLogEventType kExpectedEvents[] = {
6336 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6337 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6338 };
6339 for (NetLogEventType event : kExpectedEvents) {
6340 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516341 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156342 entries, log_position, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516343
David Benjamin9776ca22018-06-13 00:00:156344 log_position =
6345 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516346
6347 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156348 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006349 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516350 }
6351
mikecirone8b85c432016-09-08 19:11:006352 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6353 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516354 }
6355}
6356
[email protected]847c0fa92012-11-06 16:37:426357namespace {
6358
6359const char kExtraHeader[] = "Allow-Snafu";
6360const char kExtraValue[] = "fubar";
6361
6362class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206363 void OnReceivedRedirect(URLRequest* request,
6364 const RedirectInfo& redirect_info,
6365 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596366 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426367 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6368 }
6369};
6370
6371} // namespace
6372
6373TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556374 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426375
tommycli59a63432015-11-06 00:10:556376 GURL destination_url =
6377 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6378 GURL original_url =
6379 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426380 RedirectWithAdditionalHeadersDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076381 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166382 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196383 req->Start();
Wez2a31b222018-06-07 22:07:156384 d.RunUntilComplete();
[email protected]847c0fa92012-11-06 16:37:426385
6386 std::string value;
[email protected]f7022f32014-08-21 16:32:196387 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426388 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6389 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196390 EXPECT_FALSE(req->is_pending());
6391 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426392 EXPECT_EQ(kExtraValue, d.data_received());
6393}
6394
[email protected]251a1b92012-11-13 11:01:096395namespace {
6396
6397const char kExtraHeaderToRemove[] = "To-Be-Removed";
6398
6399class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206400 void OnReceivedRedirect(URLRequest* request,
6401 const RedirectInfo& redirect_info,
6402 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596403 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096404 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6405 }
6406};
6407
6408} // namespace
6409
6410TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556411 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096412
tommycli59a63432015-11-06 00:10:556413 GURL destination_url = http_test_server()->GetURL(
6414 "/echoheader?" + std::string(kExtraHeaderToRemove));
6415 GURL original_url =
6416 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096417 RedirectWithHeaderRemovalDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076418 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166419 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196420 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6421 req->Start();
Wez2a31b222018-06-07 22:07:156422 d.RunUntilComplete();
[email protected]251a1b92012-11-13 11:01:096423
6424 std::string value;
[email protected]f7022f32014-08-21 16:32:196425 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096426 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196427 EXPECT_FALSE(req->is_pending());
6428 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096429 EXPECT_EQ("None", d.data_received());
6430}
6431
mmenke94f1bd92016-12-07 21:13:056432TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446433 TestDelegate d;
6434 {
Ryan Sleevib8449e02018-07-15 04:31:076435 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166436 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6437 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446438
[email protected]f7022f32014-08-21 16:32:196439 r->Start();
6440 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446441
[email protected]f7022f32014-08-21 16:32:196442 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446443
Wez2a31b222018-06-07 22:07:156444 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446445
6446 // We expect to receive OnResponseStarted even though the request has been
6447 // cancelled.
6448 EXPECT_EQ(1, d.response_started_count());
6449 EXPECT_EQ(0, d.bytes_received());
6450 EXPECT_FALSE(d.received_data_before_response());
6451 }
6452}
6453
mmenke94f1bd92016-12-07 21:13:056454TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556455 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446456
6457 TestDelegate d;
6458 {
Ryan Sleevib8449e02018-07-15 04:31:076459 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166460 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6461 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446462
6463 d.set_cancel_in_response_started(true);
6464
[email protected]f7022f32014-08-21 16:32:196465 r->Start();
6466 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446467
Wez2a31b222018-06-07 22:07:156468 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446469
6470 EXPECT_EQ(1, d.response_started_count());
6471 EXPECT_EQ(0, d.bytes_received());
6472 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506473 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446474 }
6475}
6476
mmenke94f1bd92016-12-07 21:13:056477TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556478 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446479
6480 TestDelegate d;
6481 {
Ryan Sleevib8449e02018-07-15 04:31:076482 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166483 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6484 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056485
6486 d.set_cancel_in_received_data(true);
6487
6488 r->Start();
6489 EXPECT_TRUE(r->is_pending());
6490
Wez2a31b222018-06-07 22:07:156491 d.RunUntilComplete();
mmenke94f1bd92016-12-07 21:13:056492
6493 EXPECT_EQ(1, d.response_started_count());
6494 EXPECT_NE(0, d.received_bytes_count());
6495 EXPECT_FALSE(d.received_data_before_response());
6496 EXPECT_EQ(ERR_ABORTED, d.request_status());
6497 }
6498}
6499
6500TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6501 ASSERT_TRUE(http_test_server()->Start());
6502
6503 TestDelegate d;
6504 {
6505 // This returns an empty response (With headers).
Ryan Sleevib8449e02018-07-15 04:31:076506 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166507 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6508 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446509
6510 d.set_cancel_in_received_data(true);
6511
[email protected]f7022f32014-08-21 16:32:196512 r->Start();
6513 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446514
Wez2a31b222018-06-07 22:07:156515 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446516
6517 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056518 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446519 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506520 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446521 }
6522}
6523
mmenke94f1bd92016-12-07 21:13:056524TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556525 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446526
6527 TestDelegate d;
6528 {
Ryan Sleevib8449e02018-07-15 04:31:076529 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166530 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6531 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446532
[email protected]f7022f32014-08-21 16:32:196533 r->Start();
6534 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446535
6536 // The request will be implicitly canceled when it is destroyed. The
6537 // test delegate must not post a quit message when this happens because
6538 // this test doesn't actually have a message loop. The quit message would
6539 // get put on this thread's message queue and the next test would exit
6540 // early, causing problems.
Wez0e717112018-06-18 23:09:226541 d.set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:446542 }
6543 // expect things to just cleanup properly.
6544
kimwjdalsl2bb4ff02015-12-16 22:06:026545 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446546 // message loop
6547 EXPECT_FALSE(d.received_data_before_response());
6548 EXPECT_EQ(0, d.bytes_received());
6549}
6550
mmenke94f1bd92016-12-07 21:13:056551TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556552 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446553
6554 // populate cache
6555 {
6556 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076557 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166558 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6559 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196560 r->Start();
Wez2a31b222018-06-07 22:07:156561 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506562 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446563 }
6564
6565 // cancel read from cache (see bug 990242)
6566 {
6567 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076568 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166569 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6570 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196571 r->Start();
6572 r->Cancel();
Wez2a31b222018-06-07 22:07:156573 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446574
maksim.sisovb53724b52016-09-16 05:30:506575 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446576 EXPECT_EQ(1, d.response_started_count());
6577 EXPECT_EQ(0, d.bytes_received());
6578 EXPECT_FALSE(d.received_data_before_response());
6579 }
6580}
6581
6582TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556583 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446584 HTTPUploadDataOperationTest("POST");
6585}
6586
6587TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556588 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446589 HTTPUploadDataOperationTest("PUT");
6590}
6591
6592TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556593 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446594
6595 TestDelegate d;
6596 {
Ryan Sleevib8449e02018-07-15 04:31:076597 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166598 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6599 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196600 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446601
[email protected]f7022f32014-08-21 16:32:196602 r->Start();
6603 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446604
Wez2a31b222018-06-07 22:07:156605 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446606
maksim.sisovb53724b52016-09-16 05:30:506607 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6608 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446609
6610 EXPECT_FALSE(d.received_data_before_response());
6611 EXPECT_TRUE(d.data_received().empty());
6612 }
6613}
6614
6615TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556616 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446617
6618 TestDelegate d;
6619 {
Ryan Sleevib8449e02018-07-15 04:31:076620 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166621 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6622 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196623 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446624
[email protected]6cdfd7f2013-02-08 20:40:156625 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196626 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026627 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446628
danakj8522a25b2016-04-16 00:17:366629 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446630
[email protected]6cdfd7f2013-02-08 20:40:156631 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196632 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476633 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446634 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196635 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146636 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076637 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046638 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6639 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446640
[email protected]f7022f32014-08-21 16:32:196641 r->Start();
6642 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446643
Wez2a31b222018-06-07 22:07:156644 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446645
avibf0746c2015-12-09 19:53:146646 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296647 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6648 ASSERT_LE(size64, std::numeric_limits<int>::max());
6649 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366650 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446651
[email protected]7600d0b2013-12-08 21:43:306652 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446653
maksim.sisovb53724b52016-09-16 05:30:506654 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6655 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446656
6657 EXPECT_FALSE(d.received_data_before_response());
6658
[email protected]329b68b2012-11-14 17:54:276659 EXPECT_EQ(size, d.bytes_received());
6660 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446661 }
6662}
6663
[email protected]999dd8c2013-11-12 06:45:546664TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556665 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546666
6667 TestDelegate d;
6668 {
Ryan Sleevib8449e02018-07-15 04:31:076669 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166670 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6671 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196672 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546673
danakj8522a25b2016-04-16 00:17:366674 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546675
Jeremy Roman0579ed62017-08-29 15:56:196676 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456677 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546678 base::FilePath(FILE_PATH_LITERAL(
6679 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076680 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046681 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6682 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546683
[email protected]f7022f32014-08-21 16:32:196684 r->Start();
6685 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546686
Wez2a31b222018-06-07 22:07:156687 d.RunUntilComplete();
[email protected]999dd8c2013-11-12 06:45:546688
[email protected]999dd8c2013-11-12 06:45:546689 EXPECT_TRUE(d.request_failed());
6690 EXPECT_FALSE(d.received_data_before_response());
6691 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506692 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546693 }
6694}
6695
mmenke56b0cbb912016-03-28 21:34:536696namespace {
6697
6698// Adds a standard set of data to an upload for chunked upload integration
6699// tests.
6700void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6701 writer->AppendData("a", 1, false);
6702 writer->AppendData("bcd", 3, false);
6703 writer->AppendData("this is a longer chunk than before.", 35, false);
6704 writer->AppendData("\r\n\r\n", 4, false);
6705 writer->AppendData("0", 1, false);
6706 writer->AppendData("2323", 4, true);
6707}
6708
6709// Checks that the upload data added in AddChunksToUpload() was echoed back from
6710// the server.
6711void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6712 // This should match the chunks sent by AddChunksToUpload().
6713 const std::string expected_data =
6714 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6715
maksim.sisovb53724b52016-09-16 05:30:506716 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6717 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536718
6719 EXPECT_FALSE(d->received_data_before_response());
6720
6721 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6722 EXPECT_EQ(expected_data, d->data_received());
6723}
6724
6725} // namespace
6726
[email protected]316c1e5e2012-09-12 15:17:446727TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556728 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446729
6730 TestDelegate d;
6731 {
Ryan Sleevib8449e02018-07-15 04:31:076732 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166733 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6734 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366735 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536736 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366737 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536738 upload_data_stream->CreateWriter();
6739 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196740 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536741 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196742 r->Start();
6743 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446744
Wez2a31b222018-06-07 22:07:156745 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446746
[email protected]f7022f32014-08-21 16:32:196747 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446748 }
6749}
6750
[email protected]329b68b2012-11-14 17:54:276751TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556752 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276753
6754 TestDelegate d;
6755 {
Ryan Sleevib8449e02018-07-15 04:31:076756 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166757 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6758 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366759 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536760 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366761 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536762 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046763 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196764 r->set_method("POST");
6765 r->Start();
6766 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536767 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156768 d.RunUntilComplete();
[email protected]329b68b2012-11-14 17:54:276769
[email protected]f7022f32014-08-21 16:32:196770 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276771 }
6772}
6773
Asanka Herathf05753e2018-08-16 17:38:206774TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556775 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446776
6777 TestDelegate d;
6778 {
Ryan Sleevib8449e02018-07-15 04:31:076779 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166780 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6781 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366782 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536783 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366784 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536785 upload_data_stream->CreateWriter();
6786 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196787 r->set_method("POST");
6788 r->Start();
6789 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446790
Asanka Herathf05753e2018-08-16 17:38:206791 // Pump messages until we start sending headers..
[email protected]255620da2013-08-19 13:14:296792 base::RunLoop().RunUntilIdle();
Asanka Herathf05753e2018-08-16 17:38:206793
6794 // And now wait for completion.
6795 base::RunLoop run_loop;
6796 d.set_on_complete(run_loop.QuitClosure());
mmenke56b0cbb912016-03-28 21:34:536797 AddDataToUpload(writer.get());
Asanka Herathf05753e2018-08-16 17:38:206798 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:446799
[email protected]f7022f32014-08-21 16:32:196800 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446801 }
6802}
6803
6804TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556805 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446806
6807 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076808 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166809 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6810 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196811 req->Start();
Wez2a31b222018-06-07 22:07:156812 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446813
[email protected]f7022f32014-08-21 16:32:196814 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446815
6816 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196817 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446818
6819 std::string header;
6820 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6821 EXPECT_EQ("private", header);
6822
6823 header.clear();
6824 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6825 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6826
6827 // The response has two "X-Multiple-Entries" headers.
6828 // This verfies our output has them concatenated together.
6829 header.clear();
6830 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6831 EXPECT_EQ("a, b", header);
6832}
6833
tommycli59a63432015-11-06 00:10:556834// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6835// security state. (see http://crbug.com/550977).
6836#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466837TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556838 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6839 https_test_server.SetSSLConfig(
6840 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6841 https_test_server.ServeFilesFromSourceDirectory(
6842 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466843 ASSERT_TRUE(https_test_server.Start());
6844
tommycli59a63432015-11-06 00:10:556845 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466846 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076847 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166848 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6849 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196850 request->Start();
Wez2a31b222018-06-07 22:07:156851 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466852
6853 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076854 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406855 TransportSecurityState::STSState sts_state;
6856 TransportSecurityState::PKPState pkp_state;
6857 EXPECT_TRUE(
6858 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6859 EXPECT_FALSE(
6860 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6861 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6862 sts_state.upgrade_mode);
6863 EXPECT_TRUE(sts_state.include_subdomains);
6864 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036865#if defined(OS_ANDROID)
6866 // Android's CertVerifyProc does not (yet) handle pins.
6867#else
martijnc0d6b622015-06-30 19:14:406868 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036869#endif
[email protected]37fd55fb2013-06-29 13:13:276870}
6871
estarka5da76702015-04-09 04:00:166872TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556873 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6874 https_test_server.ServeFilesFromSourceDirectory(
6875 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166876 ASSERT_TRUE(https_test_server.Start());
6877 // Make sure this test fails if the test server is changed to not
6878 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556879 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6880 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166881
6882 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076883 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166884 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6885 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166886 request->Start();
Wez2a31b222018-06-07 22:07:156887 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:166888 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076889 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406890 TransportSecurityState::STSState sts_state;
6891 EXPECT_FALSE(
6892 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166893}
6894
estark06e0dac2015-08-07 21:56:016895namespace {
Martijn Croonenb1383da2017-10-11 11:56:356896const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
Matt Mueller230996f12018-10-22 19:39:446897const char kPKPReportUri[] = "http://report-uri.preloaded.test/pkp";
6898const char kPKPHost[] = "with-report-uri-pkp.preloaded.test";
estark06e0dac2015-08-07 21:56:016899} // namespace
6900
Matt Mueller230996f12018-10-22 19:39:446901// Tests that reports get sent on PKP violations when a report-uri is set.
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516902TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
Matt Mueller230996f12018-10-22 19:39:446903 GURL report_uri(kPKPReportUri);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516904 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6905 https_test_server.SetSSLConfig(
6906 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6907 https_test_server.ServeFilesFromSourceDirectory(
6908 base::FilePath(kTestFilePath));
6909 ASSERT_TRUE(https_test_server.Start());
6910
Matt Mueller230996f12018-10-22 19:39:446911 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016912
6913 // Set up a pin for |test_server_hostname|.
6914 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446915 security_state.EnableStaticPinsForTesting();
6916 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016917
6918 MockCertificateReportSender mock_report_sender;
6919 security_state.SetReportSender(&mock_report_sender);
6920
6921 // Set up a MockCertVerifier to trigger a violation of the previously
6922 // set pin.
6923 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6924 ASSERT_TRUE(cert);
6925
6926 MockCertVerifier cert_verifier;
6927 CertVerifyResult verify_result;
6928 verify_result.verified_cert = cert;
6929 verify_result.is_issued_by_known_root = true;
6930 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446931 ASSERT_TRUE(
6932 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016933 verify_result.public_key_hashes.push_back(hash3);
6934 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6935
6936 TestNetworkDelegate network_delegate;
6937 TestURLRequestContext context(true);
6938 context.set_transport_security_state(&security_state);
6939 context.set_network_delegate(&network_delegate);
6940 context.set_cert_verifier(&cert_verifier);
6941 context.Init();
6942
6943 // Now send a request to trigger the violation.
6944 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366945 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446946 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166947 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016948 violating_request->Start();
Wez2a31b222018-06-07 22:07:156949 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016950
6951 // Check that a report was sent.
6952 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6953 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446954 EXPECT_EQ("application/json; charset=utf-8",
6955 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366956 std::unique_ptr<base::Value> value(
Lei Zhanga8b4c5fb2019-02-16 03:02:036957 base::JSONReader::ReadDeprecated(mock_report_sender.latest_report()));
estark06e0dac2015-08-07 21:56:016958 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086959 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016960 base::DictionaryValue* report_dict;
6961 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6962 std::string report_hostname;
6963 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6964 EXPECT_EQ(test_server_hostname, report_hostname);
6965}
6966
Matt Mueller230996f12018-10-22 19:39:446967// Tests that reports do not get sent on requests to static pkp hosts that
6968// don't have pin violations.
6969TEST_F(URLRequestTestHTTP, ProcessPKPWithNoViolation) {
tommycli59a63432015-11-06 00:10:556970 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6971 https_test_server.SetSSLConfig(
6972 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6973 https_test_server.ServeFilesFromSourceDirectory(
6974 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016975 ASSERT_TRUE(https_test_server.Start());
6976
Matt Mueller230996f12018-10-22 19:39:446977 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016978
6979 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446980 security_state.EnableStaticPinsForTesting();
6981 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016982 MockCertificateReportSender mock_report_sender;
6983 security_state.SetReportSender(&mock_report_sender);
6984
Matt Mueller230996f12018-10-22 19:39:446985 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6986 ASSERT_TRUE(cert);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516987 MockCertVerifier mock_cert_verifier;
Matt Mueller230996f12018-10-22 19:39:446988 CertVerifyResult verify_result;
6989 verify_result.verified_cert = cert;
6990 verify_result.is_issued_by_known_root = true;
6991 HashValue hash;
6992 // The expected value of GoodPin1 used by |test_default::kHSTSSource|.
6993 ASSERT_TRUE(
6994 hash.FromString("sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY="));
6995 verify_result.public_key_hashes.push_back(hash);
6996 mock_cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6997
6998 TestNetworkDelegate network_delegate;
estark06e0dac2015-08-07 21:56:016999 TestURLRequestContext context(true);
7000 context.set_transport_security_state(&security_state);
7001 context.set_network_delegate(&network_delegate);
7002 context.set_cert_verifier(&mock_cert_verifier);
estark06e0dac2015-08-07 21:56:017003 context.Init();
7004
7005 // Now send a request that does not trigger the violation.
7006 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367007 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:447008 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:167009 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:017010 request->Start();
Wez2a31b222018-06-07 22:07:157011 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:017012
Matt Mueller230996f12018-10-22 19:39:447013 // Check that the request succeeded, a report was not sent and the pkp was
7014 // not bypassed.
7015 EXPECT_EQ(OK, d.request_status());
estark06e0dac2015-08-07 21:56:017016 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
7017 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
Matt Mueller230996f12018-10-22 19:39:447018 TransportSecurityState::STSState sts_state;
martijnc0d6b622015-06-30 19:14:407019 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:447020 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
7021 &sts_state, &pkp_state));
7022 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
7023 EXPECT_FALSE(request->ssl_info().pkp_bypassed);
estarka5da76702015-04-09 04:00:167024}
7025
dadriandf302c42016-06-10 18:48:597026TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
7027 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7028 https_test_server.SetSSLConfig(
7029 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7030 https_test_server.ServeFilesFromSourceDirectory(
7031 base::FilePath(kTestFilePath));
7032 ASSERT_TRUE(https_test_server.Start());
7033
7034 // Set up a MockCertVerifier to be a local root that violates the pin
7035 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7036 ASSERT_TRUE(cert);
7037
7038 MockCertVerifier cert_verifier;
7039 CertVerifyResult verify_result;
7040 verify_result.verified_cert = cert;
7041 verify_result.is_issued_by_known_root = false;
7042 HashValue hash;
7043 ASSERT_TRUE(
7044 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
7045 verify_result.public_key_hashes.push_back(hash);
7046 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
dadriandf302c42016-06-10 18:48:597047
Matt Mueller230996f12018-10-22 19:39:447048 std::string test_server_hostname = kPKPHost;
dadriandf302c42016-06-10 18:48:597049
Matt Mueller230996f12018-10-22 19:39:447050 // Set up PKP
dadriandf302c42016-06-10 18:48:597051 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:447052 security_state.EnableStaticPinsForTesting();
7053 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7054 MockCertificateReportSender mock_report_sender;
7055 security_state.SetReportSender(&mock_report_sender);
dadriandf302c42016-06-10 18:48:597056
7057 TestNetworkDelegate network_delegate;
7058 TestURLRequestContext context(true);
7059 context.set_transport_security_state(&security_state);
7060 context.set_network_delegate(&network_delegate);
7061 context.set_cert_verifier(&cert_verifier);
7062 context.Init();
7063
7064 TestDelegate d;
7065 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:447066 https_test_server.GetURL(test_server_hostname, "/simple.html"),
7067 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:597068 request->Start();
Wez2a31b222018-06-07 22:07:157069 d.RunUntilComplete();
dadriandf302c42016-06-10 18:48:597070
Matt Mueller230996f12018-10-22 19:39:447071 // Check that the request succeeded, a report was not sent and the PKP was
7072 // bypassed.
7073 EXPECT_EQ(OK, d.request_status());
7074 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
7075 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
7076 TransportSecurityState::STSState sts_state;
dadriandf302c42016-06-10 18:48:597077 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:447078 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
7079 &sts_state, &pkp_state));
7080 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
dadriandf302c42016-06-10 18:48:597081 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
7082}
7083
[email protected]242d8562012-10-30 21:20:467084TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:557085 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7086 https_test_server.SetSSLConfig(
7087 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7088 https_test_server.ServeFilesFromSourceDirectory(
7089 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:467090 ASSERT_TRUE(https_test_server.Start());
7091
tommycli59a63432015-11-06 00:10:557092 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167093
[email protected]242d8562012-10-30 21:20:467094 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077095 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557096 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167097 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197098 request->Start();
Wez2a31b222018-06-07 22:07:157099 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:467100
7101 // We should have set parameters from the first header, not the second.
7102 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:077103 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:407104 TransportSecurityState::STSState sts_state;
7105 EXPECT_TRUE(
7106 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7107 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7108 sts_state.upgrade_mode);
7109 EXPECT_FALSE(sts_state.include_subdomains);
7110 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:467111}
7112
estark1614475f2016-03-10 03:46:477113// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
7114// called.
7115class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
7116 public:
7117 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:277118 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:477119
7120 void OnExpectCTFailed(const HostPortPair& host_port_pair,
7121 const GURL& report_uri,
estarkae028b462017-06-20 23:25:017122 base::Time expiration,
estarkbf1b52962017-05-05 17:05:257123 const X509Certificate* validated_certificate_chain,
7124 const X509Certificate* served_certificate_chain,
7125 const SignedCertificateTimestampAndStatusList&
7126 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:477127 num_failures_++;
7128 }
7129
7130 uint32_t num_failures() { return num_failures_; }
7131
7132 private:
7133 uint32_t num_failures_;
7134};
7135
Emily Stark627238f2017-11-29 03:29:547136// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:477137// for every certificate.
7138class MockCTPolicyEnforcer : public CTPolicyEnforcer {
7139 public:
7140 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:547141 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:277142 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:477143
Emily Stark627238f2017-11-29 03:29:547144 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:477145 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:237146 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:207147 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:477148 return default_result_;
7149 }
7150
Emily Stark627238f2017-11-29 03:29:547151 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:477152 default_result_ = default_result;
7153 }
7154
7155 private:
Emily Stark627238f2017-11-29 03:29:547156 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:477157};
7158
Emily Stark4cfecf072017-08-08 01:05:517159// Tests that Expect CT headers for the preload list are processed correctly.
7160TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:357161 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7162
estark1614475f2016-03-10 03:46:477163 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7164 https_test_server.SetSSLConfig(
7165 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7166 https_test_server.ServeFilesFromSourceDirectory(
7167 base::FilePath(kTestFilePath));
7168 ASSERT_TRUE(https_test_server.Start());
7169
7170 MockExpectCTReporter reporter;
7171 TransportSecurityState transport_security_state;
7172 transport_security_state.enable_static_expect_ct_ = true;
7173 transport_security_state.SetExpectCTReporter(&reporter);
7174
7175 // Set up a MockCertVerifier to accept the certificate that the server sends.
7176 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7177 ASSERT_TRUE(cert);
7178 MockCertVerifier cert_verifier;
7179 CertVerifyResult verify_result;
7180 verify_result.verified_cert = cert;
7181 verify_result.is_issued_by_known_root = true;
7182 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7183
rsleevi22cae1672016-12-28 01:53:367184 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
7185 // CT violation.
7186 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:477187 MockCTPolicyEnforcer ct_policy_enforcer;
7188 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547189 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:477190
7191 TestNetworkDelegate network_delegate;
7192 // Use a MockHostResolver (which by default maps all hosts to
7193 // 127.0.0.1) so that the request can be sent to a site on the Expect
7194 // CT preload list.
7195 MockHostResolver host_resolver;
7196 TestURLRequestContext context(true);
7197 context.set_host_resolver(&host_resolver);
7198 context.set_transport_security_state(&transport_security_state);
7199 context.set_network_delegate(&network_delegate);
7200 context.set_cert_verifier(&cert_verifier);
7201 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:467202 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:477203 context.Init();
7204
7205 // Now send a request to trigger the violation.
7206 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:517207 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:477208 GURL::Replacements replace_host;
7209 replace_host.SetHostStr(kExpectCTStaticHostname);
7210 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:167211 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
7212 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:477213 violating_request->Start();
Wez2a31b222018-06-07 22:07:157214 d.RunUntilComplete();
estark1614475f2016-03-10 03:46:477215
7216 EXPECT_EQ(1u, reporter.num_failures());
7217}
Emily Stark4cfecf072017-08-08 01:05:517218
7219// Tests that Expect CT HTTP headers are processed correctly.
7220TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
7221 base::test::ScopedFeatureList feature_list;
7222 feature_list.InitAndEnableFeature(
7223 TransportSecurityState::kDynamicExpectCTFeature);
7224
7225 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7226 https_test_server.SetSSLConfig(
7227 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7228 https_test_server.ServeFilesFromSourceDirectory(
7229 base::FilePath(kTestFilePath));
7230 ASSERT_TRUE(https_test_server.Start());
7231
7232 MockExpectCTReporter reporter;
7233 TransportSecurityState transport_security_state;
7234 transport_security_state.SetExpectCTReporter(&reporter);
7235
7236 // Set up a MockCertVerifier to accept the certificate that the server sends.
7237 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7238 ASSERT_TRUE(cert);
7239 MockCertVerifier cert_verifier;
7240 CertVerifyResult verify_result;
7241 verify_result.verified_cert = cert;
7242 verify_result.is_issued_by_known_root = true;
7243 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7244
7245 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7246 // compliance.
7247 DoNothingCTVerifier ct_verifier;
7248 MockCTPolicyEnforcer ct_policy_enforcer;
7249 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547250 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517251
7252 TestNetworkDelegate network_delegate;
7253 // Use a MockHostResolver (which by default maps all hosts to
7254 // 127.0.0.1).
7255 MockHostResolver host_resolver;
7256 TestURLRequestContext context(true);
7257 context.set_host_resolver(&host_resolver);
7258 context.set_transport_security_state(&transport_security_state);
7259 context.set_network_delegate(&network_delegate);
7260 context.set_cert_verifier(&cert_verifier);
7261 context.set_cert_transparency_verifier(&ct_verifier);
7262 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7263 context.Init();
7264
7265 // Now send a request to trigger the header processing.
7266 TestDelegate d;
7267 GURL url = https_test_server.GetURL("/expect-ct-header.html");
7268 std::unique_ptr<URLRequest> request(context.CreateRequest(
7269 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7270 request->Start();
Wez2a31b222018-06-07 22:07:157271 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517272
7273 TransportSecurityState::ExpectCTState state;
7274 ASSERT_TRUE(
7275 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7276 EXPECT_TRUE(state.enforce);
7277 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7278}
7279
7280// Tests that if multiple Expect CT HTTP headers are sent, they are all
7281// processed.
7282TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
7283 base::test::ScopedFeatureList feature_list;
7284 feature_list.InitAndEnableFeature(
7285 TransportSecurityState::kDynamicExpectCTFeature);
7286
7287 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7288 https_test_server.SetSSLConfig(
7289 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7290 https_test_server.ServeFilesFromSourceDirectory(
7291 base::FilePath(kTestFilePath));
7292 ASSERT_TRUE(https_test_server.Start());
7293
7294 MockExpectCTReporter reporter;
7295 TransportSecurityState transport_security_state;
7296 transport_security_state.SetExpectCTReporter(&reporter);
7297
7298 // Set up a MockCertVerifier to accept the certificate that the server sends.
7299 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7300 ASSERT_TRUE(cert);
7301 MockCertVerifier cert_verifier;
7302 CertVerifyResult verify_result;
7303 verify_result.verified_cert = cert;
7304 verify_result.is_issued_by_known_root = true;
7305 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7306
7307 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7308 // compliance.
7309 DoNothingCTVerifier ct_verifier;
7310 MockCTPolicyEnforcer ct_policy_enforcer;
7311 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547312 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517313
7314 TestNetworkDelegate network_delegate;
7315 // Use a MockHostResolver (which by default maps all hosts to
7316 // 127.0.0.1).
7317 MockHostResolver host_resolver;
7318 TestURLRequestContext context(true);
7319 context.set_host_resolver(&host_resolver);
7320 context.set_transport_security_state(&transport_security_state);
7321 context.set_network_delegate(&network_delegate);
7322 context.set_cert_verifier(&cert_verifier);
7323 context.set_cert_transparency_verifier(&ct_verifier);
7324 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7325 context.Init();
7326
7327 // Now send a request to trigger the header processing.
7328 TestDelegate d;
7329 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7330 std::unique_ptr<URLRequest> request(context.CreateRequest(
7331 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7332 request->Start();
Wez2a31b222018-06-07 22:07:157333 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517334
7335 TransportSecurityState::ExpectCTState state;
7336 ASSERT_TRUE(
7337 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7338 EXPECT_TRUE(state.enforce);
7339 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7340}
7341
mmenkefd9d15c2017-06-29 13:45:547342#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477343
Lily Chenfec60d92019-01-24 01:16:427344#if BUILDFLAG(ENABLE_REPORTING)
7345
Lily Chend3930e72019-03-01 19:31:117346TEST_F(URLRequestTestHTTP, NetworkErrorLogging_DontReportIfNetworkNotAccessed) {
7347 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7348 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7349 ASSERT_TRUE(https_test_server.Start());
7350 GURL request_url = https_test_server.GetURL("/cachetime");
7351
7352 TestNetworkErrorLoggingService nel_service;
7353 TestURLRequestContext context(true);
7354 context.set_network_error_logging_service(&nel_service);
7355 context.Init();
7356
7357 // Populate the cache.
7358 TestDelegate d;
7359 std::unique_ptr<URLRequest> request(context.CreateRequest(
7360 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7361 request->Start();
7362 d.RunUntilComplete();
7363
7364 ASSERT_EQ(1u, nel_service.errors().size());
7365 const TestNetworkErrorLoggingService::RequestDetails& error =
7366 nel_service.errors()[0];
7367 EXPECT_EQ(request_url, error.uri);
7368 EXPECT_EQ(200, error.status_code);
7369 EXPECT_EQ(OK, error.type);
7370
7371 request = context.CreateRequest(request_url, DEFAULT_PRIORITY, &d,
7372 TRAFFIC_ANNOTATION_FOR_TESTS);
7373 request->Start();
7374 d.RunUntilComplete();
7375
7376 EXPECT_FALSE(request->response_info().network_accessed);
7377 EXPECT_TRUE(request->response_info().was_cached);
7378 // No additional NEL report was generated.
7379 EXPECT_EQ(1u, nel_service.errors().size());
7380}
7381
Lily Chenfec60d92019-01-24 01:16:427382TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicSuccess) {
7383 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7384 https_test_server.ServeFilesFromSourceDirectory(
7385 base::FilePath(kTestFilePath));
7386 ASSERT_TRUE(https_test_server.Start());
7387 GURL request_url = https_test_server.GetURL("/simple.html");
7388
7389 TestNetworkErrorLoggingService nel_service;
7390 TestURLRequestContext context(true);
7391 context.set_network_error_logging_service(&nel_service);
7392 context.Init();
7393
7394 TestDelegate d;
7395 std::unique_ptr<URLRequest> request(context.CreateRequest(
7396 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7397 request->Start();
7398 d.RunUntilComplete();
7399
7400 ASSERT_EQ(1u, nel_service.errors().size());
7401 const TestNetworkErrorLoggingService::RequestDetails& error =
7402 nel_service.errors()[0];
7403 EXPECT_EQ(request_url, error.uri);
7404 EXPECT_EQ(200, error.status_code);
7405 EXPECT_EQ(OK, error.type);
7406}
7407
7408TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicError) {
7409 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7410 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7411 ASSERT_TRUE(https_test_server.Start());
7412 GURL request_url = https_test_server.GetURL("/close-socket");
7413
7414 TestNetworkErrorLoggingService nel_service;
7415 TestURLRequestContext context(true);
7416 context.set_network_error_logging_service(&nel_service);
7417 context.Init();
7418
7419 TestDelegate d;
7420 std::unique_ptr<URLRequest> request(context.CreateRequest(
7421 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7422 request->Start();
7423 d.RunUntilComplete();
7424
7425 ASSERT_EQ(1u, nel_service.errors().size());
7426 const TestNetworkErrorLoggingService::RequestDetails& error =
7427 nel_service.errors()[0];
7428 EXPECT_EQ(request_url, error.uri);
7429 EXPECT_EQ(0, error.status_code);
7430 EXPECT_EQ(ERR_EMPTY_RESPONSE, error.type);
7431}
7432
7433TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Redirect) {
7434 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7435 https_test_server.ServeFilesFromSourceDirectory(
7436 base::FilePath(kTestFilePath));
7437 ASSERT_TRUE(https_test_server.Start());
7438 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7439 GURL redirect_url = https_test_server.GetURL("/with-headers.html");
7440
7441 TestNetworkErrorLoggingService nel_service;
7442 TestURLRequestContext context(true);
7443 context.set_network_error_logging_service(&nel_service);
7444 context.Init();
7445
7446 TestDelegate d;
7447 std::unique_ptr<URLRequest> request(context.CreateRequest(
7448 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7449 request->Start();
7450 d.RunUntilComplete();
7451
7452 ASSERT_EQ(2u, nel_service.errors().size());
7453 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7454 nel_service.errors()[0];
7455 EXPECT_EQ(request_url, error1.uri);
7456 EXPECT_EQ(302, error1.status_code);
7457 EXPECT_EQ(OK, error1.type);
7458 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7459 nel_service.errors()[1];
7460 EXPECT_EQ(redirect_url, error2.uri);
7461 EXPECT_EQ(200, error2.status_code);
7462 EXPECT_EQ(OK, error2.type);
7463}
7464
Lily Chend3930e72019-03-01 19:31:117465TEST_F(URLRequestTestHTTP, NetworkErrorLogging_RedirectWithoutLocationHeader) {
7466 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7467 https_test_server.ServeFilesFromSourceDirectory(
7468 base::FilePath(kTestFilePath));
7469 ASSERT_TRUE(https_test_server.Start());
7470 GURL request_url = https_test_server.GetURL("/308-without-location-header");
7471
7472 TestNetworkErrorLoggingService nel_service;
7473 TestURLRequestContext context(true);
7474 context.set_network_error_logging_service(&nel_service);
7475 context.Init();
7476
7477 TestDelegate d;
7478 std::unique_ptr<URLRequest> request(context.CreateRequest(
7479 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7480 request->Start();
7481 d.RunUntilComplete();
7482
7483 ASSERT_EQ(1u, nel_service.errors().size());
7484 const TestNetworkErrorLoggingService::RequestDetails& error =
7485 nel_service.errors()[0];
7486 EXPECT_EQ(request_url, error.uri);
7487 EXPECT_EQ(308, error.status_code);
7488 // The body of the response was successfully read.
7489 EXPECT_EQ(OK, error.type);
7490}
7491
Lily Chenfec60d92019-01-24 01:16:427492TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Auth) {
7493 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7494 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7495 ASSERT_TRUE(https_test_server.Start());
7496 GURL request_url = https_test_server.GetURL("/auth-basic");
7497
7498 TestNetworkErrorLoggingService nel_service;
7499 TestURLRequestContext context(true);
7500 context.set_network_error_logging_service(&nel_service);
7501 context.Init();
7502
7503 TestDelegate d;
7504 d.set_credentials(AuthCredentials(kUser, kSecret));
7505 std::unique_ptr<URLRequest> request(context.CreateRequest(
7506 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7507 request->Start();
7508 d.RunUntilComplete();
7509
7510 ASSERT_EQ(2u, nel_service.errors().size());
7511 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7512 nel_service.errors()[0];
7513 EXPECT_EQ(request_url, error1.uri);
7514 EXPECT_EQ(401, error1.status_code);
7515 EXPECT_EQ(OK, error1.type);
7516 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7517 nel_service.errors()[1];
7518 EXPECT_EQ(request_url, error2.uri);
7519 EXPECT_EQ(200, error2.status_code);
7520 EXPECT_EQ(OK, error2.type);
7521}
7522
Lily Chend3930e72019-03-01 19:31:117523TEST_F(URLRequestTestHTTP, NetworkErrorLogging_304Response) {
7524 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7525 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7526 ASSERT_TRUE(https_test_server.Start());
7527 GURL request_url = https_test_server.GetURL("/auth-basic");
7528
7529 TestNetworkErrorLoggingService nel_service;
7530 TestURLRequestContext context(true);
7531 context.set_network_error_logging_service(&nel_service);
7532 context.Init();
7533
7534 // populate the cache
7535 {
7536 TestDelegate d;
7537 d.set_credentials(AuthCredentials(kUser, kSecret));
7538 std::unique_ptr<URLRequest> r(context.CreateRequest(
7539 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7540 r->Start();
7541 d.RunUntilComplete();
7542 }
7543 ASSERT_EQ(2u, nel_service.errors().size());
7544 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7545 nel_service.errors()[0];
7546 EXPECT_EQ(request_url, error1.uri);
7547 EXPECT_EQ(401, error1.status_code);
7548 EXPECT_EQ(OK, error1.type);
7549 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7550 nel_service.errors()[1];
7551 EXPECT_EQ(request_url, error2.uri);
7552 EXPECT_EQ(200, error2.status_code);
7553 EXPECT_EQ(OK, error2.type);
7554
7555 // repeat request with end-to-end validation. since auth-basic results in a
7556 // cachable page, we expect this test to result in a 304. in which case, the
7557 // response should be fetched from the cache.
7558 {
7559 TestDelegate d;
7560 d.set_credentials(AuthCredentials(kUser, kSecret));
7561 std::unique_ptr<URLRequest> r(context.CreateRequest(
7562 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7563 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7564 r->Start();
7565 d.RunUntilComplete();
7566
7567 // Should be the same cached document.
7568 EXPECT_TRUE(r->was_cached());
7569 }
7570 ASSERT_EQ(3u, nel_service.errors().size());
7571 const TestNetworkErrorLoggingService::RequestDetails& error3 =
7572 nel_service.errors()[2];
7573 EXPECT_EQ(request_url, error3.uri);
7574 EXPECT_EQ(304, error3.status_code);
7575 EXPECT_EQ(OK, error3.type);
7576}
7577
7578TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelInResponseStarted) {
Lily Chenfec60d92019-01-24 01:16:427579 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7580 https_test_server.ServeFilesFromSourceDirectory(
7581 base::FilePath(kTestFilePath));
7582 ASSERT_TRUE(https_test_server.Start());
7583 GURL request_url = https_test_server.GetURL("/simple.html");
7584
7585 TestNetworkErrorLoggingService nel_service;
7586 TestURLRequestContext context(true);
7587 context.set_network_error_logging_service(&nel_service);
7588 context.Init();
7589
7590 TestDelegate d;
7591 d.set_cancel_in_response_started(true);
7592 std::unique_ptr<URLRequest> request(context.CreateRequest(
7593 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7594 request->Start();
7595 d.RunUntilComplete();
7596
7597 ASSERT_EQ(1u, nel_service.errors().size());
7598 const TestNetworkErrorLoggingService::RequestDetails& error =
7599 nel_service.errors()[0];
7600 EXPECT_EQ(request_url, error.uri);
7601 EXPECT_EQ(200, error.status_code);
Lily Chend3930e72019-03-01 19:31:117602 // Headers were received and the body should have been read but was not.
7603 EXPECT_EQ(ERR_ABORTED, error.type);
7604}
7605
7606TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelOnDataReceived) {
7607 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7608 https_test_server.ServeFilesFromSourceDirectory(
7609 base::FilePath(kTestFilePath));
7610 ASSERT_TRUE(https_test_server.Start());
7611 GURL request_url = https_test_server.GetURL("/simple.html");
7612
7613 TestNetworkErrorLoggingService nel_service;
7614 TestURLRequestContext context(true);
7615 context.set_network_error_logging_service(&nel_service);
7616 context.Init();
7617
7618 TestDelegate d;
7619 d.set_cancel_in_received_data(true);
7620 std::unique_ptr<URLRequest> request(context.CreateRequest(
7621 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7622 request->Start();
7623 d.RunUntilComplete();
7624
7625 ASSERT_EQ(1u, nel_service.errors().size());
7626 const TestNetworkErrorLoggingService::RequestDetails& error =
7627 nel_service.errors()[0];
7628 EXPECT_EQ(request_url, error.uri);
7629 EXPECT_EQ(200, error.status_code);
7630 // Data was received but the body was not completely read.
7631 EXPECT_EQ(ERR_ABORTED, error.type);
7632}
7633
7634TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelRedirect) {
7635 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7636 https_test_server.ServeFilesFromSourceDirectory(
7637 base::FilePath(kTestFilePath));
7638 ASSERT_TRUE(https_test_server.Start());
7639 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7640
7641 TestNetworkErrorLoggingService nel_service;
7642 TestURLRequestContext context(true);
7643 context.set_network_error_logging_service(&nel_service);
7644 context.Init();
7645
7646 TestDelegate d;
7647 d.set_cancel_in_received_redirect(true);
7648 std::unique_ptr<URLRequest> request(context.CreateRequest(
7649 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7650 request->Start();
7651 d.RunUntilComplete();
7652
7653 ASSERT_EQ(1u, nel_service.errors().size());
7654 const TestNetworkErrorLoggingService::RequestDetails& error =
7655 nel_service.errors()[0];
7656 EXPECT_EQ(request_url, error.uri);
7657 EXPECT_EQ(302, error.status_code);
7658 // A valid HTTP response was received, even though the request was cancelled.
Lily Chenfec60d92019-01-24 01:16:427659 EXPECT_EQ(OK, error.type);
7660}
7661
7662#endif // BUILDFLAG(ENABLE_REPORTING)
7663
[email protected]316c1e5e2012-09-12 15:17:447664TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557665 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447666
7667 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077668 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557669 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167670 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197671 req->Start();
Wez2a31b222018-06-07 22:07:157672 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447673
7674 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197675 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447676 EXPECT_EQ("text/html", mime_type);
7677
7678 std::string charset;
[email protected]f7022f32014-08-21 16:32:197679 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447680 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197681 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447682}
7683
[email protected]02494ec2014-05-07 15:05:297684TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347685 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347686 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347687 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027688 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347689
7690 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507691 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347692}
7693
brettwa1228ebb2016-10-28 03:51:347694#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297695TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7696 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7697 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457698 FileProtocolHandler file_protocol_handler(
7699 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297700 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7701
7702 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507703 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297704}
7705
[email protected]588614c22013-08-16 00:09:027706TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557707 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447708
7709 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077710 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557711 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167712 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197713 req->Start();
Wez2a31b222018-06-07 22:07:157714 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447715
maksim.sisovb53724b52016-09-16 05:30:507716 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307717
7718 // The redirect should have been rejected before reporting it to the caller.
7719 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447720}
brettwa1228ebb2016-10-28 03:51:347721#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447722
[email protected]588614c22013-08-16 00:09:027723TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557724 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027725
7726 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077727 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557728 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167729 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197730 req->Start();
Wez2a31b222018-06-07 22:07:157731 d.RunUntilComplete();
[email protected]588614c22013-08-16 00:09:027732
maksim.sisovb53724b52016-09-16 05:30:507733 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307734
7735 // The redirect should have been rejected before reporting it to the
7736 // caller. See https://crbug.com/723796
7737 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027738}
7739
davidbend894710b2017-06-06 19:28:307740// Test that redirects to invalid URLs are rejected. See
7741// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447742TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557743 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447744
7745 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077746 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557747 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167748 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197749 req->Start();
Wez2a31b222018-06-07 22:07:157750 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447751
davidbend894710b2017-06-06 19:28:307752 EXPECT_EQ(1, d.response_started_count());
7753 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7754
7755 // The redirect should have been rejected before reporting it to the caller.
7756 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447757}
7758
[email protected]e50efea2014-03-24 18:41:007759// Make sure redirects are cached, despite not reading their bodies.
7760TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557761 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007762 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557763 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007764
7765 {
7766 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077767 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167768 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197769 req->Start();
Wez2a31b222018-06-07 22:07:157770 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507771 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007772 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557773 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007774 }
7775
7776 {
7777 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077778 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167779 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197780 req->Start();
Wez0e717112018-06-18 23:09:227781 d.RunUntilRedirect();
[email protected]e50efea2014-03-24 18:41:007782
7783 EXPECT_EQ(1, d.received_redirect_count());
7784 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197785 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007786
Arthur Sonzognib8465ff72019-01-04 18:44:357787 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7788 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157789 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007790 EXPECT_EQ(1, d.received_redirect_count());
7791 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507792 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557793 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007794 }
7795}
7796
7797// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7798// when the headers are read, since the body won't have been read.
7799TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557800 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007801 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557802 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007803
7804 {
7805 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557806 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007807 default_network_delegate_.set_redirect_on_headers_received_url(
7808 redirect_to_url);
7809
7810 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077811 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167812 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197813 req->Start();
Wez2a31b222018-06-07 22:07:157814 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507815 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007816 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197817 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007818 }
7819
7820 {
7821 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077822 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167823 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197824 req->Start();
Wez2a31b222018-06-07 22:07:157825 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007826
maksim.sisovb53724b52016-09-16 05:30:507827 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197828 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007829 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197830 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007831 }
7832}
7833
[email protected]5f714132014-03-26 10:41:167834// Tests that redirection to an unsafe URL is allowed when it has been marked as
7835// safe.
7836TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557837 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167838
7839 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7840 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7841 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7842
7843 TestDelegate d;
7844 {
Ryan Sleevib8449e02018-07-15 04:31:077845 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167846 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7847 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167848
[email protected]f7022f32014-08-21 16:32:197849 r->Start();
Wez2a31b222018-06-07 22:07:157850 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167851
maksim.sisovb53724b52016-09-16 05:30:507852 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197853 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197854 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167855 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7856 }
7857}
7858
7859// Tests that a redirect to a different unsafe URL is blocked, even after adding
7860// some other URL to the whitelist.
7861TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557862 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167863
7864 GURL unsafe_url("data:text/html,something");
7865 GURL different_unsafe_url("data:text/html,something-else");
7866 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7867 default_network_delegate_.set_allowed_unsafe_redirect_url(
7868 different_unsafe_url);
7869
7870 TestDelegate d;
7871 {
Ryan Sleevib8449e02018-07-15 04:31:077872 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167873 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7874 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167875
[email protected]f7022f32014-08-21 16:32:197876 r->Start();
Wez2a31b222018-06-07 22:07:157877 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167878
maksim.sisovb53724b52016-09-16 05:30:507879 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307880
7881 // The redirect should have been rejected before reporting it to the caller.
7882 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167883 }
7884}
7885
[email protected]5f714132014-03-26 10:41:167886// Redirects from an URL with fragment to an unsafe URL with fragment should
7887// be allowed, and the reference fragment of the target URL should be preserved.
7888TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557889 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167890
tommycli59a63432015-11-06 00:10:557891 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167892 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7893 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7894
7895 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7896 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7897
7898 TestDelegate d;
7899 {
Ryan Sleevib8449e02018-07-15 04:31:077900 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167901 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167902
[email protected]f7022f32014-08-21 16:32:197903 r->Start();
Wez2a31b222018-06-07 22:07:157904 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167905
[email protected]f7022f32014-08-21 16:32:197906 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507907 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197908 EXPECT_EQ(original_url, r->original_url());
7909 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167910 }
7911}
7912
7913// When a delegate has specified a safe redirect URL, but it does not match the
7914// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147915TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557916 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167917
tommycli59a63432015-11-06 00:10:557918 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167919 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557920 GURL redirect_url(http_test_server()->GetURL("/target"));
7921 GURL expected_redirect_url(
7922 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167923
7924 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7925 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7926
7927 TestDelegate d;
7928 {
Ryan Sleevib8449e02018-07-15 04:31:077929 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167930 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167931
[email protected]f7022f32014-08-21 16:32:197932 r->Start();
Wez2a31b222018-06-07 22:07:157933 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167934
[email protected]f7022f32014-08-21 16:32:197935 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507936 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197937 EXPECT_EQ(original_url, r->original_url());
7938 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167939 }
7940}
7941
[email protected]f878230e2014-04-03 15:36:147942// When a delegate has specified a safe redirect URL, assume that the redirect
7943// URL should not be changed. In particular, the reference fragment should not
7944// be modified.
7945TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557946 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147947
tommycli59a63432015-11-06 00:10:557948 GURL original_url(
7949 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147950 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7951
7952 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7953 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7954
7955 TestDelegate d;
7956 {
Ryan Sleevib8449e02018-07-15 04:31:077957 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167958 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147959
[email protected]f7022f32014-08-21 16:32:197960 r->Start();
Wez2a31b222018-06-07 22:07:157961 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147962
[email protected]f7022f32014-08-21 16:32:197963 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507964 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197965 EXPECT_EQ(original_url, r->original_url());
7966 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147967 }
7968}
7969
7970// When a URLRequestRedirectJob is created, the redirection must be followed and
7971// the reference fragment of the target URL must not be modified.
7972TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557973 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147974
tommycli59a63432015-11-06 00:10:557975 GURL original_url(
7976 http_test_server()->GetURL("/original#should-not-be-appended"));
7977 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147978
7979 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077980 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167981 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147982
danakj8522a25b2016-04-16 00:17:367983 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197984 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427985 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7986 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:147987
[email protected]f7022f32014-08-21 16:32:197988 r->Start();
Wez2a31b222018-06-07 22:07:157989 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147990
maksim.sisovb53724b52016-09-16 05:30:507991 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197992 EXPECT_EQ(original_url, r->original_url());
7993 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147994}
7995
lizeb5120f6dc2016-02-19 09:29:447996TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
7997 ASSERT_TRUE(http_test_server()->Start());
7998
7999 const std::string referrer("foobar://totally.legit.referrer");
8000 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078001 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168002 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8003 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:448004 req->SetReferrer(referrer);
8005 req->Start();
Wez2a31b222018-06-07 22:07:158006 d.RunUntilComplete();
lizeb5120f6dc2016-02-19 09:29:448007
8008 EXPECT_EQ(std::string("None"), d.data_received());
8009}
8010
[email protected]316c1e5e2012-09-12 15:17:448011TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:558012 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448013
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));
[email protected]f7022f32014-08-21 16:32:198018 req->SetReferrer("http://user:[email protected]/");
8019 req->Start();
Wez2a31b222018-06-07 22:07:158020 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448021
8022 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
8023}
8024
[email protected]99ecf6e2013-04-10 22:46:138025TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:558026 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138027
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://foo.com/test#fragment");
8033 req->Start();
Wez2a31b222018-06-07 22:07:158034 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138035
8036 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
8037}
8038
8039TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
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->SetReferrer("");
8048 req->Start();
Wez2a31b222018-06-07 22:07:158049 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138050
8051 EXPECT_EQ(std::string("None"), d.data_received());
8052}
8053
Mike Westfbd44112019-05-08 18:23:378054TEST_F(URLRequestTestHTTP, CapRefererDisabled) {
8055 ASSERT_TRUE(http_test_server()->Start());
8056
8057 // Create a string, and pad it out to ~10k with a very exciting path.
8058 std::string long_referer_header = "http://foo.com/";
8059 long_referer_header.resize(10000, 'a');
8060
8061 // If the feature isn't enabled, a long `referer` will remain long.
8062 TestDelegate d;
8063 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8064 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8065 TRAFFIC_ANNOTATION_FOR_TESTS));
8066 req->SetReferrer(long_referer_header);
8067 req->Start();
8068 d.RunUntilComplete();
8069
8070 EXPECT_EQ(long_referer_header, d.data_received());
8071}
8072
8073TEST_F(URLRequestTestHTTP, CapRefererHeaderLengthEnabled) {
8074 ASSERT_TRUE(http_test_server()->Start());
8075
8076 // Create a string, and pad it out to ~10k with a very exciting path.
8077 std::string long_referer_header = "http://foo.com/";
8078 long_referer_header.resize(10000, 'a');
8079
8080 // If the feature is enabled without params, a `referer` longer than 4096
8081 // bytes will be shortened.
8082 {
8083 TestDelegate d;
8084 base::test::ScopedFeatureList feature_list;
8085 feature_list.InitAndEnableFeature(features::kCapRefererHeaderLength);
8086
8087 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8088 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8089 TRAFFIC_ANNOTATION_FOR_TESTS));
8090 req->SetReferrer(long_referer_header);
8091 req->Start();
8092 d.RunUntilComplete();
8093
8094 EXPECT_EQ("http://foo.com/", d.data_received());
8095 }
8096
8097 // If the feature is enabled with params, they will govern the shortening
8098 // behavior as expected. The following three tests verify behavior for a
8099 // param larger than the referrer length, exactly the same as the string
8100 // length, and shorter than the string length.
8101 {
8102 TestDelegate d;
8103 std::map<std::string, std::string> params;
8104 params["MaxRefererHeaderLength"] =
8105 base::NumberToString(long_referer_header.length() + 1);
8106
8107 base::test::ScopedFeatureList feature_list;
8108 feature_list.InitAndEnableFeatureWithParameters(
8109 features::kCapRefererHeaderLength, params);
8110
8111 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8112 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8113 TRAFFIC_ANNOTATION_FOR_TESTS));
8114 req->SetReferrer(long_referer_header);
8115 req->Start();
8116 d.RunUntilComplete();
8117
8118 EXPECT_EQ(long_referer_header, d.data_received());
8119 }
8120
8121 {
8122 TestDelegate d;
8123 std::map<std::string, std::string> params;
8124 params["MaxRefererHeaderLength"] =
8125 base::NumberToString(long_referer_header.length());
8126
8127 base::test::ScopedFeatureList feature_list;
8128 feature_list.InitAndEnableFeatureWithParameters(
8129 features::kCapRefererHeaderLength, params);
8130
8131 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8132 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8133 TRAFFIC_ANNOTATION_FOR_TESTS));
8134 req->SetReferrer(long_referer_header);
8135 req->Start();
8136 d.RunUntilComplete();
8137
8138 EXPECT_EQ(long_referer_header, d.data_received());
8139 }
8140
8141 {
8142 TestDelegate d;
8143 std::map<std::string, std::string> params;
8144 params["MaxRefererHeaderLength"] =
8145 base::NumberToString(long_referer_header.length() - 1);
8146
8147 base::test::ScopedFeatureList feature_list;
8148 feature_list.InitAndEnableFeatureWithParameters(
8149 features::kCapRefererHeaderLength, params);
8150
8151 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8152 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8153 TRAFFIC_ANNOTATION_FOR_TESTS));
8154 req->SetReferrer(long_referer_header);
8155 req->Start();
8156 d.RunUntilComplete();
8157
8158 EXPECT_EQ("http://foo.com/", d.data_received());
8159 }
8160}
8161
[email protected]316c1e5e2012-09-12 15:17:448162TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:558163 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448164
8165 TestDelegate d;
8166 {
8167 d.set_cancel_in_received_redirect(true);
Ryan Sleevib8449e02018-07-15 04:31:078168 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168169 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8170 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198171 req->Start();
Wez2a31b222018-06-07 22:07:158172 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448173
8174 EXPECT_EQ(1, d.response_started_count());
8175 EXPECT_EQ(0, d.bytes_received());
8176 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508177 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448178 }
8179}
8180
8181TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:558182 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448183
8184 TestDelegate d;
8185 {
tommycli59a63432015-11-06 00:10:558186 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078187 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168188 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048189
[email protected]f7022f32014-08-21 16:32:198190 req->Start();
Wez0e717112018-06-18 23:09:228191 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:448192
8193 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:238194 EXPECT_TRUE(d.have_full_request_headers());
8195 CheckFullRequestHeaders(d.full_request_headers(), test_url);
8196 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:448197
Arthur Sonzognib8465ff72019-01-04 18:44:358198 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8199 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:158200 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448201
8202 EXPECT_EQ(1, d.response_started_count());
8203 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508204 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448205
[email protected]6cdfd7f2013-02-08 20:40:158206 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198207 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478208 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:448209 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8210
8211 std::string contents;
[email protected]82f84b92013-08-30 18:23:508212 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:448213 EXPECT_EQ(contents, d.data_received());
8214 }
8215}
8216
[email protected]79e1fd62013-06-20 06:50:048217TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:558218 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:048219
8220 TestDelegate d;
8221 {
tommycli59a63432015-11-06 00:10:558222 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078223 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168224 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048225
8226 EXPECT_FALSE(d.have_full_request_headers());
8227
[email protected]f7022f32014-08-21 16:32:198228 req->Start();
Wez0e717112018-06-18 23:09:228229 d.RunUntilRedirect();
[email protected]79e1fd62013-06-20 06:50:048230
8231 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:048232
Arthur Sonzognib8465ff72019-01-04 18:44:358233 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8234 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:158235 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:048236
tommycli59a63432015-11-06 00:10:558237 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:048238 EXPECT_EQ(1, d.response_started_count());
8239 EXPECT_TRUE(d.have_full_request_headers());
8240 CheckFullRequestHeaders(d.full_request_headers(), target_url);
8241 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508242 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:048243
8244 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198245 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478246 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:048247 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8248
8249 std::string contents;
[email protected]82f84b92013-08-30 18:23:508250 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:048251 EXPECT_EQ(contents, d.data_received());
8252 }
8253}
8254
Arthur Sonzognib8465ff72019-01-04 18:44:358255TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedHeaders) {
Chong Zhang7607f1f2018-06-01 20:52:208256 ASSERT_TRUE(http_test_server()->Start());
8257
8258 TestDelegate d;
8259 {
Chong Zhang7607f1f2018-06-01 20:52:208260 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078261 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Chong Zhang7607f1f2018-06-01 20:52:208262 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8263
8264 // Set initial headers for the request.
8265 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8266 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8267
8268 req->Start();
Wez0e717112018-06-18 23:09:228269 d.RunUntilRedirect();
Chong Zhang7607f1f2018-06-01 20:52:208270
8271 // Initial request should only have initial headers.
8272 EXPECT_EQ(1, d.received_redirect_count());
8273 EXPECT_TRUE(d.have_full_request_headers());
8274 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8275 std::string sent_value;
8276 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8277 EXPECT_EQ("Value1", sent_value);
8278 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8279 EXPECT_EQ("Value2", sent_value);
8280 EXPECT_FALSE(sent_headers1.GetHeader("Header3", &sent_value));
8281 d.ClearFullRequestHeaders();
8282
8283 // Overwrite Header2 and add Header3.
Arthur Sonzognib8465ff72019-01-04 18:44:358284 net::HttpRequestHeaders modified_headers;
8285 modified_headers.SetHeader("Header2", "");
8286 modified_headers.SetHeader("Header3", "Value3");
Chong Zhang7607f1f2018-06-01 20:52:208287
Arthur Sonzognib8465ff72019-01-04 18:44:358288 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8289 modified_headers);
Wez2a31b222018-06-07 22:07:158290 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:208291
8292 EXPECT_EQ(1, d.response_started_count());
8293 EXPECT_FALSE(d.received_data_before_response());
8294 EXPECT_EQ(OK, d.request_status());
8295
8296 // Redirected request should also have modified headers.
8297 EXPECT_TRUE(d.have_full_request_headers());
8298 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8299 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8300 EXPECT_EQ("Value1", sent_value);
8301 EXPECT_TRUE(sent_headers2.GetHeader("Header2", &sent_value));
8302 EXPECT_EQ("", sent_value);
8303 EXPECT_TRUE(sent_headers2.GetHeader("Header3", &sent_value));
8304 EXPECT_EQ("Value3", sent_value);
8305 }
8306}
8307
Arthur Sonzognib8465ff72019-01-04 18:44:358308TEST_F(URLRequestTestHTTP, DeferredRedirect_RemovedHeaders) {
8309 ASSERT_TRUE(http_test_server()->Start());
8310
8311 TestDelegate d;
8312 {
8313 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
8314 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8315 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8316
8317 // Set initial headers for the request.
8318 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8319 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8320
8321 req->Start();
8322 d.RunUntilRedirect();
8323
8324 // Initial request should have initial headers.
8325 EXPECT_EQ(1, d.received_redirect_count());
8326 EXPECT_TRUE(d.have_full_request_headers());
8327 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8328 std::string sent_value;
8329 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8330 EXPECT_EQ("Value1", sent_value);
8331 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8332 EXPECT_EQ("Value2", sent_value);
8333 d.ClearFullRequestHeaders();
8334
8335 // Keep Header1 and remove Header2.
8336 std::vector<std::string> removed_headers({"Header2"});
8337 req->FollowDeferredRedirect(removed_headers,
8338 base::nullopt /* modified_headers */);
8339 d.RunUntilComplete();
8340
8341 EXPECT_EQ(1, d.response_started_count());
8342 EXPECT_FALSE(d.received_data_before_response());
8343 EXPECT_EQ(OK, d.request_status());
8344
8345 // Redirected request should also have
8346 EXPECT_TRUE(d.have_full_request_headers());
8347 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8348 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8349 EXPECT_EQ("Value1", sent_value);
8350 EXPECT_FALSE(sent_headers2.GetHeader("Header2", &sent_value));
8351 }
8352}
8353
[email protected]316c1e5e2012-09-12 15:17:448354TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:558355 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448356
8357 TestDelegate d;
8358 {
Ryan Sleevib8449e02018-07-15 04:31:078359 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168360 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8361 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198362 req->Start();
Wez0e717112018-06-18 23:09:228363 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:448364
8365 EXPECT_EQ(1, d.received_redirect_count());
8366
[email protected]f7022f32014-08-21 16:32:198367 req->Cancel();
Wez2a31b222018-06-07 22:07:158368 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448369
8370 EXPECT_EQ(1, d.response_started_count());
8371 EXPECT_EQ(0, d.bytes_received());
8372 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508373 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448374 }
8375}
8376
8377TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:558378 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448379
[email protected]3b23a222013-05-15 21:33:258380 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:448381 {
8382 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078383 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558384 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168385 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448386 HttpRequestHeaders headers;
8387 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198388 req->SetExtraRequestHeaders(headers);
8389 req->Start();
Wez2a31b222018-06-07 22:07:158390 d.RunUntilComplete();
[email protected]3b23a222013-05-15 21:33:258391
8392 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198393 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258394 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448395 }
8396
[email protected]3b23a222013-05-15 21:33:258397 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:448398 {
8399 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078400 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558401 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168402 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448403 HttpRequestHeaders headers;
8404 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198405 req->SetExtraRequestHeaders(headers);
8406 req->Start();
Wez2a31b222018-06-07 22:07:158407 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448408
[email protected]f7022f32014-08-21 16:32:198409 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258410
8411 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198412 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258413 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:448414 }
8415
[email protected]3b23a222013-05-15 21:33:258416 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:448417 {
8418 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078419 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558420 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168421 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448422 HttpRequestHeaders headers;
8423 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:198424 req->SetExtraRequestHeaders(headers);
8425 req->Start();
Wez2a31b222018-06-07 22:07:158426 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448427
[email protected]f7022f32014-08-21 16:32:198428 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258429
8430 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198431 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258432 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448433 }
8434}
8435
8436TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:558437 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448438
8439 // populate the cache
8440 {
8441 TestDelegate d;
8442 d.set_credentials(AuthCredentials(kUser, kSecret));
8443
Ryan Sleevib8449e02018-07-15 04:31:078444 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168445 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8446 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198447 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448448
Wez2a31b222018-06-07 22:07:158449 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448450
8451 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8452 }
8453
8454 // repeat request with end-to-end validation. since auth-basic results in a
8455 // cachable page, we expect this test to result in a 304. in which case, the
8456 // response should be fetched from the cache.
8457 {
8458 TestDelegate d;
8459 d.set_credentials(AuthCredentials(kUser, kSecret));
8460
Ryan Sleevib8449e02018-07-15 04:31:078461 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168462 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8463 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198464 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8465 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448466
Wez2a31b222018-06-07 22:07:158467 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448468
8469 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8470
8471 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198472 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:448473 }
8474}
8475
8476// Check that Set-Cookie headers in 401 responses are respected.
8477// http://crbug.com/6450
8478TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:558479 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448480
8481 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:558482 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:448483
8484 // Request a page that will give a 401 containing a Set-Cookie header.
8485 // Verify that when the transaction is restarted, it includes the new cookie.
8486 {
[email protected]ceefd7fd2012-11-29 00:36:248487 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448488 TestURLRequestContext context(true);
8489 context.set_network_delegate(&network_delegate);
8490 context.Init();
8491
8492 TestDelegate d;
8493 d.set_credentials(AuthCredentials(kUser, kSecret));
8494
danakj8522a25b2016-04-16 00:17:368495 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:168496 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
8497 TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298498 r->set_site_for_cookies(url_requiring_auth);
[email protected]f7022f32014-08-21 16:32:198499 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448500
Wez2a31b222018-06-07 22:07:158501 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448502
8503 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8504
8505 // Make sure we sent the cookie in the restarted transaction.
8506 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8507 != std::string::npos);
8508 }
8509
8510 // Same test as above, except this time the restart is initiated earlier
8511 // (without user intervention since identity is embedded in the URL).
8512 {
[email protected]ceefd7fd2012-11-29 00:36:248513 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448514 TestURLRequestContext context(true);
8515 context.set_network_delegate(&network_delegate);
8516 context.Init();
8517
8518 TestDelegate d;
8519
8520 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:188521 replacements.SetUsernameStr("user2");
8522 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:448523 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
8524
rhalavatib7bd7c792017-04-27 05:25:168525 std::unique_ptr<URLRequest> r(context.CreateRequest(
8526 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298527 r->set_site_for_cookies(url_with_identity);
[email protected]f7022f32014-08-21 16:32:198528 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448529
Wez2a31b222018-06-07 22:07:158530 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448531
8532 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
8533
8534 // Make sure we sent the cookie in the restarted transaction.
8535 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8536 != std::string::npos);
8537 }
8538}
8539
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548540TEST_F(URLRequestTest, CatchFilteredCookies) {
8541 HttpTestServer test_server;
8542 ASSERT_TRUE(test_server.Start());
8543
8544 FilteringTestLayeredNetworkDelegate network_delegate(
8545 std::make_unique<TestNetworkDelegate>());
8546 network_delegate.SetCookieFilter("not_stored_cookie");
8547 network_delegate.set_block_get_cookies();
8548 TestURLRequestContext context(true);
8549 context.set_network_delegate(&network_delegate);
8550 context.Init();
8551 // Make sure cookies blocked from being stored are caught.
8552 {
8553 TestDelegate d;
Lily Chen3ac7cf42019-05-30 23:29:298554 GURL test_url = test_server.GetURL("/set-cookie?not_stored_cookie=true");
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548555 std::unique_ptr<URLRequest> req(context.CreateRequest(
Lily Chen3ac7cf42019-05-30 23:29:298556 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8557 req->set_site_for_cookies(test_url);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548558 req->Start();
8559 d.RunUntilComplete();
8560
8561 ASSERT_EQ(1u, req->not_stored_cookies().size());
8562 EXPECT_EQ("not_stored_cookie",
8563 req->not_stored_cookies().front().cookie->Name());
8564 EXPECT_EQ(
8565 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
8566 req->not_stored_cookies().front().status);
8567 }
8568 // Set a cookie to be blocked later
8569 {
8570 TestDelegate d;
Lily Chen3ac7cf42019-05-30 23:29:298571 GURL test_url = test_server.GetURL("/set-cookie?not_sent_cookies=true");
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548572 std::unique_ptr<URLRequest> req(context.CreateRequest(
Lily Chen3ac7cf42019-05-30 23:29:298573 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8574 req->set_site_for_cookies(test_url);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548575 req->Start();
8576 d.RunUntilComplete();
8577 }
8578 {
8579 TestDelegate d;
8580 // Make sure cookies blocked from being sent are caught.
Lily Chen3ac7cf42019-05-30 23:29:298581 GURL test_url = test_server.GetURL("/echoheader?Cookie");
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548582 std::unique_ptr<URLRequest> req(context.CreateRequest(
Lily Chen3ac7cf42019-05-30 23:29:298583 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8584 req->set_site_for_cookies(test_url);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548585 req->Start();
8586 d.RunUntilComplete();
8587
8588 EXPECT_TRUE(d.data_received().find("not_sent_cookies=true") ==
8589 std::string::npos);
8590
8591 ASSERT_EQ(1u, req->not_sent_cookies().size());
8592 EXPECT_EQ("not_sent_cookies",
8593 req->not_sent_cookies().front().cookie.Name());
8594 EXPECT_EQ(
8595 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
8596 req->not_sent_cookies().front().status);
8597 }
8598}
8599
8600TEST_F(URLRequestTestHTTP, AuthChallengeWithFilteredCookies) {
Aaron Tagliaboschi028009e2019-03-07 16:28:068601 ASSERT_TRUE(http_test_server()->Start());
8602
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548603 GURL url_requiring_auth =
8604 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
8605 GURL url_requiring_auth_wo_cookies =
8606 http_test_server()->GetURL("/auth-basic");
8607 // Check not_stored_cookies is populated first round trip, and cleared on the
8608 // second.
8609 {
8610 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8611 std::make_unique<TestNetworkDelegate>());
8612 filtering_network_delegate.SetCookieFilter("got_challenged");
8613 TestURLRequestContext context(true);
8614 context.set_network_delegate(&filtering_network_delegate);
8615 context.Init();
Aaron Tagliaboschi028009e2019-03-07 16:28:068616
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548617 TestDelegate delegate;
Aaron Tagliaboschi028009e2019-03-07 16:28:068618
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548619 std::unique_ptr<URLRequest> request(
8620 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &delegate,
8621 TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298622 request->set_site_for_cookies(url_requiring_auth);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548623 request->Start();
Aaron Tagliaboschi028009e2019-03-07 16:28:068624
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548625 delegate.RunUntilAuthRequired();
8626 // Make sure it was blocked once.
8627 EXPECT_EQ(1, filtering_network_delegate.blocked_set_cookie_count());
Aaron Tagliaboschi028009e2019-03-07 16:28:068628
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548629 // The number of cookies blocked from the most recent round trip.
8630 ASSERT_EQ(1u, request->not_stored_cookies().size());
Aaron Tagliaboschi028009e2019-03-07 16:28:068631
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548632 // Now check the second round trip
8633 request->SetAuth(AuthCredentials(kUser, kSecret));
8634 delegate.RunUntilComplete();
8635 EXPECT_THAT(delegate.request_status(), IsOk());
Aaron Tagliaboschi028009e2019-03-07 16:28:068636
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548637 // There are DCHECKs in URLRequestHttpJob that would fail if
8638 // not_sent_cookies and not_stored_cookies were not cleared properly.
8639
8640 // Make sure the cookie was actually filtered and not sent.
8641 EXPECT_EQ(std::string::npos,
8642 delegate.data_received().find("Cookie: got_challenged=true"));
8643
8644 // The number of cookies blocked from the most recent round trip.
8645 ASSERT_EQ(0u, request->not_stored_cookies().size());
8646 }
8647
8648 // Check not_sent_cookies on first round trip (and cleared for the second).
8649 {
8650 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8651 std::make_unique<TestNetworkDelegate>());
8652 filtering_network_delegate.set_block_get_cookies();
8653 TestURLRequestContext context(true);
8654 context.set_network_delegate(&filtering_network_delegate);
8655
8656 std::unique_ptr<CookieMonster> cm =
8657 std::make_unique<CookieMonster>(nullptr, nullptr);
8658 cm->SetCookieWithOptionsAsync(url_requiring_auth_wo_cookies,
8659 "another_cookie=true", CookieOptions(),
8660 CookieStore::SetCookiesCallback());
8661 context.set_cookie_store(cm.get());
8662 context.Init();
8663
8664 TestDelegate delegate;
8665
8666 std::unique_ptr<URLRequest> request(
8667 context.CreateRequest(url_requiring_auth_wo_cookies, DEFAULT_PRIORITY,
8668 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298669 request->set_site_for_cookies(url_requiring_auth_wo_cookies);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548670 request->Start();
8671
8672 delegate.RunUntilAuthRequired();
8673
8674 ASSERT_EQ(1u, request->not_sent_cookies().size());
8675 EXPECT_EQ("another_cookie",
8676 request->not_sent_cookies().front().cookie.Name());
8677 EXPECT_EQ("true", request->not_sent_cookies().front().cookie.Value());
8678
8679 // Check not_sent_cookies on second roundtrip.
8680 request->set_not_sent_cookies({});
8681 cm->DeleteAllAsync(CookieStore::DeleteCallback());
8682 cm->SetCookieWithOptionsAsync(url_requiring_auth_wo_cookies,
8683 "one_more_cookie=true", CookieOptions(),
8684 CookieStore::SetCookiesCallback());
8685
8686 request->SetAuth(AuthCredentials(kUser, kSecret));
8687 delegate.RunUntilComplete();
8688 EXPECT_THAT(delegate.request_status(), IsOk());
8689
8690 // There are DCHECKs in URLRequestHttpJob that would fail if
8691 // not_sent_cookies and not_stored_cookies we not cleared properly.
8692
8693 // Make sure the cookie was actually filtered.
8694 EXPECT_EQ(std::string::npos,
8695 delegate.data_received().find("Cookie: one_more_cookie=true"));
8696 // got_challenged was set after the first request and blocked on the second,
8697 // so it should only have been blocked this time
8698 EXPECT_EQ(2, filtering_network_delegate.blocked_get_cookie_count());
8699
8700 // // The number of cookies blocked from the most recent round trip.
8701 ASSERT_EQ(1u, request->not_sent_cookies().size());
8702 EXPECT_EQ("one_more_cookie",
8703 request->not_sent_cookies().front().cookie.Name());
8704 }
Aaron Tagliaboschi028009e2019-03-07 16:28:068705}
8706
[email protected]58e32bb2013-01-21 18:23:258707// Tests that load timing works as expected with auth and the cache.
8708TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:558709 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:258710
8711 // populate the cache
8712 {
8713 TestDelegate d;
8714 d.set_credentials(AuthCredentials(kUser, kSecret));
8715
Ryan Sleevib8449e02018-07-15 04:31:078716 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168717 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8718 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198719 r->Start();
[email protected]58e32bb2013-01-21 18:23:258720
Wez2a31b222018-06-07 22:07:158721 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258722
8723 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8724
8725 LoadTimingInfo load_timing_info_before_auth;
8726 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
8727 &load_timing_info_before_auth));
8728 TestLoadTimingNotReused(load_timing_info_before_auth,
8729 CONNECT_TIMING_HAS_DNS_TIMES);
8730
8731 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198732 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:258733 // The test server does not support keep alive sockets, so the second
8734 // request with auth should use a new socket.
8735 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
8736 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
8737 load_timing_info.socket_log_id);
8738 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
8739 load_timing_info.connect_timing.connect_start);
8740 }
8741
[email protected]3b23a222013-05-15 21:33:258742 // Repeat request with end-to-end validation. Since auth-basic results in a
8743 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258744 // response should be fetched from the cache.
8745 {
8746 TestDelegate d;
8747 d.set_credentials(AuthCredentials(kUser, kSecret));
8748
Ryan Sleevib8449e02018-07-15 04:31:078749 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168750 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8751 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198752 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8753 r->Start();
[email protected]58e32bb2013-01-21 18:23:258754
Wez2a31b222018-06-07 22:07:158755 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258756
8757 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8758
8759 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198760 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258761
[email protected]3b23a222013-05-15 21:33:258762 // Since there was a request that went over the wire, the load timing
8763 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258764 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198765 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258766 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258767 }
8768}
8769
[email protected]316c1e5e2012-09-12 15:17:448770// In this test, we do a POST which the server will 302 redirect.
8771// The subsequent transaction should use GET, and should not send the
8772// Content-Type header.
8773// http://code.google.com/p/chromium/issues/detail?id=843
8774TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558775 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448776
8777 const char kData[] = "hello world";
8778
8779 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078780 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168781 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8782 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198783 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078784 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448785
8786 // Set headers (some of which are specific to the POST).
8787 HttpRequestHeaders headers;
Yeol45b9e0a2018-07-27 02:03:298788 headers.SetHeader("Content-Type",
8789 "multipart/form-data;"
8790 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ");
8791 headers.SetHeader("Accept",
8792 "text/xml,application/xml,application/xhtml+xml,"
8793 "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
8794 headers.SetHeader("Accept-Language", "en-US,en");
8795 headers.SetHeader("Accept-Charset", "ISO-8859-1,*,utf-8");
8796 headers.SetHeader("Content-Length", "11");
8797 headers.SetHeader("Origin", "http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198798 req->SetExtraRequestHeaders(headers);
8799 req->Start();
Wez2a31b222018-06-07 22:07:158800 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448801
8802 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198803 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448804 EXPECT_EQ("text/html", mime_type);
8805
8806 const std::string& data = d.data_received();
8807
8808 // Check that the post-specific headers were stripped:
8809 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8810 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498811 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448812
8813 // These extra request headers should not have been stripped.
8814 EXPECT_TRUE(ContainsString(data, "Accept:"));
8815 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8816 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8817}
8818
jww5fe460ff2015-03-28 00:22:518819// The following tests check that we handle mutating the request for HTTP
8820// redirects as expected.
8821// See https://crbug.com/56373, https://crbug.com/102130, and
8822// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448823
8824TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558825 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448826
tommycli59a63432015-11-06 00:10:558827 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518828 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558829 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448830
8831 HTTPRedirectMethodTest(url, "POST", "GET", true);
8832 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8833 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518834
8835 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8836 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498837 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8838 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8839 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408840 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8841 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448842}
8843
8844TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558845 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448846
tommycli59a63432015-11-06 00:10:558847 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518848 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558849 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448850
8851 HTTPRedirectMethodTest(url, "POST", "GET", true);
8852 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8853 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518854
8855 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8856 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498857 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8858 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8859 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408860 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8861 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448862}
8863
8864TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558865 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448866
tommycli59a63432015-11-06 00:10:558867 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518868 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558869 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448870
8871 HTTPRedirectMethodTest(url, "POST", "GET", true);
8872 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8873 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518874
Alex Clarke1e08882b32017-10-06 14:22:408875 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8876 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8877 std::string());
8878 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8879 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8880 std::string());
jww5fe460ff2015-03-28 00:22:518881 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8882 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408883 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8884 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8885 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8886 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8887 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498888 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8889 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8890 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408891 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
8892 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:448893}
8894
8895TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558896 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448897
tommycli59a63432015-11-06 00:10:558898 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518899 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558900 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448901
8902 HTTPRedirectMethodTest(url, "POST", "POST", true);
8903 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8904 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518905
8906 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8907 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8908 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8909 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408910 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8911 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448912}
8913
[email protected]0a17aab32014-04-24 03:32:378914TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558915 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378916
tommycli59a63432015-11-06 00:10:558917 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518918 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558919 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378920
8921 HTTPRedirectMethodTest(url, "POST", "POST", true);
8922 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8923 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518924
8925 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8926 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8927 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8928 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408929 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8930 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:378931}
8932
8933// Make sure that 308 responses without bodies are not treated as redirects.
8934// Certain legacy apis that pre-date the response code expect this behavior
8935// (Like Google Drive).
8936TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558937 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378938
8939 TestDelegate d;
tommycli59a63432015-11-06 00:10:558940 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378941
Ryan Sleevib8449e02018-07-15 04:31:078942 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168943 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378944
[email protected]f7022f32014-08-21 16:32:198945 request->Start();
Wez2a31b222018-06-07 22:07:158946 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:508947 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378948 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198949 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378950 EXPECT_EQ("This is not a redirect.", d.data_received());
8951}
8952
[email protected]f878230e2014-04-03 15:36:148953TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558954 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148955
tommycli59a63432015-11-06 00:10:558956 GURL original_url(
8957 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8958 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148959
8960 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:148961 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
8962 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148963
Josh Karlinbe37f912018-12-07 01:05:148964 r->Start();
8965 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148966
Josh Karlinbe37f912018-12-07 01:05:148967 EXPECT_EQ(2U, r->url_chain().size());
8968 EXPECT_EQ(OK, d.request_status());
8969 EXPECT_EQ(original_url, r->original_url());
8970 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148971}
8972
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548973TEST_F(URLRequestTestHTTP, RedirectWithFilteredCookies) {
8974 ASSERT_TRUE(http_test_server()->Start());
8975
8976 // FilteringTestLayeredNetworkDelegate filters by name, so the names of the
8977 // two cookies have to be the same. The values have been set to different
8978 // strings (the value of the server-redirect cookies is "true" and set-cookie
8979 // is "other") to differentiate between the two round trips.
8980 GURL redirect_to(
8981 http_test_server()->GetURL("/set-cookie?server-redirect=other"));
8982
8983 GURL original_url(http_test_server()->GetURL("/server-redirect-with-cookie?" +
8984 redirect_to.spec()));
8985
8986 GURL original_url_wo_cookie(
8987 http_test_server()->GetURL("/server-redirect?" + redirect_to.spec()));
8988 // Check not_stored_cookies on first round trip.
8989 {
8990 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8991 std::make_unique<TestNetworkDelegate>()); // Must outlive URLRequest.
8992 filtering_network_delegate.SetCookieFilter(
8993 "server-redirect"); // Filter the cookie server-redirect sets.
8994 TestURLRequestContext context(true);
8995 context.set_network_delegate(&filtering_network_delegate);
8996 context.Init();
8997
8998 TestDelegate delegate;
8999 std::unique_ptr<URLRequest> request(
9000 context.CreateRequest(original_url, DEFAULT_PRIORITY, &delegate,
9001 TRAFFIC_ANNOTATION_FOR_TESTS));
9002
Lily Chen3ac7cf42019-05-30 23:29:299003 request->set_site_for_cookies(original_url);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549004 request->Start();
9005 delegate.RunUntilRedirect();
9006
9007 // Make sure it was blocked once.
9008 EXPECT_EQ(1, filtering_network_delegate.blocked_set_cookie_count());
9009
9010 // The number of cookies blocked from the most recent round trip.
9011 ASSERT_EQ(1u, request->not_stored_cookies().size());
9012 EXPECT_EQ("server-redirect",
9013 request->not_stored_cookies().front().cookie->Name());
9014 EXPECT_EQ("true", request->not_stored_cookies().front().cookie->Value());
9015
9016 // Check not_stored_cookies on second round trip (and clearing from the
9017 // first).
9018 request->FollowDeferredRedirect(base::nullopt, base::nullopt);
9019 delegate.RunUntilComplete();
9020 EXPECT_THAT(delegate.request_status(), IsOk());
9021
9022 // There are DCHECKs in URLRequestHttpJob that would fail if
9023 // not_sent_cookies and not_stored_cookies we not cleared properly.
9024
9025 // Make sure it was blocked twice.
9026 EXPECT_EQ(2, filtering_network_delegate.blocked_set_cookie_count());
9027
9028 // The number of cookies blocked from the most recent round trip.
9029 ASSERT_EQ(1u, request->not_stored_cookies().size());
9030 EXPECT_EQ("server-redirect",
9031 request->not_stored_cookies().front().cookie->Name());
9032 EXPECT_EQ("other", request->not_stored_cookies().front().cookie->Value());
9033 }
9034
9035 // Check not_sent_cookies on first round trip.
9036 {
9037 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
9038 std::make_unique<TestNetworkDelegate>());
9039 filtering_network_delegate.set_block_get_cookies();
9040 TestURLRequestContext context(true);
9041 context.set_network_delegate(&filtering_network_delegate);
9042 std::unique_ptr<CookieMonster> cm =
9043 std::make_unique<CookieMonster>(nullptr, nullptr);
9044 cm->SetCookieWithOptionsAsync(original_url, "another_cookie=true",
9045 CookieOptions(),
9046 CookieStore::SetCookiesCallback());
9047 context.set_cookie_store(cm.get());
9048 context.Init();
9049
9050 TestDelegate delegate;
9051 std::unique_ptr<URLRequest> request(
9052 context.CreateRequest(original_url_wo_cookie, DEFAULT_PRIORITY,
9053 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
9054
Lily Chen3ac7cf42019-05-30 23:29:299055 request->set_site_for_cookies(original_url_wo_cookie);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549056 request->Start();
9057
9058 delegate.RunUntilRedirect();
9059
9060 ASSERT_EQ(1u, request->not_sent_cookies().size());
9061 EXPECT_EQ("another_cookie",
9062 request->not_sent_cookies().front().cookie.Name());
9063
9064 // Check not_sent_cookies on second round trip
9065 request->set_not_sent_cookies({});
9066 cm->DeleteAllAsync(CookieStore::DeleteCallback());
9067 cm->SetCookieWithOptionsAsync(original_url_wo_cookie,
9068 "one_more_cookie=true", CookieOptions(),
9069 CookieStore::SetCookiesCallback());
9070
9071 request->FollowDeferredRedirect(base::nullopt, base::nullopt);
9072 delegate.RunUntilComplete();
9073 EXPECT_THAT(delegate.request_status(), IsOk());
9074
9075 // There are DCHECKs in URLRequestHttpJob that would fail if
9076 // not_sent_cookies and not_stored_cookies we not cleared properly.
9077
9078 EXPECT_EQ(2, filtering_network_delegate.blocked_get_cookie_count());
9079
9080 // The number of cookies blocked from the most recent round trip.
9081 ASSERT_EQ(1u, request->not_sent_cookies().size());
9082 EXPECT_EQ("one_more_cookie",
9083 request->not_sent_cookies().front().cookie.Name());
9084 EXPECT_EQ("true", request->not_sent_cookies().front().cookie.Value());
9085 }
9086}
9087
[email protected]cba24642014-08-15 20:49:599088TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:559089 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:599090
tommycli59a63432015-11-06 00:10:559091 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:599092 GURL first_party_url("http://example.com");
9093
9094 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:149095 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9096 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9097 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:599098
Josh Karlinbe37f912018-12-07 01:05:149099 r->Start();
9100 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:599101
Josh Karlinbe37f912018-12-07 01:05:149102 EXPECT_EQ(2U, r->url_chain().size());
9103 EXPECT_EQ(OK, d.request_status());
9104 EXPECT_EQ(first_party_url, r->site_for_cookies());
9105}
9106
9107TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameOrigin) {
9108 ASSERT_TRUE(http_test_server()->Start());
9109
9110 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9111 url::Origin top_frame_origin =
9112 url::Origin::Create(GURL("http://example.com"));
9113 TestDelegate d;
9114
9115 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9116 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9117 r->set_top_frame_origin(top_frame_origin);
9118
9119 r->Start();
9120 d.RunUntilComplete();
9121
9122 EXPECT_EQ(2U, r->url_chain().size());
9123 EXPECT_EQ(OK, d.request_status());
9124 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
9125}
9126
9127TEST_F(URLRequestTestHTTP, RedirectPreserveUnsetTopFrameOrigin) {
9128 ASSERT_TRUE(http_test_server()->Start());
9129
9130 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9131 TestDelegate d;
9132
9133 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9134 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9135 // Since we're not setting a top frame origin, we wouldn't expect one after
9136 // the redirect.
9137 r->Start();
9138 d.RunUntilComplete();
9139
9140 EXPECT_EQ(2U, r->url_chain().size());
9141 EXPECT_EQ(OK, d.request_status());
9142 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:599143}
9144
Josh Karlinf3caee1642018-12-10 22:54:279145TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameURL) {
9146 ASSERT_TRUE(http_test_server()->Start());
9147
9148 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9149 url::Origin top_frame_origin =
9150 url::Origin::Create(GURL("http://example.com"));
9151 TestDelegate d;
9152 {
9153 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9154 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9155 r->set_top_frame_origin(top_frame_origin);
9156
9157 r->Start();
9158 d.RunUntilComplete();
9159
9160 EXPECT_EQ(2U, r->url_chain().size());
9161 EXPECT_EQ(OK, d.request_status());
9162 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
9163 }
9164}
9165
[email protected]cba24642014-08-15 20:49:599166TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:559167 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:599168
tommycli59a63432015-11-06 00:10:559169 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:599170 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:559171 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:599172
9173 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:149174
Ryan Sleevib8449e02018-07-15 04:31:079175 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169176 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:469177 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:199178 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:599179 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
9180
[email protected]f7022f32014-08-21 16:32:199181 r->Start();
Wez2a31b222018-06-07 22:07:159182 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:599183
[email protected]f7022f32014-08-21 16:32:199184 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:509185 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:469186 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
Josh Karlinbe37f912018-12-07 01:05:149187}
9188
9189TEST_F(URLRequestTestHTTP, RedirectUpdateTopFrameOrigin) {
9190 ASSERT_TRUE(http_test_server()->Start());
9191
9192 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9193 url::Origin original_top_frame_origin =
9194 url::Origin::Create(GURL("http://example.com"));
9195 url::Origin expected_top_frame_origin =
9196 url::Origin::Create(GURL(http_test_server()->GetURL("/echo")));
9197
9198 TestDelegate d;
9199
9200 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9201 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9202 r->set_top_frame_origin(original_top_frame_origin);
9203 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
9204
9205 r->Start();
9206 d.RunUntilComplete();
9207
9208 EXPECT_EQ(2U, r->url_chain().size());
9209 EXPECT_EQ(OK, d.request_status());
9210 EXPECT_EQ(expected_top_frame_origin, *r->top_frame_origin());
9211}
9212
9213TEST_F(URLRequestTestHTTP, RedirectIgnoreUnsetTopFrameOrigin) {
9214 ASSERT_TRUE(http_test_server()->Start());
9215
9216 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9217 TestDelegate d;
9218
9219 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9220 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9221 // Since we're not setting a top frame origin, we wouldn't expect one after
9222 // the redirect.
9223 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
9224
9225 r->Start();
9226 d.RunUntilComplete();
9227
9228 EXPECT_EQ(2U, r->url_chain().size());
9229 EXPECT_EQ(OK, d.request_status());
9230 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:599231}
9232
[email protected]316c1e5e2012-09-12 15:17:449233TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:559234 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449235
9236 const char kData[] = "hello world";
9237
9238 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079239 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169240 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9241 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199242 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079243 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:449244 HttpRequestHeaders headers;
9245 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:249246 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:199247 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:449248
danakj8522a25b2016-04-16 00:17:369249 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559250 req.get(), &default_network_delegate_,
9251 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429252 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9253 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:449254
[email protected]f7022f32014-08-21 16:32:199255 req->Start();
Wez2a31b222018-06-07 22:07:159256 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:199257 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:449258}
9259
9260TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:559261 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449262
9263 const char kData[] = "hello world";
9264
9265 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079266 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169267 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9268 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199269 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079270 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:449271 HttpRequestHeaders headers;
9272 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:249273 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:199274 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:449275
danakj8522a25b2016-04-16 00:17:369276 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559277 req.get(), &default_network_delegate_,
9278 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:099279 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:429280 "Very Good Reason"));
9281 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:449282
[email protected]f7022f32014-08-21 16:32:199283 req->Start();
Wez2a31b222018-06-07 22:07:159284 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:199285 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:449286 EXPECT_EQ(kData, d.data_received());
9287}
9288
9289// Check that default A-L header is sent.
9290TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559291 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449292
[email protected]8790210c2013-12-02 05:29:539293 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:249294 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:449295 TestURLRequestContext context(true);
9296 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:439297 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:449298 context.Init();
9299
9300 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369301 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:559302 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169303 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199304 req->Start();
Wez2a31b222018-06-07 22:07:159305 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449306 EXPECT_EQ("en", d.data_received());
9307}
9308
9309// Check that an empty A-L header is not sent. http://crbug.com/77365.
9310TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559311 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449312
[email protected]8790210c2013-12-02 05:29:539313 std::string empty_string; // Avoid most vexing parse on line below.
9314 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:249315 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:449316 TestURLRequestContext context(true);
9317 context.set_network_delegate(&network_delegate);
9318 context.Init();
9319 // We override the language after initialization because empty entries
9320 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:439321 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:449322
9323 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369324 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:559325 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169326 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199327 req->Start();
Wez2a31b222018-06-07 22:07:159328 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449329 EXPECT_EQ("None", d.data_received());
9330}
9331
9332// Check that if request overrides the A-L header, the default is not appended.
9333// See http://crbug.com/20894
9334TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559335 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449336
9337 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079338 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559339 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169340 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449341 HttpRequestHeaders headers;
9342 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:199343 req->SetExtraRequestHeaders(headers);
9344 req->Start();
Wez2a31b222018-06-07 22:07:159345 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449346 EXPECT_EQ(std::string("ru"), d.data_received());
9347}
9348
9349// Check that default A-E header is sent.
9350TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559351 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449352
9353 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079354 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559355 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169356 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449357 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:199358 req->SetExtraRequestHeaders(headers);
9359 req->Start();
Wez2a31b222018-06-07 22:07:159360 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449361 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
9362}
9363
9364// Check that if request overrides the A-E header, the default is not appended.
9365// See http://crbug.com/47381
9366TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559367 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449368
9369 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079370 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559371 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169372 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449373 HttpRequestHeaders headers;
9374 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:199375 req->SetExtraRequestHeaders(headers);
9376 req->Start();
Wez2a31b222018-06-07 22:07:159377 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449378 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
9379 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
9380}
9381
[email protected]84f05432013-03-15 01:00:129382// Check that setting the A-C header sends the proper header.
9383TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:559384 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449385
9386 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079387 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559388 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:169389 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449390 HttpRequestHeaders headers;
9391 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:199392 req->SetExtraRequestHeaders(headers);
9393 req->Start();
Wez2a31b222018-06-07 22:07:159394 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449395 EXPECT_EQ(std::string("koi-8r"), d.data_received());
9396}
9397
9398// Check that default User-Agent header is sent.
9399TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:559400 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449401
9402 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079403 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559404 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169405 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199406 req->Start();
Wez2a31b222018-06-07 22:07:159407 d.RunUntilComplete();
Ryan Sleevib8449e02018-07-15 04:31:079408 EXPECT_EQ(default_context().http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:379409 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449410}
9411
9412// Check that if request overrides the User-Agent header,
9413// the default is not appended.
marqf14fff8d2015-12-02 15:52:299414// TODO(crbug.com/564656) This test is flaky on iOS.
9415#if defined(OS_IOS)
9416#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
9417#else
9418#define MAYBE_OverrideUserAgent OverrideUserAgent
9419#endif
9420TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:559421 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449422
9423 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079424 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559425 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169426 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449427 HttpRequestHeaders headers;
9428 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:199429 req->SetExtraRequestHeaders(headers);
9430 req->Start();
Wez2a31b222018-06-07 22:07:159431 d.RunUntilComplete();
[email protected]cd6f2522014-01-16 18:27:359432 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449433}
9434
[email protected]ee4c30d2012-11-07 15:08:439435// Check that a NULL HttpUserAgentSettings causes the corresponding empty
9436// User-Agent header to be sent but does not send the Accept-Language and
9437// Accept-Charset headers.
9438TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:559439 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:439440
[email protected]ceefd7fd2012-11-29 00:36:249441 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:439442 TestURLRequestContext context(true);
9443 context.set_network_delegate(&network_delegate);
9444 context.Init();
9445 // We override the HttpUserAgentSettings after initialization because empty
9446 // entries get overridden by Init().
Raul Tambre94493c652019-03-11 17:18:359447 context.set_http_user_agent_settings(nullptr);
[email protected]ee4c30d2012-11-07 15:08:439448
9449 struct {
9450 const char* request;
9451 const char* expected_response;
tommycli59a63432015-11-06 00:10:559452 } tests[] = {{"/echoheader?Accept-Language", "None"},
9453 {"/echoheader?Accept-Charset", "None"},
9454 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:439455
Avi Drissman4365a4782018-12-28 19:26:249456 for (size_t i = 0; i < base::size(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:439457 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369458 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169459 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
9460 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199461 req->Start();
Wez2a31b222018-06-07 22:07:159462 d.RunUntilComplete();
[email protected]ee4c30d2012-11-07 15:08:439463 EXPECT_EQ(tests[i].expected_response, d.data_received())
9464 << " Request = \"" << tests[i].request << "\"";
9465 }
9466}
9467
[email protected]5033ab82013-03-22 20:17:469468// Make sure that URLRequest passes on its priority updates to
9469// newly-created jobs after the first one.
9470TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:559471 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:469472
9473 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079474 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169475 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9476 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199477 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:469478
danakj8522a25b2016-04-16 00:17:369479 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559480 req.get(), &default_network_delegate_,
9481 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429482 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9483 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:469484
[email protected]f7022f32014-08-21 16:32:199485 req->SetPriority(LOW);
9486 req->Start();
9487 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:469488
mmenkeed0498b2015-12-08 23:20:429489 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:369490 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:429491 req.get(), &default_network_delegate_, &job_priority));
9492 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:469493
9494 // Should trigger |job| to be started.
Wez2a31b222018-06-07 22:07:159495 d.RunUntilComplete();
mmenkeed0498b2015-12-08 23:20:429496 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:469497}
9498
[email protected]80abdad2014-03-15 00:20:549499// Check that creating a network request while entering/exiting suspend mode
9500// fails as it should. This is the only case where an HttpTransactionFactory
9501// does not return an HttpTransaction.
9502TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
9503 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:369504 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
Ryan Sleevib8449e02018-07-15 04:31:079505 default_context().http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:549506 network_layer->OnSuspend();
9507
dchengc7eeda422015-12-26 03:56:489508 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:039509 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:279510 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:549511
9512 TestURLRequestContext context(true);
9513 context.set_http_transaction_factory(&http_cache);
9514 context.Init();
9515
9516 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369517 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169518 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9519 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199520 req->Start();
Wez2a31b222018-06-07 22:07:159521 d.RunUntilComplete();
[email protected]80abdad2014-03-15 00:20:549522
9523 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:509524 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:549525}
9526
mmenke2281f3762015-11-02 20:38:179527namespace {
[email protected]80abdad2014-03-15 00:20:549528
mmenke2281f3762015-11-02 20:38:179529// HttpTransactionFactory that synchronously fails to create transactions.
9530class FailingHttpTransactionFactory : public HttpTransactionFactory {
9531 public:
9532 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
9533 : network_session_(network_session) {}
9534
Chris Watkins7a41d3552017-12-01 02:13:279535 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:179536
9537 // HttpTransactionFactory methods:
9538 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:369539 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:179540 return ERR_FAILED;
9541 }
9542
9543 HttpCache* GetCache() override { return nullptr; }
9544
9545 HttpNetworkSession* GetSession() override { return network_session_; }
9546
9547 private:
9548 HttpNetworkSession* network_session_;
9549
9550 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
9551};
9552
9553} // namespace
9554
9555// Check that when a request that fails to create an HttpTransaction can be
9556// cancelled while the failure notification is pending, and doesn't send two
9557// failure notifications.
9558//
9559// This currently only happens when in suspend mode and there's no cache, but
9560// just use a special HttpTransactionFactory, to avoid depending on those
9561// behaviors.
9562TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
9563 FailingHttpTransactionFactory http_transaction_factory(
Ryan Sleevib8449e02018-07-15 04:31:079564 default_context().http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:549565 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:179566 context.set_http_transaction_factory(&http_transaction_factory);
9567 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:549568 context.Init();
9569
9570 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369571 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169572 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9573 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:179574 // Don't send cookies (Collecting cookies is asynchronous, and need request to
9575 // try to create an HttpNetworkTransaction synchronously on start).
9576 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:199577 req->Start();
mmenke2281f3762015-11-02 20:38:179578 req->Cancel();
Wez2a31b222018-06-07 22:07:159579 d.RunUntilComplete();
mmenke2281f3762015-11-02 20:38:179580 // Run pending error task, if there is one.
9581 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:549582
9583 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:179584 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509585 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:179586
9587 // NetworkDelegate should see the cancellation, but not the error.
9588 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
9589 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:549590}
9591
ttuttlec0c828492015-05-15 01:25:559592TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:559593 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559594
9595 TestDelegate d;
tommycli59a63432015-11-06 00:10:559596 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079597 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169598 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559599
9600 req->Start();
Wez2a31b222018-06-07 22:07:159601 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559602
9603 EXPECT_TRUE(req->response_info().network_accessed);
9604}
9605
9606TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:559607 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559608
9609 // Populate the cache.
9610 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079611 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169612 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9613 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559614 req->Start();
Wez2a31b222018-06-07 22:07:159615 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559616
maksim.sisovb53724b52016-09-16 05:30:509617 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559618 EXPECT_TRUE(req->response_info().network_accessed);
9619 EXPECT_FALSE(req->response_info().was_cached);
9620
Ryan Sleevib8449e02018-07-15 04:31:079621 req = default_context().CreateRequest(
9622 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9623 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:559624 req->Start();
Wez2a31b222018-06-07 22:07:159625 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559626
maksim.sisovb53724b52016-09-16 05:30:509627 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559628 EXPECT_FALSE(req->response_info().network_accessed);
9629 EXPECT_TRUE(req->response_info().was_cached);
9630}
9631
9632TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:559633 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559634
9635 TestDelegate d;
tommycli59a63432015-11-06 00:10:559636 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079637 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169638 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:339639 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:559640
9641 req->Start();
Wez2a31b222018-06-07 22:07:159642 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559643
9644 EXPECT_FALSE(req->response_info().network_accessed);
9645}
9646
rdsmithbf8c3c12016-11-18 18:16:249647// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:089648// correctly in the absence of contention.
9649TEST_F(URLRequestTestHTTP, ThrottledPriority) {
9650 ASSERT_TRUE(http_test_server()->Start());
9651
9652 TestDelegate d;
9653 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079654 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169655 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:089656 req->Start();
Wez2a31b222018-06-07 22:07:159657 d.RunUntilComplete();
rdsmith5eb6fbc2016-10-21 17:36:089658
9659 EXPECT_TRUE(req->status().is_success());
9660}
9661
ricea3a1c71f2016-06-17 10:05:269662TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
9663 ASSERT_TRUE(http_test_server()->Start());
9664
9665 TestDelegate d;
9666 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169667 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9668 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269669 req->Start();
Wez2a31b222018-06-07 22:07:159670 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269671
9672 EXPECT_EQ(5, req->GetRawBodyBytes());
9673}
9674
9675TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
9676 ASSERT_TRUE(http_test_server()->Start());
9677
9678 TestDelegate d;
9679 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169680 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
9681 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269682 req->Start();
Wez2a31b222018-06-07 22:07:159683 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269684
9685 EXPECT_EQ(30, req->GetRawBodyBytes());
9686}
9687
jamd3f5a3c2016-10-27 18:52:029688// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
9689// the delegate isn't called back synchronously.
9690TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
9691 ASSERT_TRUE(http_test_server()->Start());
9692 default_network_delegate_.set_before_start_transaction_fails();
9693
9694 TestDelegate d;
9695 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169696 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
9697 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:029698 req->Start();
9699 DCHECK(!d.response_completed());
Wez2a31b222018-06-07 22:07:159700 d.RunUntilComplete();
jamd3f5a3c2016-10-27 18:52:029701 DCHECK(d.response_completed());
9702 EXPECT_EQ(ERR_FAILED, d.request_status());
9703}
9704
bengr1bf8e942014-11-07 01:36:509705class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9706 public:
9707 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9708 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9709 // tests into the factory tests.
Raul Tambre94493c652019-03-11 17:18:359710 URLRequestInterceptorTestHTTP()
9711 : URLRequestTestHTTP(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:509712
9713 void SetUpFactory() override {
9714 interceptor_ = new MockURLRequestInterceptor();
9715 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369716 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509717 }
9718
9719 MockURLRequestInterceptor* interceptor() const {
9720 return interceptor_;
9721 }
9722
9723 private:
9724 MockURLRequestInterceptor* interceptor_;
9725};
9726
9727TEST_F(URLRequestInterceptorTestHTTP,
9728 NetworkDelegateNotificationOnRedirectIntercept) {
9729 interceptor()->set_intercept_redirect(true);
9730 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9731 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9732
tommycli59a63432015-11-06 00:10:559733 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509734
9735 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369736 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169737 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9738 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509739 req->Start();
Wez2a31b222018-06-07 22:07:159740 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509741
9742 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9743 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509744 int status = d.request_status();
9745 EXPECT_EQ(OK, status);
9746 if (status == OK)
bengr1bf8e942014-11-07 01:36:509747 EXPECT_EQ(200, req->response_headers()->response_code());
9748
9749 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9750 EXPECT_EQ(1, d.response_started_count());
9751 EXPECT_EQ(0, d.received_redirect_count());
9752
9753 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009754 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509755 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9756}
9757
9758TEST_F(URLRequestInterceptorTestHTTP,
9759 NetworkDelegateNotificationOnErrorIntercept) {
9760 // Intercept that error and respond with an OK response.
9761 interceptor()->set_intercept_final_response(true);
9762 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9763 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9764 default_network_delegate()->set_can_be_intercepted_on_error(true);
9765
tommycli59a63432015-11-06 00:10:559766 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509767
9768 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369769 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559770 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169771 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509772 req->set_method("GET");
9773 req->Start();
Wez2a31b222018-06-07 22:07:159774 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509775
9776 EXPECT_TRUE(interceptor()->did_intercept_final());
9777
9778 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509779 int status = d.request_status();
9780 EXPECT_EQ(OK, status);
9781 if (status == OK)
bengr1bf8e942014-11-07 01:36:509782 EXPECT_EQ(200, req->response_headers()->response_code());
9783 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9784 EXPECT_EQ(1, d.response_started_count());
9785 EXPECT_EQ(0, d.received_redirect_count());
9786
9787 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009788 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509789 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9790}
9791
9792TEST_F(URLRequestInterceptorTestHTTP,
9793 NetworkDelegateNotificationOnResponseIntercept) {
9794 // Intercept that error and respond with an OK response.
9795 interceptor()->set_intercept_final_response(true);
9796
9797 // Intercept with a real URLRequestHttpJob.
9798 interceptor()->set_use_url_request_http_job(true);
9799
tommycli59a63432015-11-06 00:10:559800 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509801
9802 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369803 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169804 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9805 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509806 req->set_method("GET");
9807 req->Start();
Wez2a31b222018-06-07 22:07:159808 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509809
9810 EXPECT_TRUE(interceptor()->did_intercept_final());
9811
9812 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509813 int status = d.request_status();
9814 EXPECT_EQ(OK, status);
9815 if (status == OK)
bengr1bf8e942014-11-07 01:36:509816 EXPECT_EQ(200, req->response_headers()->response_code());
9817 EXPECT_EQ("hello", d.data_received());
9818 EXPECT_EQ(1, d.response_started_count());
9819 EXPECT_EQ(0, d.received_redirect_count());
9820
9821 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009822 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509823 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9824}
9825
mkwst0c5eab872014-11-21 14:18:549826class URLRequestTestReferrerPolicy : public URLRequestTest {
9827 public:
Chris Watkins7a41d3552017-12-01 02:13:279828 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:549829
tommycli59a63432015-11-06 00:10:559830 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9831 origin_server_.reset(new EmbeddedTestServer(type));
9832 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9833 origin_server_->AddDefaultHandlers(
9834 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9835 } else {
9836 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9837 }
mkwst0c5eab872014-11-21 14:18:549838 ASSERT_TRUE(origin_server_->Start());
9839 }
9840
tommycli59a63432015-11-06 00:10:559841 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9842 net::EmbeddedTestServer::Type dest_type) {
9843 origin_server_.reset(new EmbeddedTestServer(origin_type));
9844 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9845 origin_server_->AddDefaultHandlers(
9846 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9847 } else {
9848 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9849 }
mkwst0c5eab872014-11-21 14:18:549850 ASSERT_TRUE(origin_server_->Start());
9851
tommycli59a63432015-11-06 00:10:559852 destination_server_.reset(new EmbeddedTestServer(dest_type));
9853 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9854 destination_server_->AddDefaultHandlers(
9855 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9856 } else {
9857 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9858 }
mkwst0c5eab872014-11-21 14:18:549859 ASSERT_TRUE(destination_server_->Start());
9860 }
9861
9862 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9863 const GURL& referrer,
9864 const GURL& expected) {
9865 // Create and execute the request: we'll only have a |destination_server_|
9866 // if the origins are meant to be distinct. Otherwise, we'll use the
9867 // |origin_server_| for both endpoints.
9868 GURL destination_url =
tommycli59a63432015-11-06 00:10:559869 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9870 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549871 GURL origin_url =
tommycli59a63432015-11-06 00:10:559872 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549873
9874 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079875 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169876 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549877 req->set_referrer_policy(policy);
9878 req->SetReferrer(referrer.spec());
9879 req->Start();
Wez2a31b222018-06-07 22:07:159880 d.RunUntilComplete();
mkwst0c5eab872014-11-21 14:18:549881
9882 EXPECT_EQ(1, d.response_started_count());
9883 EXPECT_EQ(1, d.received_redirect_count());
9884 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509885 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549886 EXPECT_EQ(200, req->response_headers()->response_code());
9887
9888 EXPECT_EQ(expected.spec(), req->referrer());
9889 if (expected.is_empty())
9890 EXPECT_EQ("None", d.data_received());
9891 else
9892 EXPECT_EQ(expected.spec(), d.data_received());
9893 }
9894
tommycli59a63432015-11-06 00:10:559895 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549896
9897 private:
danakj8522a25b2016-04-16 00:17:369898 std::unique_ptr<EmbeddedTestServer> origin_server_;
9899 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549900};
9901
9902TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559903 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549904
estarkc8ccba82017-06-13 22:37:409905 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549906 VerifyReferrerAfterRedirect(
9907 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409908 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549909
9910 VerifyReferrerAfterRedirect(
9911 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409912 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549913
9914 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409915 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549916
estarkc8ccba82017-06-13 22:37:409917 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9918 referrer);
9919
9920 // The original referrer set on the request is expected to obey the referrer
9921 // policy and already be stripped to the origin; thus this test case just
9922 // checks that this policy doesn't cause the referrer to change when following
9923 // a redirect.
9924 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9925 referrer.GetOrigin());
9926
9927 VerifyReferrerAfterRedirect(
9928 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9929 referrer);
9930
9931 // The original referrer set on the request is expected to obey the referrer
9932 // policy and already be stripped to the origin; thus this test case just
9933 // checks that this policy doesn't cause the referrer to change when following
9934 // a redirect.
9935 VerifyReferrerAfterRedirect(
9936 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9937 referrer.GetOrigin(), referrer.GetOrigin());
9938
9939 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549940}
9941
tommycli59a63432015-11-06 00:10:559942TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9943 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9944 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409945 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549946
9947 VerifyReferrerAfterRedirect(
9948 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409949 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549950
9951 VerifyReferrerAfterRedirect(
9952 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409953 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549954
9955 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409956 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9957 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549958
estarkc8ccba82017-06-13 22:37:409959 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9960 referrer);
9961
9962 // The original referrer set on the request is expected to obey the referrer
9963 // policy and already be stripped to the origin; thus this test case just
9964 // checks that this policy doesn't cause the referrer to change when following
9965 // a redirect.
9966 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9967 referrer.GetOrigin());
9968
9969 VerifyReferrerAfterRedirect(
9970 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9971
9972 // The original referrer set on the request is expected to obey the referrer
9973 // policy and already be stripped to the origin; thus this test case just
9974 // checks that this policy doesn't cause the referrer to change when following
9975 // a redirect.
9976 VerifyReferrerAfterRedirect(
9977 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9978 referrer.GetOrigin(), referrer.GetOrigin());
9979
9980 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549981}
9982
9983TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559984 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409985 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549986
9987 VerifyReferrerAfterRedirect(
9988 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409989 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549990
9991 VerifyReferrerAfterRedirect(
9992 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409993 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549994
9995 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409996 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549997
estarkc8ccba82017-06-13 22:37:409998 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9999 referrer);
10000
10001 // The original referrer set on the request is expected to obey the referrer
10002 // policy and already be stripped to the origin; thus this test case just
10003 // checks that this policy doesn't cause the referrer to change when following
10004 // a redirect.
10005 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10006 referrer.GetOrigin());
10007
10008 VerifyReferrerAfterRedirect(
10009 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
10010 referrer);
10011
10012 // The original referrer set on the request is expected to obey the referrer
10013 // policy and already be stripped to the origin; thus this test case just
10014 // checks that this policy doesn't cause the referrer to change when following
10015 // a redirect.
10016 VerifyReferrerAfterRedirect(
10017 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10018 referrer.GetOrigin(), referrer.GetOrigin());
10019
10020 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410021}
10022
tommycli59a63432015-11-06 00:10:5510023TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
10024 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
10025 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:4010026 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410027
10028 VerifyReferrerAfterRedirect(
10029 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010030 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410031
10032 VerifyReferrerAfterRedirect(
10033 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010034 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410035
10036 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010037 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:5510038 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410039
estarkc8ccba82017-06-13 22:37:4010040 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10041 referrer);
10042
10043 // The original referrer set on the request is expected to obey the referrer
10044 // policy and already be stripped to the origin; thus this test case just
10045 // checks that this policy doesn't cause the referrer to change when following
10046 // a redirect.
10047 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10048 referrer.GetOrigin());
10049
10050 VerifyReferrerAfterRedirect(
10051 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10052
10053 // The original referrer set on the request is expected to obey the referrer
10054 // policy and already be stripped to the origin; thus this test case just
10055 // checks that this policy doesn't cause the referrer to change when following
10056 // a redirect.
10057 VerifyReferrerAfterRedirect(
10058 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10059 referrer.GetOrigin(), referrer.GetOrigin());
10060
10061 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410062}
10063
tommycli59a63432015-11-06 00:10:5510064TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
10065 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
10066 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:4010067 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410068
10069 VerifyReferrerAfterRedirect(
10070 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010071 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410072
10073 VerifyReferrerAfterRedirect(
10074 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010075 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410076
10077 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010078 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:5510079 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410080
estarkc8ccba82017-06-13 22:37:4010081 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10082 referrer);
10083
10084 // The original referrer set on the request is expected to obey the referrer
10085 // policy and already be stripped to the origin; thus this test case just
10086 // checks that this policy doesn't cause the referrer to change when following
10087 // a redirect.
10088 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10089 referrer.GetOrigin());
10090
10091 VerifyReferrerAfterRedirect(
10092 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10093
10094 // The original referrer set on the request is expected to obey the referrer
10095 // policy and already be stripped to the origin; thus this test case just
10096 // checks that this policy doesn't cause the referrer to change when following
10097 // a redirect.
10098 VerifyReferrerAfterRedirect(
10099 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10100 referrer.GetOrigin(), referrer.GetOrigin());
10101
10102 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410103}
10104
tommycli59a63432015-11-06 00:10:5510105TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
10106 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
10107 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:4010108 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410109
10110 VerifyReferrerAfterRedirect(
10111 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010112 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:5410113
10114 VerifyReferrerAfterRedirect(
10115 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010116 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:5410117
10118 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010119 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:5510120 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410121
estarkc8ccba82017-06-13 22:37:4010122 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10123 referrer);
10124
10125 // The original referrer set on the request is expected to obey the referrer
10126 // policy and already be stripped to the origin; thus this test case just
10127 // checks that this policy doesn't cause the referrer to change when following
10128 // a redirect.
10129 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10130 referrer.GetOrigin());
10131
10132 VerifyReferrerAfterRedirect(
10133 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10134
10135 // The original referrer set on the request is expected to obey the referrer
10136 // policy and already be stripped to the origin, though it should be
10137 // subsequently cleared during the downgrading redirect.
10138 VerifyReferrerAfterRedirect(
10139 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10140 referrer.GetOrigin(), GURL());
10141
10142 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410143}
10144
Bence Béky98447b12018-05-08 03:14:0110145class HTTPSRequestTest : public TestWithScopedTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:5010146 public:
fdorayf33fede2017-05-11 21:18:1010147 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:0910148 default_context_.set_network_delegate(&default_network_delegate_);
10149 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:5010150 }
Martijn Croonenb1383da2017-10-11 11:56:3510151 ~HTTPSRequestTest() override {
10152 SetTransportSecurityStateSourceForTesting(nullptr);
10153 }
[email protected]87a09a92011-07-14 15:50:5010154
10155 protected:
[email protected]ceefd7fd2012-11-29 00:36:2410156 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:0910157 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:4610158};
10159
[email protected]c044616e2013-02-20 02:01:2610160TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:5510161 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10162 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210163 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:1110164 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:4610165
[email protected]ea224582008-12-07 20:25:4610166 TestDelegate d;
10167 {
danakj8522a25b2016-04-16 00:17:3610168 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610169 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10170 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910171 r->Start();
10172 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:4610173
Wez2a31b222018-06-07 22:07:1510174 d.RunUntilComplete();
[email protected]ea224582008-12-07 20:25:4610175
10176 EXPECT_EQ(1, d.response_started_count());
10177 EXPECT_FALSE(d.received_data_before_response());
10178 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:1910179 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:1910180 EXPECT_EQ(test_server.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3710181 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
[email protected]6d81b482011-02-22 19:47:1910182 EXPECT_EQ(test_server.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3710183 r->GetResponseRemoteEndpoint().port());
[email protected]ea224582008-12-07 20:25:4610184 }
[email protected]ea224582008-12-07 20:25:4610185}
10186
[email protected]5774ada2010-07-15 06:30:5410187TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:5510188 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10189 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10190 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210191 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:1110192 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:3310193
10194 bool err_allowed = true;
10195 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
10196 TestDelegate d;
10197 {
10198 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:3610199 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610200 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10201 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:3310202
[email protected]f7022f32014-08-21 16:32:1910203 r->Start();
10204 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:3310205
Wez2a31b222018-06-07 22:07:1510206 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:3310207
10208 EXPECT_EQ(1, d.response_started_count());
10209 EXPECT_FALSE(d.received_data_before_response());
10210 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:1710211 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:3310212 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:1910213 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:1710214 } else {
[email protected]bacff652009-03-31 17:50:3310215 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:1710216 }
[email protected]bacff652009-03-31 17:50:3310217 }
10218 }
10219}
10220
[email protected]5774ada2010-07-15 06:30:5410221TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:5510222 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10223 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
10224 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210225 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:1110226 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:3310227
10228 // Iterate from false to true, just so that we do the opposite of the
10229 // previous test in order to increase test coverage.
10230 bool err_allowed = false;
10231 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
10232 TestDelegate d;
10233 {
10234 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:3610235 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610236 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10237 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:3310238
[email protected]f7022f32014-08-21 16:32:1910239 r->Start();
10240 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:3310241
Wez2a31b222018-06-07 22:07:1510242 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:3310243
10244 EXPECT_EQ(1, d.response_started_count());
10245 EXPECT_FALSE(d.received_data_before_response());
10246 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:1710247 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:3310248 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:1910249 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:1710250 } else {
[email protected]bacff652009-03-31 17:50:3310251 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:1710252 }
[email protected]bacff652009-03-31 17:50:3310253 }
10254 }
10255}
[email protected]73e0bba2009-02-19 22:57:0910256
Emily Stark79fba5842019-04-25 04:59:3610257// A TestDelegate used to test that an appropriate net error code is provided
10258// when an SSL certificate error occurs.
10259class SSLNetErrorTestDelegate : public TestDelegate {
10260 public:
10261 void OnSSLCertificateError(URLRequest* request,
10262 int net_error,
10263 const SSLInfo& ssl_info,
10264 bool fatal) override {
10265 net_error_ = net_error;
10266 on_ssl_certificate_error_called_ = true;
10267 TestDelegate::OnSSLCertificateError(request, net_error, ssl_info, fatal);
10268 }
10269
10270 bool on_ssl_certificate_error_called() {
10271 return on_ssl_certificate_error_called_;
10272 }
10273
10274 int net_error() { return net_error_; }
10275
10276 private:
10277 bool on_ssl_certificate_error_called_ = false;
10278 int net_error_ = net::OK;
10279};
10280
10281// Tests that the URLRequest::Delegate receives an appropriate net error code
10282// when an SSL certificate error occurs.
10283TEST_F(HTTPSRequestTest, SSLNetErrorReportedToDelegate) {
10284 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10285 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
10286 test_server.AddDefaultHandlers(
10287 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10288 ASSERT_TRUE(test_server.Start());
10289
10290 SSLNetErrorTestDelegate d;
10291 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10292 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10293 TRAFFIC_ANNOTATION_FOR_TESTS));
10294 r->Start();
10295 EXPECT_TRUE(r->is_pending());
10296 d.RunUntilComplete();
10297
10298 EXPECT_TRUE(d.on_ssl_certificate_error_called());
10299 EXPECT_EQ(net::ERR_CERT_DATE_INVALID, d.net_error());
10300}
10301
tommycli59a63432015-11-06 00:10:5510302// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
10303// security state. (see http://crbug.com/550977).
10304#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:3510305// This tests that a load of a domain with preloaded HSTS and HPKP with a
10306// certificate error sets the |certificate_errors_are_fatal| flag correctly.
10307// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:4410308TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:3510309 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
10310
tommycli59a63432015-11-06 00:10:5510311 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10312 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10313 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:4410314 ASSERT_TRUE(test_server.Start());
10315
Martijn Croonenb1383da2017-10-11 11:56:3510316 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
10317 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
10318 // means that we have to use a MockHostResolver in order to direct
10319 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
10320 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:4410321
10322 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:2410323 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:4410324 TestURLRequestContext context(true);
10325 context.set_network_delegate(&network_delegate);
10326 context.set_host_resolver(&host_resolver);
10327 TransportSecurityState transport_security_state;
10328 context.set_transport_security_state(&transport_security_state);
10329 context.Init();
10330
10331 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610332 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:3510333 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:3610334 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610335 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410336
[email protected]f7022f32014-08-21 16:32:1910337 r->Start();
10338 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410339
Wez2a31b222018-06-07 22:07:1510340 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410341
10342 EXPECT_EQ(1, d.response_started_count());
10343 EXPECT_FALSE(d.received_data_before_response());
10344 EXPECT_TRUE(d.have_certificate_errors());
10345 EXPECT_TRUE(d.certificate_errors_are_fatal());
10346}
10347
10348// This tests that cached HTTPS page loads do not cause any updates to the
10349// TransportSecurityState.
10350TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:3510351 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
10352
[email protected]316c1e5e2012-09-12 15:17:4410353 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
10354 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:5510355 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10356 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10357 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:4410358 ASSERT_TRUE(test_server.Start());
10359
Martijn Croonenb1383da2017-10-11 11:56:3510360 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
10361 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
10362 // means that we have to use a MockHostResolver in order to direct
10363 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
10364 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:4410365
10366 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:2410367 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:4410368 TestURLRequestContext context(true);
10369 context.set_network_delegate(&network_delegate);
10370 context.set_host_resolver(&host_resolver);
10371 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:2610372
martijnc0d6b622015-06-30 19:14:4010373 TransportSecurityState::STSState static_sts_state;
10374 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610375 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510376 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:4410377 context.set_transport_security_state(&transport_security_state);
10378 context.Init();
10379
martijnc0d6b622015-06-30 19:14:4010380 TransportSecurityState::STSState dynamic_sts_state;
10381 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:3510382 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
10383 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
10384 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
10385 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610386
[email protected]316c1e5e2012-09-12 15:17:4410387 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610388 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:3510389 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:3610390 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610391 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410392
[email protected]f7022f32014-08-21 16:32:1910393 r->Start();
10394 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410395
Wez2a31b222018-06-07 22:07:1510396 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410397
10398 EXPECT_EQ(1, d.response_started_count());
10399 EXPECT_FALSE(d.received_data_before_response());
10400 EXPECT_TRUE(d.have_certificate_errors());
10401 EXPECT_TRUE(d.certificate_errors_are_fatal());
10402
[email protected]9e6968d2014-05-07 21:46:2610403 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:4010404 TransportSecurityState::STSState new_static_sts_state;
10405 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610406 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510407 "hsts-hpkp-preloaded.test", &new_static_sts_state,
10408 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:4010409 TransportSecurityState::STSState new_dynamic_sts_state;
10410 TransportSecurityState::PKPState new_dynamic_pkp_state;
10411 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:3510412 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:4010413 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:3510414 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610415
martijnc0d6b622015-06-30 19:14:4010416 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
10417 EXPECT_EQ(new_static_sts_state.include_subdomains,
10418 static_sts_state.include_subdomains);
10419 EXPECT_EQ(new_static_pkp_state.include_subdomains,
10420 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:4810421 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
10422 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
10423 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:4410424}
10425
[email protected]8ccc69f2012-11-28 19:52:1410426// Make sure HSTS preserves a POST request's method and body.
10427TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
10428 static const char kData[] = "hello world";
10429
tommycli59a63432015-11-06 00:10:5510430 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10431 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210432 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:1410433 ASSERT_TRUE(test_server.Start());
10434
10435
10436 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10437 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:5510438 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:2210439 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:1410440 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:1410441
10442 // Force https for www.somewhere.com.
10443 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:2010444 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
10445 bool include_subdomains = false;
10446 transport_security_state.AddHSTS("www.somewhere.com", expiry,
10447 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:1410448
10449 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10450
10451 TestURLRequestContext context(true);
10452 context.set_host_resolver(&host_resolver);
10453 context.set_transport_security_state(&transport_security_state);
10454 context.set_network_delegate(&network_delegate);
10455 context.Init();
10456
10457 TestDelegate d;
10458 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
10459 // cause a certificate error. Ignore the error.
10460 d.set_allow_certificate_errors(true);
10461
danakj8522a25b2016-04-16 00:17:3610462 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:1910463 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:3610464 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610465 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910466 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:0710467 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:1410468
[email protected]f7022f32014-08-21 16:32:1910469 req->Start();
Wez2a31b222018-06-07 22:07:1510470 d.RunUntilComplete();
[email protected]8ccc69f2012-11-28 19:52:1410471
[email protected]f7022f32014-08-21 16:32:1910472 EXPECT_EQ("https", req->url().scheme());
10473 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:1410474 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:4010475
10476 LoadTimingInfo load_timing_info;
10477 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
10478 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
10479 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:1410480}
10481
rob4e0be1f2014-09-11 23:40:2210482// Make sure that the CORS headers are added to cross-origin HSTS redirects.
10483TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
10484 static const char kOriginHeaderValue[] = "http://www.example.com";
10485
tommycli59a63432015-11-06 00:10:5510486 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10487 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:2210488 ASSERT_TRUE(test_server.Start());
10489
10490 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10491 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:5510492 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
10493 // default.
rob4e0be1f2014-09-11 23:40:2210494 MockHostResolver host_resolver;
10495
10496 TransportSecurityState transport_security_state;
10497 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
10498 bool include_subdomains = false;
10499 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
10500
10501 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10502
10503 MockCertVerifier cert_verifier;
10504 cert_verifier.set_default_result(OK);
10505
10506 TestURLRequestContext context(true);
10507 context.set_host_resolver(&host_resolver);
10508 context.set_transport_security_state(&transport_security_state);
10509 context.set_network_delegate(&network_delegate);
10510 context.set_cert_verifier(&cert_verifier);
10511 context.Init();
10512
10513 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
10514 test_server.host_port_pair().port()));
10515 url::Replacements<char> replacements;
10516 const char kNewScheme[] = "https";
10517 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
10518 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
10519
10520 TestDelegate d;
rob4e0be1f2014-09-11 23:40:2210521
rhalavatib7bd7c792017-04-27 05:25:1610522 std::unique_ptr<URLRequest> req(context.CreateRequest(
10523 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:2210524 // Set Origin header to simulate a cross-origin request.
10525 HttpRequestHeaders request_headers;
10526 request_headers.SetHeader("Origin", kOriginHeaderValue);
10527 req->SetExtraRequestHeaders(request_headers);
10528
10529 req->Start();
Wez0e717112018-06-18 23:09:2210530 d.RunUntilRedirect();
rob4e0be1f2014-09-11 23:40:2210531
10532 EXPECT_EQ(1, d.received_redirect_count());
10533
10534 const HttpResponseHeaders* headers = req->response_headers();
10535 std::string redirect_location;
Raul Tambre94493c652019-03-11 17:18:3510536 EXPECT_TRUE(
10537 headers->EnumerateHeader(nullptr, "Location", &redirect_location));
rob4e0be1f2014-09-11 23:40:2210538 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
10539
10540 std::string received_cors_header;
Raul Tambre94493c652019-03-11 17:18:3510541 EXPECT_TRUE(headers->EnumerateHeader(nullptr, "Access-Control-Allow-Origin",
rob4e0be1f2014-09-11 23:40:2210542 &received_cors_header));
10543 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
10544}
10545
[email protected]316c1e5e2012-09-12 15:17:4410546namespace {
10547
10548class SSLClientAuthTestDelegate : public TestDelegate {
10549 public:
10550 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
Wez0e717112018-06-18 23:09:2210551 set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:4410552 }
dchengb03027d2014-10-21 12:00:2010553 void OnCertificateRequested(URLRequest* request,
10554 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:4410555 on_certificate_requested_count_++;
Wez0e717112018-06-18 23:09:2210556 std::move(on_certificate_requested_).Run();
10557 }
10558 void RunUntilCertificateRequested() {
10559 base::RunLoop run_loop;
10560 on_certificate_requested_ = run_loop.QuitClosure();
10561 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:4410562 }
10563 int on_certificate_requested_count() {
10564 return on_certificate_requested_count_;
10565 }
10566 private:
10567 int on_certificate_requested_count_;
Wez0e717112018-06-18 23:09:2210568 base::OnceClosure on_certificate_requested_;
[email protected]316c1e5e2012-09-12 15:17:4410569};
10570
David Benjamin76a40ad2018-02-24 22:22:0810571class TestSSLPrivateKey : public SSLPrivateKey {
10572 public:
10573 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
10574 : key_(std::move(key)) {}
10575
10576 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
10577 int sign_count() const { return sign_count_; }
10578
David Benjaminb65b0732018-11-09 20:33:5310579 std::string GetProviderName() override { return key_->GetProviderName(); }
David Benjamin76a40ad2018-02-24 22:22:0810580 std::vector<uint16_t> GetAlgorithmPreferences() override {
10581 return key_->GetAlgorithmPreferences();
10582 }
10583 void Sign(uint16_t algorithm,
10584 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:2610585 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:0810586 sign_count_++;
10587 if (fail_signing_) {
10588 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:2610589 FROM_HERE, base::BindOnce(std::move(callback),
10590 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
10591 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:0810592 } else {
David Benjamin8f2d2c12018-02-27 00:08:2610593 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:0810594 }
10595 }
10596
10597 private:
10598 ~TestSSLPrivateKey() override = default;
10599
10600 scoped_refptr<SSLPrivateKey> key_;
10601 bool fail_signing_ = false;
10602 int sign_count_ = 0;
10603};
10604
[email protected]316c1e5e2012-09-12 15:17:4410605} // namespace
10606
10607// TODO(davidben): Test the rest of the code. Specifically,
10608// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:4410609// - Getting a certificate request in an SSL renegotiation sending the
10610// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:0810611TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:5510612 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10613 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:1210614 ssl_config.client_cert_type =
10615 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:0810616 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:5510617 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210618 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410619 ASSERT_TRUE(test_server.Start());
10620
10621 SSLClientAuthTestDelegate d;
10622 {
danakj8522a25b2016-04-16 00:17:3610623 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610624 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10625 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410626
[email protected]f7022f32014-08-21 16:32:1910627 r->Start();
10628 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410629
Wez0e717112018-06-18 23:09:2210630 d.RunUntilCertificateRequested();
10631 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410632
10633 EXPECT_EQ(1, d.on_certificate_requested_count());
10634 EXPECT_FALSE(d.received_data_before_response());
10635 EXPECT_EQ(0, d.bytes_received());
10636
10637 // Send no certificate.
10638 // TODO(davidben): Get temporary client cert import (with keys) working on
10639 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:5410640 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:4410641
Wez2a31b222018-06-07 22:07:1510642 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410643
David Benjamin76a40ad2018-02-24 22:22:0810644 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:4410645 EXPECT_EQ(1, d.response_started_count());
10646 EXPECT_FALSE(d.received_data_before_response());
10647 EXPECT_NE(0, d.bytes_received());
10648 }
10649}
10650
David Benjamin76a40ad2018-02-24 22:22:0810651TEST_F(HTTPSRequestTest, ClientAuth) {
10652 std::unique_ptr<FakeClientCertIdentity> identity =
10653 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10654 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10655 ASSERT_TRUE(identity);
10656 scoped_refptr<TestSSLPrivateKey> private_key =
10657 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10658
10659 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10660 net::SSLServerConfig ssl_config;
10661 ssl_config.client_cert_type =
10662 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10663 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10664 test_server.AddDefaultHandlers(
10665 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10666 ASSERT_TRUE(test_server.Start());
10667
10668 {
10669 SSLClientAuthTestDelegate d;
10670 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10671 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10672 TRAFFIC_ANNOTATION_FOR_TESTS));
10673
10674 r->Start();
10675 EXPECT_TRUE(r->is_pending());
10676
Wez0e717112018-06-18 23:09:2210677 d.RunUntilCertificateRequested();
10678 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810679
10680 EXPECT_EQ(1, d.on_certificate_requested_count());
10681 EXPECT_FALSE(d.received_data_before_response());
10682 EXPECT_EQ(0, d.bytes_received());
10683
10684 // Send a certificate.
10685 r->ContinueWithCertificate(identity->certificate(), private_key);
10686
Wez2a31b222018-06-07 22:07:1510687 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810688
10689 EXPECT_EQ(OK, d.request_status());
10690 EXPECT_EQ(1, d.response_started_count());
10691 EXPECT_FALSE(d.received_data_before_response());
10692 EXPECT_NE(0, d.bytes_received());
10693
10694 // The private key should have been used.
10695 EXPECT_EQ(1, private_key->sign_count());
10696 }
10697
10698 // Close all connections and clear the session cache to force a new handshake.
10699 default_context_.http_transaction_factory()
10700 ->GetSession()
10701 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710702 default_context_.http_transaction_factory()
10703 ->GetSession()
10704 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810705
10706 // Connecting again should not call OnCertificateRequested. The identity is
10707 // taken from the client auth cache.
10708 {
10709 SSLClientAuthTestDelegate d;
10710 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10711 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10712 TRAFFIC_ANNOTATION_FOR_TESTS));
10713
10714 r->Start();
10715 EXPECT_TRUE(r->is_pending());
10716
Wez2a31b222018-06-07 22:07:1510717 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810718
10719 EXPECT_EQ(OK, d.request_status());
10720 EXPECT_EQ(0, d.on_certificate_requested_count());
10721 EXPECT_FALSE(d.received_data_before_response());
10722 EXPECT_EQ(1, d.response_started_count());
10723 EXPECT_FALSE(d.received_data_before_response());
10724 EXPECT_NE(0, d.bytes_received());
10725
10726 // The private key should have been used.
10727 EXPECT_EQ(2, private_key->sign_count());
10728 }
10729}
10730
10731// Test that private keys that fail to sign anything get evicted from the cache.
10732TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
10733 std::unique_ptr<FakeClientCertIdentity> identity =
10734 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10735 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10736 ASSERT_TRUE(identity);
10737 scoped_refptr<TestSSLPrivateKey> private_key =
10738 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10739 private_key->set_fail_signing(true);
10740
10741 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10742 net::SSLServerConfig ssl_config;
10743 ssl_config.client_cert_type =
10744 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10745 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10746 test_server.AddDefaultHandlers(
10747 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10748 ASSERT_TRUE(test_server.Start());
10749
10750 {
10751 SSLClientAuthTestDelegate d;
10752 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10753 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10754 TRAFFIC_ANNOTATION_FOR_TESTS));
10755
10756 r->Start();
10757 EXPECT_TRUE(r->is_pending());
Wez0e717112018-06-18 23:09:2210758
10759 d.RunUntilCertificateRequested();
10760 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810761
10762 EXPECT_EQ(1, d.on_certificate_requested_count());
10763 EXPECT_FALSE(d.received_data_before_response());
10764 EXPECT_EQ(0, d.bytes_received());
10765
10766 // Send a certificate.
10767 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510768 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810769
10770 // The private key cannot sign anything, so we report an error.
10771 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
10772 EXPECT_EQ(1, d.response_started_count());
10773 EXPECT_FALSE(d.received_data_before_response());
10774 EXPECT_EQ(0, d.bytes_received());
10775
10776 // The private key should have been used.
10777 EXPECT_EQ(1, private_key->sign_count());
10778 }
10779
10780 // Close all connections and clear the session cache to force a new handshake.
10781 default_context_.http_transaction_factory()
10782 ->GetSession()
10783 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710784 default_context_.http_transaction_factory()
10785 ->GetSession()
10786 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810787
10788 // The bad identity should have been evicted from the cache, so connecting
10789 // again should call OnCertificateRequested again.
10790 {
10791 SSLClientAuthTestDelegate d;
10792 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10793 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10794 TRAFFIC_ANNOTATION_FOR_TESTS));
10795
10796 r->Start();
10797 EXPECT_TRUE(r->is_pending());
10798
Wez0e717112018-06-18 23:09:2210799 d.RunUntilCertificateRequested();
10800 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810801
10802 EXPECT_EQ(1, d.on_certificate_requested_count());
10803 EXPECT_FALSE(d.received_data_before_response());
10804 EXPECT_EQ(0, d.bytes_received());
10805
10806 // There should have been no additional uses of the private key.
10807 EXPECT_EQ(1, private_key->sign_count());
10808 }
10809}
10810
10811// Test that cached private keys that fail to sign anything trigger a
10812// retry. This is so we handle unplugged smartcards
10813// gracefully. https://crbug.com/813022.
10814TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
10815 std::unique_ptr<FakeClientCertIdentity> identity =
10816 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10817 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10818 ASSERT_TRUE(identity);
10819 scoped_refptr<TestSSLPrivateKey> private_key =
10820 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10821
10822 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10823 net::SSLServerConfig ssl_config;
10824 ssl_config.client_cert_type =
10825 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10826 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10827 test_server.AddDefaultHandlers(
10828 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10829 ASSERT_TRUE(test_server.Start());
10830
10831 // Connect with a client certificate to put it in the client auth cache.
10832 {
10833 SSLClientAuthTestDelegate d;
10834 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10835 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10836 TRAFFIC_ANNOTATION_FOR_TESTS));
10837
10838 r->Start();
10839 EXPECT_TRUE(r->is_pending());
10840
Wez0e717112018-06-18 23:09:2210841 d.RunUntilCertificateRequested();
10842 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810843
10844 EXPECT_EQ(1, d.on_certificate_requested_count());
10845 EXPECT_FALSE(d.received_data_before_response());
10846 EXPECT_EQ(0, d.bytes_received());
10847
10848 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510849 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810850
10851 EXPECT_EQ(OK, d.request_status());
10852 EXPECT_EQ(1, d.response_started_count());
10853 EXPECT_FALSE(d.received_data_before_response());
10854 EXPECT_NE(0, d.bytes_received());
10855
10856 // The private key should have been used.
10857 EXPECT_EQ(1, private_key->sign_count());
10858 }
10859
10860 // Close all connections and clear the session cache to force a new handshake.
10861 default_context_.http_transaction_factory()
10862 ->GetSession()
10863 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710864 default_context_.http_transaction_factory()
10865 ->GetSession()
10866 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810867
10868 // Cause the private key to fail. Connecting again should attempt to use it,
10869 // notice the failure, and then request a new identity via
10870 // OnCertificateRequested.
10871 private_key->set_fail_signing(true);
10872
10873 {
10874 SSLClientAuthTestDelegate d;
10875 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10876 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10877 TRAFFIC_ANNOTATION_FOR_TESTS));
10878
10879 r->Start();
10880 EXPECT_TRUE(r->is_pending());
10881
Wez0e717112018-06-18 23:09:2210882 d.RunUntilCertificateRequested();
10883 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810884
10885 // There was an additional signing call on the private key (the one which
10886 // failed).
10887 EXPECT_EQ(2, private_key->sign_count());
10888
10889 // That caused another OnCertificateRequested call.
10890 EXPECT_EQ(1, d.on_certificate_requested_count());
10891 EXPECT_FALSE(d.received_data_before_response());
10892 EXPECT_EQ(0, d.bytes_received());
10893 }
10894}
10895
[email protected]316c1e5e2012-09-12 15:17:4410896TEST_F(HTTPSRequestTest, ResumeTest) {
10897 // Test that we attempt a session resume when making two connections to the
10898 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:2210899 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410900 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210901 SpawnedTestServer test_server(
10902 SpawnedTestServer::TYPE_HTTPS,
10903 ssl_options,
10904 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410905 ASSERT_TRUE(test_server.Start());
10906
Daniel McArdle3a663d62019-01-31 00:48:4710907 default_context_.http_transaction_factory()
10908 ->GetSession()
10909 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4410910
10911 {
10912 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610913 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610914 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10915 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410916
[email protected]f7022f32014-08-21 16:32:1910917 r->Start();
10918 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410919
Wez2a31b222018-06-07 22:07:1510920 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410921
10922 EXPECT_EQ(1, d.response_started_count());
10923 }
10924
10925 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10926 CloseAllConnections();
10927
10928 {
10929 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610930 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610931 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10932 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410933
[email protected]f7022f32014-08-21 16:32:1910934 r->Start();
10935 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410936
Wez2a31b222018-06-07 22:07:1510937 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410938
10939 // The response will look like;
Steven Valdez0ef94d02018-11-19 23:28:1310940 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]316c1e5e2012-09-12 15:17:4410941 // insert abc
10942 // lookup abc
10943 // insert xyz
10944 //
10945 // With a newline at the end which makes the split think that there are
10946 // four lines.
10947
10948 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2910949 std::vector<std::string> lines = base::SplitString(
10950 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Steven Valdez0ef94d02018-11-19 23:28:1310951 ASSERT_EQ(5u, lines.size()) << d.data_received();
[email protected]316c1e5e2012-09-12 15:17:4410952
10953 std::string session_id;
10954
Steven Valdez0ef94d02018-11-19 23:28:1310955 for (size_t i = 0; i < 3; i++) {
brettw3a2c6902015-07-06 19:43:2910956 std::vector<std::string> parts = base::SplitString(
10957 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410958 ASSERT_EQ(2u, parts.size());
Steven Valdez0ef94d02018-11-19 23:28:1310959 if (i % 2 == 1) {
[email protected]316c1e5e2012-09-12 15:17:4410960 EXPECT_EQ("insert", parts[0]);
10961 session_id = parts[1];
10962 } else {
10963 EXPECT_EQ("lookup", parts[0]);
Steven Valdez0ef94d02018-11-19 23:28:1310964 if (i != 0)
10965 EXPECT_EQ(session_id, parts[1]);
[email protected]316c1e5e2012-09-12 15:17:4410966 }
10967 }
10968 }
10969}
10970
10971TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
10972 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
10973 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2210974 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410975 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210976 SpawnedTestServer test_server(
10977 SpawnedTestServer::TYPE_HTTPS,
10978 ssl_options,
10979 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410980 ASSERT_TRUE(test_server.Start());
10981
Daniel McArdle3a663d62019-01-31 00:48:4710982 default_context_.http_transaction_factory()
10983 ->GetSession()
10984 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4410985
10986 {
10987 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610988 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0410989 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1610990 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410991
[email protected]f7022f32014-08-21 16:32:1910992 r->Start();
10993 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410994
Wez2a31b222018-06-07 22:07:1510995 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410996
10997 EXPECT_EQ(1, d.response_started_count());
10998 }
10999
11000 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4111001 HttpNetworkSession::Context session_context;
11002 session_context.host_resolver = default_context_.host_resolver();
11003 session_context.cert_verifier = default_context_.cert_verifier();
11004 session_context.transport_security_state =
11005 default_context_.transport_security_state();
11006 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2011007 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4111008 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5911009 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4111010 session_context.ssl_config_service = default_context_.ssl_config_service();
11011 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4411012 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4111013 session_context.http_server_properties =
11014 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4411015
mmenke6ddfbea2017-05-31 21:48:4111016 HttpNetworkSession network_session(HttpNetworkSession::Params(),
11017 session_context);
zhongyi4928bd52017-02-08 02:16:2711018 std::unique_ptr<HttpCache> cache(
11019 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
11020 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4411021
11022 default_context_.set_http_transaction_factory(cache.get());
11023
11024 {
11025 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611026 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611027 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
11028 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4411029
[email protected]f7022f32014-08-21 16:32:1911030 r->Start();
11031 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4411032
Wez2a31b222018-06-07 22:07:1511033 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4411034
[email protected]316c1e5e2012-09-12 15:17:4411035 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0411036 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]316c1e5e2012-09-12 15:17:4411037 }
11038}
11039
Daniel McArdleda3fa942019-02-15 16:41:2111040// Test that sessions started with privacy mode enabled cannot be resumed when
11041// it is disabled, and vice versa.
11042TEST_F(HTTPSRequestTest, NoSessionResumptionBetweenPrivacyModes) {
11043 // Start a server.
11044 SpawnedTestServer test_server(
11045 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(),
11046 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11047 ASSERT_TRUE(test_server.Start());
11048 const auto url = test_server.GetURL("/");
11049
11050 auto ConnectAndCheckHandshake = [this, url](bool allow_credentials,
11051 auto expected_handshake) {
11052 // Construct request and indirectly set the privacy mode.
11053 TestDelegate d;
11054 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11055 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11056 r->set_allow_credentials(allow_credentials);
11057
11058 // Start the request and check the SSL handshake type.
11059 r->Start();
11060 EXPECT_TRUE(r->is_pending());
11061 d.RunUntilComplete();
11062 EXPECT_EQ(1, d.response_started_count());
11063 EXPECT_EQ(expected_handshake, r->ssl_info().handshake_type);
11064 };
11065
11066 // Exhaustively check all pairs of privacy mode values. Note that we are using
11067 // allow_credentials to indirectly enable/disable privacy mode.
11068 const bool kAllowCredentialsValues[] = {false, true};
11069 for (const auto allow_creds_1 : kAllowCredentialsValues) {
11070 for (const auto allow_creds_2 : kAllowCredentialsValues) {
11071 SCOPED_TRACE(base::StringPrintf("allow_creds_1=%d, allow_creds_2=%d",
11072 allow_creds_1, allow_creds_2));
11073
11074 // The session cache starts off empty, so we expect a full handshake.
11075 ConnectAndCheckHandshake(allow_creds_1, SSLInfo::HANDSHAKE_FULL);
11076
11077 // The second handshake depends on whether we are using the same session
11078 // cache as the first request.
11079 ConnectAndCheckHandshake(allow_creds_2, allow_creds_1 == allow_creds_2
11080 ? SSLInfo::HANDSHAKE_RESUME
11081 : SSLInfo::HANDSHAKE_FULL);
11082 // Flush both session caches.
11083 auto* network_session =
11084 default_context_.http_transaction_factory()->GetSession();
11085 network_session->ClearSSLSessionCache();
11086 }
11087 }
11088}
11089
Bence Béky98447b12018-05-08 03:14:0111090class HTTPSFallbackTest : public TestWithScopedTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:5511091 public:
fdorayf33fede2017-05-11 21:18:1011092 HTTPSFallbackTest() : context_(true) {
Nick Harper2243e8002018-09-28 20:33:2611093 ssl_config_service_ = std::make_unique<TestSSLConfigService>();
davidben095ebb52017-04-12 22:23:3411094 context_.set_ssl_config_service(ssl_config_service_.get());
11095 }
Chris Watkins7a41d3552017-12-01 02:13:2711096 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5511097
11098 protected:
davidben095ebb52017-04-12 22:23:3411099 TestSSLConfigService* ssl_config_service() {
11100 return ssl_config_service_.get();
11101 }
11102
[email protected]48d2b7c52014-06-27 01:16:5511103 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
11104 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0011105 context_.Init();
11106 delegate_.set_allow_certificate_errors(true);
11107
[email protected]48d2b7c52014-06-27 01:16:5511108 SpawnedTestServer test_server(
11109 SpawnedTestServer::TYPE_HTTPS,
11110 ssl_options,
11111 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11112 ASSERT_TRUE(test_server.Start());
11113
tommycli59a63432015-11-06 00:10:5511114 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1611115 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5511116 request_->Start();
11117
Wez2a31b222018-06-07 22:07:1511118 delegate_.RunUntilComplete();
[email protected]48d2b7c52014-06-27 01:16:5511119 }
11120
davidben095ebb52017-04-12 22:23:3411121 void ExpectConnection(int version) {
11122 EXPECT_EQ(1, delegate_.response_started_count());
11123 EXPECT_NE(0, delegate_.bytes_received());
11124 EXPECT_EQ(version, SSLConnectionStatusToVersion(
11125 request_->ssl_info().connection_status));
11126 }
11127
[email protected]48d2b7c52014-06-27 01:16:5511128 void ExpectFailure(int error) {
11129 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5011130 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5511131 }
11132
11133 private:
Ryan Sleevib8449e02018-07-15 04:31:0711134 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5511135 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4711136 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3611137 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:5511138};
11139
davidbenb127ca82015-06-15 19:05:4211140// Tests the TLS 1.0 fallback doesn't happen.
11141TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5511142 SpawnedTestServer::SSLOptions ssl_options(
11143 SpawnedTestServer::SSLOptions::CERT_OK);
11144 ssl_options.tls_intolerant =
11145 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
11146
11147 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5511148 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4211149}
11150
davidben5a312152016-06-27 22:11:4711151// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5511152TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4211153 SpawnedTestServer::SSLOptions ssl_options(
11154 SpawnedTestServer::SSLOptions::CERT_OK);
11155 ssl_options.tls_intolerant =
11156 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
11157
11158 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5511159 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
11160}
11161
David Benjamind61bd532019-04-23 21:11:3711162// Tests the TLS 1.2 fallback doesn't happen.
11163TEST_F(HTTPSFallbackTest, TLSv1_2NoFallback) {
davidben095ebb52017-04-12 22:23:3411164 SpawnedTestServer::SSLOptions ssl_options(
11165 SpawnedTestServer::SSLOptions::CERT_OK);
11166 ssl_options.tls_intolerant =
11167 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
davidben095ebb52017-04-12 22:23:3411168
11169 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
David Benjamind61bd532019-04-23 21:11:3711170 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidben095ebb52017-04-12 22:23:3411171}
11172
Bence Béky98447b12018-05-08 03:14:0111173class HTTPSSessionTest : public TestWithScopedTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:2411174 public:
fdorayf33fede2017-05-11 21:18:1011175 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5911176 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2411177
11178 default_context_.set_network_delegate(&default_network_delegate_);
11179 default_context_.set_cert_verifier(&cert_verifier_);
11180 default_context_.Init();
11181 }
Chris Watkins7a41d3552017-12-01 02:13:2711182 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2411183
11184 protected:
11185 MockCertVerifier cert_verifier_;
11186 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
11187 TestURLRequestContext default_context_;
11188};
11189
11190// Tests that session resumption is not attempted if an invalid certificate
11191// is presented.
11192TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
11193 SpawnedTestServer::SSLOptions ssl_options;
11194 ssl_options.record_resume = true;
11195 SpawnedTestServer test_server(
11196 SpawnedTestServer::TYPE_HTTPS,
11197 ssl_options,
11198 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11199 ASSERT_TRUE(test_server.Start());
11200
Daniel McArdle3a663d62019-01-31 00:48:4711201 default_context_.http_transaction_factory()
11202 ->GetSession()
11203 ->ClearSSLSessionCache();
[email protected]a8fed1742013-12-27 02:14:2411204
11205 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5911206 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2411207 {
11208 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611209 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0411210 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1611211 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2411212
[email protected]f7022f32014-08-21 16:32:1911213 r->Start();
11214 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2411215
Wez2a31b222018-06-07 22:07:1511216 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2411217
11218 EXPECT_EQ(1, d.response_started_count());
11219 }
11220
11221 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
11222 CloseAllConnections();
11223
11224 // Now change the certificate to be acceptable (so that the response is
11225 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5911226 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2411227 {
11228 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611229 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611230 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
11231 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2411232
[email protected]f7022f32014-08-21 16:32:1911233 r->Start();
11234 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2411235
Wez2a31b222018-06-07 22:07:1511236 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2411237
[email protected]a8fed1742013-12-27 02:14:2411238 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0411239 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]a8fed1742013-12-27 02:14:2411240 }
11241}
11242
[email protected]dffe8242012-03-20 15:14:2711243// This the fingerprint of the "Testing CA" certificate used by the testserver.
11244// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5811245static const SHA256HashValue kOCSPTestCertFingerprint = {{
11246 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
11247 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
11248 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1511249}};
[email protected]dffe8242012-03-20 15:14:2711250
[email protected]51523f52013-07-31 21:57:2811251// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
11252// testserver.
mattm0b12a6f2016-11-29 19:57:1611253static const SHA256HashValue kOCSPTestCertSPKI = {{
11254 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
11255 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
11256 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
11257}};
[email protected]51523f52013-07-31 21:57:2811258
[email protected]dffe8242012-03-20 15:14:2711259// This is the policy OID contained in the certificates that testserver
11260// generates.
11261static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
11262
11263class HTTPSOCSPTest : public HTTPSRequestTest {
11264 public:
11265 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0911266 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0811267 ev_test_policy_(
11268 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
11269 kOCSPTestCertFingerprint,
11270 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0211271 }
11272
dcheng67be2b1f2014-10-27 21:47:2911273 void SetUp() override {
Matt Muellera4aaa9d2019-04-24 21:09:1411274 cert_net_fetcher_ = base::MakeRefCounted<CertNetFetcherImpl>();
11275 cert_verifier_ = CertVerifier::CreateDefault(cert_net_fetcher_);
11276 context_.set_cert_verifier(cert_verifier_.get());
Ryan Sleevi8a9c9c12018-05-09 02:36:2311277 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
[email protected]ef2bf422012-05-11 03:27:0911278 context_.Init();
[email protected]dffe8242012-03-20 15:14:2711279
Matt Muellera4aaa9d2019-04-24 21:09:1411280 cert_net_fetcher_->SetURLRequestContext(&context_);
Ryan Sleevi24fe2682018-08-16 21:33:4611281 context_.cert_verifier()->SetConfig(GetCertVerifierConfig());
11282
[email protected]cba24642014-08-15 20:49:5911283 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2011284 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
Matt Mueller09c8fd9a2019-05-04 00:37:2411285 ASSERT_TRUE(root_cert);
[email protected]90499482013-06-01 00:39:5011286 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2711287
svaldez2135be52016-04-20 16:34:5311288#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0911289 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2711290#endif
11291 }
11292
dadrian612337a2016-07-20 22:36:5811293 void DoConnectionWithDelegate(
11294 const SpawnedTestServer::SSLOptions& ssl_options,
11295 TestDelegate* delegate,
11296 SSLInfo* out_ssl_info) {
11297 // Always overwrite |out_ssl_info|.
11298 out_ssl_info->Reset();
11299
[email protected]ce7d0cbc2013-05-03 18:57:2211300 SpawnedTestServer test_server(
11301 SpawnedTestServer::TYPE_HTTPS,
11302 ssl_options,
11303 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2711304 ASSERT_TRUE(test_server.Start());
11305
dadrian612337a2016-07-20 22:36:5811306 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1611307 std::unique_ptr<URLRequest> r(
11308 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
11309 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911310 r->Start();
[email protected]dffe8242012-03-20 15:14:2711311
Wez2a31b222018-06-07 22:07:1511312 delegate->RunUntilComplete();
dadrian612337a2016-07-20 22:36:5811313 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2711314
dadrian612337a2016-07-20 22:36:5811315 *out_ssl_info = r->ssl_info();
11316 }
11317
11318 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
11319 CertStatus* out_cert_status) {
11320 // Always overwrite |out_cert_status|.
11321 *out_cert_status = 0;
11322
11323 TestDelegate d;
11324 SSLInfo ssl_info;
11325 ASSERT_NO_FATAL_FAILURE(
11326 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
11327
11328 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2711329 }
11330
dcheng67be2b1f2014-10-27 21:47:2911331 ~HTTPSOCSPTest() override {
Matt Muellera4aaa9d2019-04-24 21:09:1411332 cert_net_fetcher_->Shutdown();
svaldez2135be52016-04-20 16:34:5311333#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1811334 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2711335#endif
11336 }
11337
[email protected]a13234c2012-03-20 21:45:0211338 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611339 // GetCertVerifierConfig() configures the URLRequestContext that will be used
11340 // for making connections to the testserver. This can be overridden in test
11341 // subclasses for different behaviour.
11342 virtual CertVerifier::Config GetCertVerifierConfig() {
11343 CertVerifier::Config config;
11344 config.enable_rev_checking = true;
11345 return config;
[email protected]a13234c2012-03-20 21:45:0211346 }
11347
danakj8522a25b2016-04-16 00:17:3611348 std::unique_ptr<ScopedTestRoot> test_root_;
Ryan Sleevib8449e02018-07-15 04:31:0711349 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
Matt Muellera4aaa9d2019-04-24 21:09:1411350 scoped_refptr<CertNetFetcherImpl> cert_net_fetcher_;
11351 std::unique_ptr<CertVerifier> cert_verifier_;
[email protected]ef2bf422012-05-11 03:27:0911352 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3611353 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2711354};
11355
[email protected]a13234c2012-03-20 21:45:0211356static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2011357#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0211358 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
11359 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0411360 // TODO(eroman): Should this also be the return value for
11361 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0211362 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
11363#else
11364 return 0;
11365#endif
11366}
11367
[email protected]3a86a712013-07-30 07:16:2011368// SystemSupportsHardFailRevocationChecking returns true iff the current
11369// operating system supports revocation checking and can distinguish between
11370// situations where a given certificate lacks any revocation information (eg:
11371// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
11372// revocation information cannot be obtained (eg: the CRL was unreachable).
11373// If it does not, then tests which rely on 'hard fail' behaviour should be
11374// skipped.
11375static bool SystemSupportsHardFailRevocationChecking() {
Eric Roman1b628daa2017-10-19 19:52:0411376#if defined(OS_WIN) || defined(USE_NSS_CERTS) || \
11377 defined(USE_BUILTIN_CERT_VERIFIER)
[email protected]3a86a712013-07-30 07:16:2011378 return true;
11379#else
11380 return false;
11381#endif
11382}
11383
[email protected]a13234c2012-03-20 21:45:0211384// SystemUsesChromiumEVMetadata returns true iff the current operating system
11385// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
11386// several tests are effected because our testing EV certificate won't be
11387// recognised as EV.
11388static bool SystemUsesChromiumEVMetadata() {
Eric Roman5f8d9d22017-10-17 02:32:5211389#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0111390 return true;
Eric Roman5f8d9d22017-10-17 02:32:5211391#else
11392 return false;
[email protected]05454a432012-03-20 20:04:0111393#endif
11394}
11395
mattmaf868e72016-09-23 23:25:2011396// Returns the expected CertStatus for tests that expect an online revocation
11397// check failure as a result of checking a test EV cert, which will not
11398// actually trigger an online revocation check on some platforms.
11399static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
11400 if (SystemUsesChromiumEVMetadata()) {
11401 return ExpectedCertStatusForFailedOnlineRevocationCheck();
11402 } else {
11403 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
11404 // be enabled, and thus there will not be a revocation check to fail.
11405 return 0u;
11406 }
11407}
11408
[email protected]b6f2de32012-08-17 04:35:0811409static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3911410#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0211411 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
11412 return false;
11413#else
11414 return true;
11415#endif
11416}
11417
davidbend1fb2f12014-11-08 02:51:0011418static bool SystemSupportsOCSPStapling() {
Matt Mueller7f60dc42019-04-26 22:47:1011419#if defined(OS_ANDROID)
mathpc992e602015-10-21 20:34:0311420 return false;
Matt Mueller7f60dc42019-04-26 22:47:1011421#elif defined(OS_MACOSX)
11422 // The SecTrustSetOCSPResponse function exists since macOS 10.9+, but does
11423 // not actually do anything until 10.12.
11424 if (base::mac::IsAtLeastOS10_12())
11425 return true;
11426 return false;
11427#else
11428 return true;
mathpc992e602015-10-21 20:34:0311429#endif
davidbend1fb2f12014-11-08 02:51:0011430}
11431
[email protected]dffe8242012-03-20 15:14:2711432TEST_F(HTTPSOCSPTest, Valid) {
11433 if (!SystemSupportsOCSP()) {
11434 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11435 return;
11436 }
11437
[email protected]ce7d0cbc2013-05-03 18:57:2211438 SpawnedTestServer::SSLOptions ssl_options(
11439 SpawnedTestServer::SSLOptions::CERT_AUTO);
11440 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2711441
[email protected]924e9f92012-12-16 22:00:5311442 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211443 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711444
11445 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11446
[email protected]a13234c2012-03-20 21:45:0211447 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11448 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2711449
11450 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11451}
11452
11453TEST_F(HTTPSOCSPTest, Revoked) {
11454 if (!SystemSupportsOCSP()) {
11455 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11456 return;
11457 }
11458
[email protected]ce7d0cbc2013-05-03 18:57:2211459 SpawnedTestServer::SSLOptions ssl_options(
11460 SpawnedTestServer::SSLOptions::CERT_AUTO);
11461 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2711462
11463 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211464 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711465
[email protected]dffe8242012-03-20 15:14:2711466 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2711467 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11468 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11469}
11470
11471TEST_F(HTTPSOCSPTest, Invalid) {
11472 if (!SystemSupportsOCSP()) {
11473 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11474 return;
11475 }
11476
[email protected]ce7d0cbc2013-05-03 18:57:2211477 SpawnedTestServer::SSLOptions ssl_options(
11478 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811479 ssl_options.ocsp_status =
11480 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2711481
[email protected]924e9f92012-12-16 22:00:5311482 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211483 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711484
Eric Roman1b628daa2017-10-19 19:52:0411485#if defined(USE_BUILTIN_CERT_VERIFIER)
11486 // TODO(649017): This test uses soft-fail revocation checking, but returns an
11487 // invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
11488 // doesn't consider this a candidate for soft-fail (only considers
11489 // network-level failures as skippable).
11490 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11491 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11492#else
[email protected]a13234c2012-03-20 21:45:0211493 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2711494 cert_status & CERT_STATUS_ALL_ERRORS);
Eric Roman1b628daa2017-10-19 19:52:0411495#endif
[email protected]dffe8242012-03-20 15:14:2711496
11497 // Without a positive OCSP response, we shouldn't show the EV status.
11498 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11499 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11500}
[email protected]a13234c2012-03-20 21:45:0211501
Matt Mueller5339d862018-05-02 18:53:5711502TEST_F(HTTPSOCSPTest, IntermediateValid) {
11503 if (!SystemSupportsOCSP()) {
11504 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11505 return;
11506 }
11507
11508 SpawnedTestServer::SSLOptions ssl_options(
11509 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11510 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11511 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11512
11513 CertStatus cert_status;
11514 DoConnection(ssl_options, &cert_status);
11515
11516 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11517
11518 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11519 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11520
11521 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11522}
11523
11524TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
11525 if (!SystemSupportsOCSP()) {
11526 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11527 return;
11528 }
11529
11530 SpawnedTestServer::SSLOptions ssl_options(
11531 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11532 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11533 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11534 // Use an OCSP response for the intermediate that would be too old for a leaf
11535 // cert, but is still valid for an intermediate.
11536 ssl_options.ocsp_intermediate_date =
11537 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
11538
11539 CertStatus cert_status;
11540 DoConnection(ssl_options, &cert_status);
11541
11542 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11543
11544 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11545 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11546
11547 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11548}
11549
11550TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
11551 if (!SystemSupportsOCSP()) {
11552 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11553 return;
11554 }
11555
11556 SpawnedTestServer::SSLOptions ssl_options(
11557 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11558 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11559 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11560 ssl_options.ocsp_intermediate_date =
11561 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
11562
11563 CertStatus cert_status;
11564 DoConnection(ssl_options, &cert_status);
11565
11566#if defined(USE_BUILTIN_CERT_VERIFIER)
11567 // The builtin verifier enforces the baseline requirements for max age of an
11568 // intermediate's OCSP response.
11569 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11570 cert_status & CERT_STATUS_ALL_ERRORS);
11571 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11572#else
11573 // The platform verifiers are more lenient.
11574 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11575 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11576 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11577#endif
11578 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11579}
11580
11581TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
11582 if (!SystemSupportsOCSP()) {
11583 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11584 return;
11585 }
11586
11587 SpawnedTestServer::SSLOptions ssl_options(
11588 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11589 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11590 ssl_options.ocsp_intermediate_status =
11591 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11592
11593 CertStatus cert_status;
11594 DoConnection(ssl_options, &cert_status);
11595
11596#if defined(OS_WIN)
11597 // TODO(mattm): why does CertVerifyProcWin accept this?
11598 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11599#else
11600 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11601#endif
11602 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11603 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11604}
11605
davidbend1fb2f12014-11-08 02:51:0011606TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0311607 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011608 LOG(WARNING)
11609 << "Skipping test because system doesn't support OCSP stapling";
11610 return;
11611 }
11612
11613 SpawnedTestServer::SSLOptions ssl_options(
11614 SpawnedTestServer::SSLOptions::CERT_AUTO);
11615 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11616 ssl_options.staple_ocsp_response = true;
11617 ssl_options.ocsp_server_unavailable = true;
11618
11619 CertStatus cert_status;
11620 DoConnection(ssl_options, &cert_status);
11621
11622 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11623
11624 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11625 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11626
11627 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11628}
11629
davidben6c3191b2014-11-21 22:38:0411630// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4811631#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0411632#define MAYBE_RevokedStapled DISABLED_RevokedStapled
11633#else
11634#define MAYBE_RevokedStapled RevokedStapled
11635#endif
11636TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0311637 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011638 LOG(WARNING)
11639 << "Skipping test because system doesn't support OCSP stapling";
11640 return;
11641 }
11642
11643 SpawnedTestServer::SSLOptions ssl_options(
11644 SpawnedTestServer::SSLOptions::CERT_AUTO);
11645 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11646 ssl_options.staple_ocsp_response = true;
11647 ssl_options.ocsp_server_unavailable = true;
11648
11649 CertStatus cert_status;
11650 DoConnection(ssl_options, &cert_status);
11651
11652 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11653 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11654 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11655}
11656
dadrian612337a2016-07-20 22:36:5811657static const struct OCSPVerifyTestData {
11658 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
11659 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
11660 OCSPVerifyResult::ResponseStatus response_status;
11661 bool has_revocation_status;
11662 OCSPRevocationStatus cert_status;
11663} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3111664 // 0
dadrian612337a2016-07-20 22:36:5811665 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11666 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11667 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11668 OCSPVerifyResult::PROVIDED,
11669 true,
11670 OCSPRevocationStatus::GOOD},
11671
Eric Roman8673b812017-09-20 18:57:3111672 // 1
dadrian612337a2016-07-20 22:36:5811673 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11674 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11675 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11676 OCSPVerifyResult::INVALID_DATE,
11677 false,
11678 OCSPRevocationStatus::UNKNOWN},
11679
Eric Roman8673b812017-09-20 18:57:3111680 // 2
dadrian612337a2016-07-20 22:36:5811681 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11682 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11683 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11684 OCSPVerifyResult::INVALID_DATE,
11685 false,
11686 OCSPRevocationStatus::UNKNOWN},
11687
Eric Roman8673b812017-09-20 18:57:3111688 // 3
dadrian612337a2016-07-20 22:36:5811689 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11690 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11691 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11692 OCSPVerifyResult::INVALID_DATE,
11693 false,
11694 OCSPRevocationStatus::UNKNOWN},
11695
Eric Roman8673b812017-09-20 18:57:3111696 // 4
dadrian612337a2016-07-20 22:36:5811697 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11698 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11699 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11700 OCSPVerifyResult::INVALID_DATE,
11701 false,
11702 OCSPRevocationStatus::UNKNOWN},
11703
Eric Roman8673b812017-09-20 18:57:3111704 // 5
dadrian612337a2016-07-20 22:36:5811705 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
11706 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11707 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11708 OCSPVerifyResult::ERROR_RESPONSE,
11709 false,
11710 OCSPRevocationStatus::UNKNOWN},
11711
Eric Roman8673b812017-09-20 18:57:3111712 // 6
dadrian612337a2016-07-20 22:36:5811713 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
11714 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11715 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11716 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
11717 false,
11718 OCSPRevocationStatus::UNKNOWN},
11719
Eric Roman8673b812017-09-20 18:57:3111720 // 7
dadrian612337a2016-07-20 22:36:5811721 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
11722 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11723 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11724 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
11725 false,
11726 OCSPRevocationStatus::UNKNOWN},
11727
Eric Roman8673b812017-09-20 18:57:3111728 // 8
dadrian612337a2016-07-20 22:36:5811729 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11730 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11731 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11732 OCSPVerifyResult::INVALID_DATE,
11733 false,
11734 OCSPRevocationStatus::UNKNOWN},
11735
Eric Roman8673b812017-09-20 18:57:3111736 // 9
dadrian612337a2016-07-20 22:36:5811737 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11738 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11739 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11740 OCSPVerifyResult::PROVIDED,
11741 true,
11742 OCSPRevocationStatus::UNKNOWN},
11743
Eric Roman8673b812017-09-20 18:57:3111744 // 10
dadrian612337a2016-07-20 22:36:5811745 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11746 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11747 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11748 OCSPVerifyResult::INVALID_DATE,
11749 false,
11750 OCSPRevocationStatus::UNKNOWN},
11751
Eric Roman8673b812017-09-20 18:57:3111752 // 11
dadrian612337a2016-07-20 22:36:5811753 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11754 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11755 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11756 OCSPVerifyResult::INVALID_DATE,
11757 false,
11758 OCSPRevocationStatus::UNKNOWN},
11759
Eric Roman8673b812017-09-20 18:57:3111760 // 12
dadrian612337a2016-07-20 22:36:5811761 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11762 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11763 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
11764 OCSPVerifyResult::BAD_PRODUCED_AT,
11765 false,
11766 OCSPRevocationStatus::UNKNOWN},
11767
Eric Roman8673b812017-09-20 18:57:3111768 // 13
dadrian612337a2016-07-20 22:36:5811769 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11770 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11771 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11772 OCSPVerifyResult::BAD_PRODUCED_AT,
11773 false,
11774 OCSPRevocationStatus::UNKNOWN},
11775
Eric Roman8673b812017-09-20 18:57:3111776 // 14
dadrian612337a2016-07-20 22:36:5811777 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11778 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11779 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11780 OCSPVerifyResult::BAD_PRODUCED_AT,
11781 false,
11782 OCSPRevocationStatus::UNKNOWN},
11783
Eric Roman8673b812017-09-20 18:57:3111784 // 15
dadrian612337a2016-07-20 22:36:5811785 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11786 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11787 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11788 OCSPVerifyResult::PROVIDED,
11789 true,
11790 OCSPRevocationStatus::GOOD},
11791
Eric Roman8673b812017-09-20 18:57:3111792 // 16
dadrian612337a2016-07-20 22:36:5811793 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11794 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11795 {SpawnedTestServer::SSLOptions::OCSP_OK,
11796 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11797 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11798 OCSPVerifyResult::PROVIDED,
11799 true,
11800 OCSPRevocationStatus::GOOD},
11801
Eric Roman8673b812017-09-20 18:57:3111802 // 17
dadrian612337a2016-07-20 22:36:5811803 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11804 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11805 {SpawnedTestServer::SSLOptions::OCSP_OK,
11806 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11807 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11808 OCSPVerifyResult::PROVIDED,
11809 true,
11810 OCSPRevocationStatus::GOOD},
11811
Eric Roman8673b812017-09-20 18:57:3111812 // 18
dadrian612337a2016-07-20 22:36:5811813 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11814 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11815 {SpawnedTestServer::SSLOptions::OCSP_OK,
11816 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11817 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11818 OCSPVerifyResult::PROVIDED,
11819 true,
11820 OCSPRevocationStatus::GOOD},
11821
Eric Roman8673b812017-09-20 18:57:3111822 // 19
dadrian612337a2016-07-20 22:36:5811823 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11824 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11825 {SpawnedTestServer::SSLOptions::OCSP_OK,
11826 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11827 {SpawnedTestServer::SSLOptions::OCSP_OK,
11828 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11829 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11830 OCSPVerifyResult::INVALID_DATE,
11831 false,
11832 OCSPRevocationStatus::UNKNOWN},
11833
Eric Roman8673b812017-09-20 18:57:3111834 // 20
dadrian612337a2016-07-20 22:36:5811835 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11836 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11837 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11838 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11839 {SpawnedTestServer::SSLOptions::OCSP_OK,
11840 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11841 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11842 OCSPVerifyResult::PROVIDED,
11843 true,
11844 OCSPRevocationStatus::REVOKED},
11845
Eric Roman8673b812017-09-20 18:57:3111846 // 21
dadrian612337a2016-07-20 22:36:5811847 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11848 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11849 {SpawnedTestServer::SSLOptions::OCSP_OK,
11850 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11851 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11852 OCSPVerifyResult::PROVIDED,
11853 true,
11854 OCSPRevocationStatus::UNKNOWN},
11855
Eric Roman8673b812017-09-20 18:57:3111856 // 22
dadrian612337a2016-07-20 22:36:5811857 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11858 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11859 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11860 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11861 {SpawnedTestServer::SSLOptions::OCSP_OK,
11862 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11863 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11864 OCSPVerifyResult::PROVIDED,
11865 true,
11866 OCSPRevocationStatus::UNKNOWN},
11867
Eric Roman8673b812017-09-20 18:57:3111868 // 23
dadrian612337a2016-07-20 22:36:5811869 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11870 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11871 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11872 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11873 false,
11874 OCSPRevocationStatus::UNKNOWN},
11875
Eric Roman8673b812017-09-20 18:57:3111876 // 24
dadrian612337a2016-07-20 22:36:5811877 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11878 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11879 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11880 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11881 false,
11882 OCSPRevocationStatus::UNKNOWN},
11883
Eric Roman8673b812017-09-20 18:57:3111884// These tests fail when using NSS for certificate verification, as NSS fails
11885// and doesn't return the partial path. As a result the OCSP checks being done
11886// at the CertVerifyProc layer cannot access the issuer certificate.
11887#if !defined(USE_NSS_CERTS)
11888 // 25
11889 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11890 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11891 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11892 OCSPVerifyResult::PROVIDED,
11893 true,
11894 OCSPRevocationStatus::REVOKED},
11895
11896 // 26
11897 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11898 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11899 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11900 OCSPVerifyResult::INVALID_DATE,
11901 false,
11902 OCSPRevocationStatus::UNKNOWN},
11903
11904 // 27
11905 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11906 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11907 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11908 OCSPVerifyResult::INVALID_DATE,
11909 false,
11910 OCSPRevocationStatus::UNKNOWN},
11911#endif
dadrian612337a2016-07-20 22:36:5811912};
11913
11914class HTTPSOCSPVerifyTest
11915 : public HTTPSOCSPTest,
11916 public testing::WithParamInterface<OCSPVerifyTestData> {};
11917
Christos Froussios09e6ac42019-04-05 14:08:2011918// TODO(crbug.com/949958): The test is flaky on Mac
11919#if defined(OS_MACOSX)
11920#define MAYBE_VerifyResult DISABLED_VerifyResult
11921#else
11922#define MAYBE_VerifyResult VerifyResult
11923#endif
11924TEST_P(HTTPSOCSPVerifyTest, MAYBE_VerifyResult) {
dadrian612337a2016-07-20 22:36:5811925 SpawnedTestServer::SSLOptions ssl_options(
11926 SpawnedTestServer::SSLOptions::CERT_AUTO);
11927 OCSPVerifyTestData test = GetParam();
11928
11929 ssl_options.ocsp_responses = test.ocsp_responses;
11930 ssl_options.ocsp_produced = test.ocsp_produced;
11931 ssl_options.staple_ocsp_response = true;
11932
11933 SSLInfo ssl_info;
11934 OCSPErrorTestDelegate delegate;
11935 ASSERT_NO_FATAL_FAILURE(
11936 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
11937
11938 // The SSLInfo must be extracted from |delegate| on error, due to how
11939 // URLRequest caches certificate errors.
11940 if (delegate.have_certificate_errors()) {
11941 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
11942 ssl_info = delegate.ssl_info();
11943 }
11944
11945 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
11946
11947 if (test.has_revocation_status)
11948 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
11949}
11950
Victor Costan8fb98f6f2019-02-01 17:08:2911951INSTANTIATE_TEST_SUITE_P(OCSPVerify,
11952 HTTPSOCSPVerifyTest,
11953 testing::ValuesIn(kOCSPVerifyData));
dadrian612337a2016-07-20 22:36:5811954
mattm0b12a6f2016-11-29 19:57:1611955class HTTPSAIATest : public HTTPSOCSPTest {
11956 public:
Ryan Sleevi24fe2682018-08-16 21:33:4611957 CertVerifier::Config GetCertVerifierConfig() override {
11958 CertVerifier::Config config;
11959 return config;
mattm0b12a6f2016-11-29 19:57:1611960 }
11961};
11962
11963TEST_F(HTTPSAIATest, AIAFetching) {
11964 SpawnedTestServer::SSLOptions ssl_options(
11965 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
11966 SpawnedTestServer test_server(
11967 SpawnedTestServer::TYPE_HTTPS, ssl_options,
11968 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11969 ASSERT_TRUE(test_server.Start());
11970
Ryan Sleevi5b4702a2018-04-06 22:23:5611971 // Unmark the certificate's OID as EV, which will disable revocation
11972 // checking.
11973 ev_test_policy_.reset();
11974
mattm0b12a6f2016-11-29 19:57:1611975 TestDelegate d;
11976 d.set_allow_certificate_errors(true);
11977 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611978 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11979 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611980
11981 r->Start();
11982 EXPECT_TRUE(r->is_pending());
11983
Wez2a31b222018-06-07 22:07:1511984 d.RunUntilComplete();
mattm0b12a6f2016-11-29 19:57:1611985
11986 EXPECT_EQ(1, d.response_started_count());
11987
11988 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4811989 EXPECT_EQ(OK, d.request_status());
11990 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11991 ASSERT_TRUE(r->ssl_info().cert);
11992 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611993 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3411994 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611995}
11996
[email protected]3a86a712013-07-30 07:16:2011997class HTTPSHardFailTest : public HTTPSOCSPTest {
11998 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611999 CertVerifier::Config GetCertVerifierConfig() override {
12000 CertVerifier::Config config;
12001 config.require_rev_checking_local_anchors = true;
12002 return config;
[email protected]3a86a712013-07-30 07:16:2012003 }
12004};
12005
[email protected]3a86a712013-07-30 07:16:2012006TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
12007 if (!SystemSupportsOCSP()) {
12008 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12009 return;
12010 }
12011
12012 if (!SystemSupportsHardFailRevocationChecking()) {
12013 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
12014 << "revocation checking";
12015 return;
12016 }
12017
12018 SpawnedTestServer::SSLOptions ssl_options(
12019 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812020 ssl_options.ocsp_status =
12021 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2012022
12023 CertStatus cert_status;
12024 DoConnection(ssl_options, &cert_status);
12025
Eric Roman1b628daa2017-10-19 19:52:0412026#if defined(USE_BUILTIN_CERT_VERIFIER)
12027 // TODO(crbug.com/649017): Should we consider invalid response as
12028 // affirmatively revoked?
12029 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
12030 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
12031#else
12032 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
12033#endif
[email protected]3a86a712013-07-30 07:16:2012034
12035 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0412036 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2012037 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12038}
12039
[email protected]a13234c2012-03-20 21:45:0212040class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
12041 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4612042 CertVerifier::Config GetCertVerifierConfig() override {
12043 CertVerifier::Config config;
12044 return config;
[email protected]a13234c2012-03-20 21:45:0212045 }
12046};
12047
12048TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
12049 if (!SystemSupportsOCSP()) {
12050 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12051 return;
12052 }
12053
[email protected]ce7d0cbc2013-05-03 18:57:2212054 SpawnedTestServer::SSLOptions ssl_options(
12055 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812056 ssl_options.ocsp_status =
12057 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0212058
[email protected]924e9f92012-12-16 22:00:5312059 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212060 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212061
mattmaf868e72016-09-23 23:25:2012062 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0212063 cert_status & CERT_STATUS_ALL_ERRORS);
12064
12065 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0812066 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12067 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212068}
12069
[email protected]be0fff62013-08-29 23:37:4812070TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
12071 if (!SystemSupportsOCSP()) {
12072 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12073 return;
12074 }
12075
12076 SpawnedTestServer::SSLOptions ssl_options(
12077 SpawnedTestServer::SSLOptions::CERT_AUTO);
12078 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]be0fff62013-08-29 23:37:4812079
12080 CertStatus cert_status;
12081 DoConnection(ssl_options, &cert_status);
12082
mattm1a282f52016-11-10 21:49:4212083// Currently only works for Windows and OS X. When using NSS, it's not
12084// possible to determine whether the check failed because of actual
12085// revocation or because there was an OCSP failure.
12086#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4812087 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12088#else
12089 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12090#endif
12091
12092 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12093 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12094 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
12095}
12096
[email protected]a13234c2012-03-20 21:45:0212097TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
12098 if (!SystemSupportsOCSP()) {
12099 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12100 return;
12101 }
12102
[email protected]ce7d0cbc2013-05-03 18:57:2212103 SpawnedTestServer::SSLOptions ssl_options(
12104 SpawnedTestServer::SSLOptions::CERT_AUTO);
12105 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0212106
12107 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212108 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212109
12110 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12111
12112 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12113 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0812114 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12115 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212116}
12117
12118TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
12119 if (!SystemSupportsOCSP()) {
12120 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12121 return;
12122 }
12123
[email protected]ce7d0cbc2013-05-03 18:57:2212124 SpawnedTestServer::SSLOptions ssl_options(
12125 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812126 ssl_options.ocsp_status =
12127 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212128 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12129 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
12130 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0212131
12132 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212133 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212134
mattmaf868e72016-09-23 23:25:2012135 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0212136 cert_status & CERT_STATUS_ALL_ERRORS);
12137
12138 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0812139 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12140 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212141}
12142
[email protected]51523f52013-07-31 21:57:2812143TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
12144 if (!SystemSupportsOCSP()) {
12145 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12146 return;
12147 }
12148
12149 SpawnedTestServer::SSLOptions ssl_options(
12150 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812151 ssl_options.ocsp_status =
12152 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212153 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12154 cert_verifier_config.crl_set =
12155 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {});
12156 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2812157
12158 CertStatus cert_status;
12159 DoConnection(ssl_options, &cert_status);
12160
12161 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
12162 // revocation check for EV.
12163 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12164 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12165 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
12166 EXPECT_FALSE(
12167 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
12168}
12169
12170TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
12171 if (!SystemSupportsOCSP()) {
12172 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12173 return;
12174 }
12175
[email protected]ce7d0cbc2013-05-03 18:57:2212176 SpawnedTestServer::SSLOptions ssl_options(
12177 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812178 ssl_options.ocsp_status =
12179 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212180 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12181 cert_verifier_config.crl_set = CRLSet::EmptyCRLSetForTesting();
12182 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0212183
[email protected]51523f52013-07-31 21:57:2812184 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1212185 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212186
[email protected]51523f52013-07-31 21:57:2812187 // Even with a fresh CRLSet, we should still do online revocation checks when
12188 // the certificate chain isn't covered by the CRLSet, which it isn't in this
12189 // test.
mattmaf868e72016-09-23 23:25:2012190 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2812191 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0212192
[email protected]51523f52013-07-31 21:57:2812193 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0212194 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2812195 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212196}
12197
12198class HTTPSCRLSetTest : public HTTPSOCSPTest {
12199 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4612200 CertVerifier::Config GetCertVerifierConfig() override {
12201 CertVerifier::Config config;
12202 return config;
Ryan Sleevi5b4702a2018-04-06 22:23:5612203 }
12204
12205 void SetUp() override {
12206 HTTPSOCSPTest::SetUp();
12207
12208 // Unmark the certificate's OID as EV, which should disable revocation
12209 // checking (as per the user preference).
12210 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0212211 }
12212};
12213
12214TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2212215 SpawnedTestServer::SSLOptions ssl_options(
12216 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812217 ssl_options.ocsp_status =
12218 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212219 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12220 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
12221 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0212222
[email protected]924e9f92012-12-16 22:00:5312223 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212224 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212225
12226 // If we're not trying EV verification then, even if the CRLSet has expired,
12227 // we don't fall back to online revocation checks.
12228 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12229 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12230 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12231}
[email protected]51523f52013-07-31 21:57:2812232
Ryan Sleevi5b4702a2018-04-06 22:23:5612233TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
12234 // Test that when online revocation checking is disabled, and the leaf
12235 // certificate is not EV, that no revocation checking actually happens.
12236 if (!SystemSupportsOCSP()) {
12237 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12238 return;
12239 }
12240
12241 SpawnedTestServer::SSLOptions ssl_options(
12242 SpawnedTestServer::SSLOptions::CERT_AUTO);
12243 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Ryan Sleevib369d712018-08-20 16:43:2212244
12245 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12246 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
12247 context_.cert_verifier()->SetConfig(cert_verifier_config);
Ryan Sleevi5b4702a2018-04-06 22:23:5612248
12249 CertStatus cert_status;
12250 DoConnection(ssl_options, &cert_status);
12251
12252 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12253
12254 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12255 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12256}
12257
[email protected]51523f52013-07-31 21:57:2812258TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2512259#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2812260 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12261 return;
12262#endif
12263
12264 SpawnedTestServer::SSLOptions ssl_options(
12265 SpawnedTestServer::SSLOptions::CERT_AUTO);
12266 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12267 ssl_options.cert_serial = 10;
Ryan Sleevib369d712018-08-20 16:43:2212268
12269 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12270 cert_verifier_config.crl_set =
12271 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {});
12272 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2812273
12274 CertStatus cert_status = 0;
12275 DoConnection(ssl_options, &cert_status);
12276
12277 // If the certificate is recorded as revoked in the CRLSet, that should be
12278 // reflected without online revocation checking.
12279 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12280 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612281 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2812282}
Adam Langleyea6d6782017-12-05 23:57:3312283
12284TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
12285#if defined(OS_ANDROID)
12286 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12287 return;
12288#endif
12289
12290 SpawnedTestServer::SSLOptions ssl_options(
12291 SpawnedTestServer::SSLOptions::CERT_AUTO);
12292 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12293 static const char kCommonName[] = "Test CN";
12294 ssl_options.cert_common_name = kCommonName;
12295
12296 {
Ryan Sleevib369d712018-08-20 16:43:2212297 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12298 cert_verifier_config.crl_set =
12299 CRLSet::ForTesting(false, nullptr, "", kCommonName, {});
12300 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3312301
12302 CertStatus cert_status = 0;
12303 DoConnection(ssl_options, &cert_status);
12304
12305 // If the certificate is recorded as revoked in the CRLSet, that should be
12306 // reflected without online revocation checking.
12307 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12308 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612309 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3312310 }
12311
12312 const uint8_t kTestServerSPKISHA256[32] = {
12313 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
12314 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
12315 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
12316 };
12317 const std::string spki_hash(
12318 reinterpret_cast<const char*>(kTestServerSPKISHA256),
12319 sizeof(kTestServerSPKISHA256));
12320
12321 {
Ryan Sleevib369d712018-08-20 16:43:2212322 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12323 cert_verifier_config.crl_set =
12324 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash});
12325 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3312326
12327 CertStatus cert_status = 0;
12328 DoConnection(ssl_options, &cert_status);
12329
12330 // When the correct SPKI hash is specified, the connection should succeed
12331 // even though the subject is listed in the CRLSet.
12332 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12333 }
12334}
[email protected]316c1e5e2012-09-12 15:17:4412335#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2712336
Sergey Ulanovc4580e72017-09-13 23:30:1112337#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
12338 !defined(OS_FUCHSIA)
12339// FTP uses a second TCP connection with the port number allocated dynamically
12340// on the server side, so it would be hard to make RemoteTestServer proxy FTP
12341// connections reliably. FTP tests are disabled on platforms that use
12342// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3112343class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1112344 public:
[email protected]d9fca99a2012-02-24 16:16:2012345 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0512346 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5512347 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4712348 // Can't use |default_context_|'s HostResolver to set up the
12349 // FTPTransactionFactory because it hasn't been created yet.
Ryan Sleevib8449e02018-07-15 04:31:0712350 default_context().set_host_resolver(&host_resolver_);
mmenke9f2ec60c2015-06-01 20:59:4712351 }
12352
12353 // URLRequestTest interface:
12354 void SetUpFactory() override {
12355 // Add FTP support to the default URLRequestContext.
12356 job_factory_impl_->SetProtocolHandler(
Emily Stark01227982019-06-06 18:45:5612357 "ftp", FtpProtocolHandler::Create(&host_resolver_, &ftp_auth_cache_));
mmenke9f2ec60c2015-06-01 20:59:4712358 }
12359
12360 std::string GetTestFileContents() {
12361 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1912362 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4712363 path = path.Append(kTestFilePath);
12364 path = path.AppendASCII(kFtpTestFile);
12365 std::string contents;
12366 EXPECT_TRUE(base::ReadFileToString(path, &contents));
12367 return contents;
[email protected]95409e12010-08-17 20:07:1112368 }
12369
[email protected]b89ca032009-08-31 21:41:3112370 protected:
mmenke9f2ec60c2015-06-01 20:59:4712371 MockHostResolver host_resolver_;
Emily Stark01227982019-06-06 18:45:5612372 FtpAuthCache ftp_auth_cache_;
mmenke9f2ec60c2015-06-01 20:59:4712373
tommycli59a63432015-11-06 00:10:5512374 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3112375};
12376
[email protected]d2a133182012-08-05 16:44:0812377// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0912378TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0812379 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0812380
12381 TestDelegate d;
12382 {
Ryan Sleevib8449e02018-07-15 04:31:0712383 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612384 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912385 r->Start();
12386 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0812387
Wez2a31b222018-06-07 22:07:1512388 d.RunUntilComplete();
[email protected]d2a133182012-08-05 16:44:0812389
[email protected]f7022f32014-08-21 16:32:1912390 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5012391 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0812392 }
12393}
12394
mmenke9f2ec60c2015-06-01 20:59:4712395TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5512396 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112397
[email protected]a25e90e2009-09-09 17:05:3712398 TestDelegate d;
12399 {
Ryan Sleevib8449e02018-07-15 04:31:0712400 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612401 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
12402 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912403 r->Start();
12404 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712405
Wez2a31b222018-06-07 22:07:1512406 d.RunUntilComplete();
[email protected]a25e90e2009-09-09 17:05:3712407
[email protected]f7022f32014-08-21 16:32:1912408 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712409 EXPECT_EQ(1, d.response_started_count());
12410 EXPECT_FALSE(d.received_data_before_response());
12411 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5512412 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712413 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512414 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712415 r->GetResponseRemoteEndpoint().port());
[email protected]a25e90e2009-09-09 17:05:3712416 }
12417}
12418
mmenke9f2ec60c2015-06-01 20:59:4712419TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5512420 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112421
[email protected]dd265012009-01-08 20:45:2712422 TestDelegate d;
12423 {
Ryan Sleevib8449e02018-07-15 04:31:0712424 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612425 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
12426 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912427 r->Start();
12428 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712429
Wez2a31b222018-06-07 22:07:1512430 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712431
[email protected]f7022f32014-08-21 16:32:1912432 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712433 EXPECT_EQ(1, d.response_started_count());
12434 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712435 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512436 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712437 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512438 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712439 r->GetResponseRemoteEndpoint().port());
[email protected]dd265012009-01-08 20:45:2712440 }
12441}
12442
Mike West80462a12018-11-27 16:05:0612443TEST_F(URLRequestTestFTP, FTPMimeType) {
12444 ASSERT_TRUE(ftp_test_server_.Start());
12445
12446 struct {
12447 const char* path;
12448 const char* mime;
12449 } test_cases[] = {
12450 {"/", "text/vnd.chromium.ftp-dir"},
12451 {kFtpTestFile, "application/octet-stream"},
12452 };
12453
12454 for (const auto test : test_cases) {
12455 TestDelegate d;
12456
12457 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
12458 ftp_test_server_.GetURL(test.path), DEFAULT_PRIORITY, &d,
12459 TRAFFIC_ANNOTATION_FOR_TESTS));
12460 r->Start();
12461 EXPECT_TRUE(r->is_pending());
12462
12463 d.RunUntilComplete();
12464
12465 std::string mime;
12466 r->GetMimeType(&mime);
12467 EXPECT_EQ(test.mime, mime);
12468 }
12469}
12470
mmenke9f2ec60c2015-06-01 20:59:4712471TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5512472 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112473
[email protected]dd265012009-01-08 20:45:2712474 TestDelegate d;
12475 {
Ryan Sleevib8449e02018-07-15 04:31:0712476 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512477 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12478 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612479 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912480 r->Start();
12481 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712482
Wez2a31b222018-06-07 22:07:1512483 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712484
[email protected]f7022f32014-08-21 16:32:1912485 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4712486 EXPECT_EQ(1, d.response_started_count());
12487 EXPECT_FALSE(d.received_data_before_response());
12488 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512489 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712490 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512491 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712492 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:2512493
12494 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1912495 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2512496 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2712497 }
12498}
12499
mmenke9f2ec60c2015-06-01 20:59:4712500TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5512501 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112502
[email protected]dd265012009-01-08 20:45:2712503 TestDelegate d;
12504 {
Ryan Sleevib8449e02018-07-15 04:31:0712505 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512506 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12507 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612508 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912509 r->Start();
12510 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712511
Wez2a31b222018-06-07 22:07:1512512 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712513
[email protected]f7022f32014-08-21 16:32:1912514 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712515 EXPECT_EQ(1, d.response_started_count());
12516 EXPECT_FALSE(d.received_data_before_response());
12517 EXPECT_EQ(d.bytes_received(), 0);
12518 }
12519}
12520
mmenke9f2ec60c2015-06-01 20:59:4712521TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5512522 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112523
[email protected]8b8a197d2009-08-26 15:57:5812524 TestDelegate d;
12525 // Set correct login credentials. The delegate will be asked for them when
12526 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812527 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812528 {
Ryan Sleevib8449e02018-07-15 04:31:0712529 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512530 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12531 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612532 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912533 r->Start();
12534 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812535
Wez2a31b222018-06-07 22:07:1512536 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812537
[email protected]f7022f32014-08-21 16:32:1912538 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812539 EXPECT_EQ(1, d.response_started_count());
12540 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712541 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812542 }
12543}
12544
mmenke9f2ec60c2015-06-01 20:59:4712545TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5512546 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112547
[email protected]dd265012009-01-08 20:45:2712548 TestDelegate d;
12549 {
Ryan Sleevib8449e02018-07-15 04:31:0712550 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512551 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12552 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612553 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912554 r->Start();
12555 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712556
Wez2a31b222018-06-07 22:07:1512557 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712558
[email protected]f7022f32014-08-21 16:32:1912559 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712560 EXPECT_EQ(1, d.response_started_count());
12561 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712562 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2712563 }
12564}
[email protected]8b8a197d2009-08-26 15:57:5812565
mmenke9f2ec60c2015-06-01 20:59:4712566TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5512567 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112568
[email protected]8b8a197d2009-08-26 15:57:5812569 TestDelegate d;
12570 // Set correct login credentials. The delegate will be asked for them when
12571 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812572 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812573 {
Ryan Sleevib8449e02018-07-15 04:31:0712574 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512575 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12576 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612577 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912578 r->Start();
12579 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812580
Wez2a31b222018-06-07 22:07:1512581 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812582
[email protected]f7022f32014-08-21 16:32:1912583 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812584 EXPECT_EQ(1, d.response_started_count());
12585 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712586 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812587 }
12588}
[email protected]60a3df52009-09-22 16:13:2412589
mmenke9f2ec60c2015-06-01 20:59:4712590TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5512591 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112592
danakj8522a25b2016-04-16 00:17:3612593 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412594 {
12595 // Pass correct login identity in the URL.
Ryan Sleevib8449e02018-07-15 04:31:0712596 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512597 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12598 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612599 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912600 r->Start();
12601 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412602
Wez2a31b222018-06-07 22:07:1512603 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412604
[email protected]f7022f32014-08-21 16:32:1912605 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412606 EXPECT_EQ(1, d->response_started_count());
12607 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712608 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412609 }
12610
12611 d.reset(new TestDelegate);
12612 {
12613 // This request should use cached identity from previous request.
Ryan Sleevib8449e02018-07-15 04:31:0712614 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612615 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12616 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912617 r->Start();
12618 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412619
Wez2a31b222018-06-07 22:07:1512620 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412621
[email protected]f7022f32014-08-21 16:32:1912622 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412623 EXPECT_EQ(1, d->response_started_count());
12624 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712625 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412626 }
12627}
12628
mmenke9f2ec60c2015-06-01 20:59:4712629TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5512630 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112631
danakj8522a25b2016-04-16 00:17:3612632 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412633 // Set correct login credentials. The delegate will be asked for them when
12634 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812635 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2412636 {
Ryan Sleevib8449e02018-07-15 04:31:0712637 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512638 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12639 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612640 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912641 r->Start();
12642 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412643
Wez2a31b222018-06-07 22:07:1512644 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412645
[email protected]f7022f32014-08-21 16:32:1912646 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412647 EXPECT_EQ(1, d->response_started_count());
12648 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712649 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412650 }
12651
12652 // Use a new delegate without explicit credentials. The cached ones should be
12653 // used.
12654 d.reset(new TestDelegate);
12655 {
12656 // Don't pass wrong credentials in the URL, they would override valid cached
12657 // ones.
Ryan Sleevib8449e02018-07-15 04:31:0712658 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612659 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12660 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912661 r->Start();
12662 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412663
Wez2a31b222018-06-07 22:07:1512664 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412665
[email protected]f7022f32014-08-21 16:32:1912666 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412667 EXPECT_EQ(1, d->response_started_count());
12668 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712669 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412670 }
12671}
ricea3a1c71f2016-06-17 10:05:2612672
12673TEST_F(URLRequestTestFTP, RawBodyBytes) {
12674 ASSERT_TRUE(ftp_test_server_.Start());
12675
12676 TestDelegate d;
12677 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612678 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12679 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2612680 req->Start();
Wez2a31b222018-06-07 22:07:1512681 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:2612682
12683 EXPECT_EQ(6, req->GetRawBodyBytes());
12684}
12685
Matt Menkef1b97e02019-05-13 23:52:4112686class URLRequestTestFTPOverHttpProxy : public URLRequestTestFTP {
12687 public:
12688 // Test interface:
12689 void SetUp() override {
12690 proxy_resolution_service_ = ProxyResolutionService::CreateFixed(
12691 "localhost", TRAFFIC_ANNOTATION_FOR_TESTS);
12692 default_context_->set_proxy_resolution_service(
12693 proxy_resolution_service_.get());
12694 URLRequestTestFTP::SetUp();
12695 }
12696
12697 private:
12698 std::unique_ptr<ProxyResolutionService> proxy_resolution_service_;
12699};
12700
12701// Check that FTP is not supported over an HTTP proxy.
12702TEST_F(URLRequestTestFTPOverHttpProxy, Fails) {
12703 TestDelegate delegate;
12704 std::unique_ptr<URLRequest> request(
12705 default_context_->CreateRequest(GURL("ftp://foo.test/"), DEFAULT_PRIORITY,
12706 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12707 request->Start();
12708 delegate.RunUntilComplete();
12709
12710 EXPECT_THAT(delegate.request_status(), IsError(ERR_NO_SUPPORTED_PROXIES));
12711}
12712
brettwa1228ebb2016-10-28 03:51:3412713#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5112714
ttuttlec0c828492015-05-15 01:25:5512715TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
12716 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712717 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612718 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512719
12720 EXPECT_FALSE(req->response_info().network_accessed);
12721
12722 req->Start();
Wez2a31b222018-06-07 22:07:1512723 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512724
12725 EXPECT_EQ(1, default_network_delegate_.completed_requests());
12726 EXPECT_FALSE(req->response_info().network_accessed);
12727}
12728
12729TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
12730 MockHostResolver host_resolver;
12731 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
12732 TestURLRequestContext context(true);
12733 context.set_network_delegate(&network_delegate);
12734 context.set_host_resolver(&host_resolver);
12735 host_resolver.rules()->AddSimulatedFailure("*");
12736 context.Init();
12737
12738 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612739 std::unique_ptr<URLRequest> req(
12740 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
12741 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512742
12743 EXPECT_FALSE(req->response_info().network_accessed);
12744
12745 req->Start();
Wez2a31b222018-06-07 22:07:1512746 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512747 EXPECT_TRUE(req->response_info().network_accessed);
12748}
12749
mmenkeed0498b2015-12-08 23:20:4212750// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2212751// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4212752TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2212753 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712754 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612755 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
12756 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2212757
danakj8522a25b2016-04-16 00:17:3612758 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2212759 req.get(), &default_network_delegate_,
12760 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4212761 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
12762 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2212763
12764 req->Start();
12765 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2212766 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5012767 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2212768 EXPECT_EQ(0, d.received_redirect_count());
12769}
12770
Andrey Kosyakov2e893e62017-08-31 17:00:5212771TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412772 ASSERT_TRUE(http_test_server()->Start());
12773 TestURLRequestContext context;
12774 GURL url(http_test_server()->GetURL("/cachetime"));
12775 TestDelegate delegate;
12776 HttpRequestHeaders extra_headers;
12777 extra_headers.SetHeader("X-Foo", "bar");
12778
12779 {
Andrey Kosyakov2e893e62017-08-31 17:00:5212780 HttpRawRequestHeaders raw_req_headers;
12781 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12782
Andrey Kosyakov83a6eee2017-08-14 19:20:0412783 std::unique_ptr<URLRequest> r(context.CreateRequest(
12784 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12785 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212786 r->SetRequestHeadersCallback(base::Bind(
12787 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
12788 r->SetResponseHeadersCallback(base::Bind(
12789 [](scoped_refptr<const HttpResponseHeaders>* left,
12790 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12791 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412792 r->Start();
12793 while (!delegate.response_started_count())
12794 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5212795 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412796 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212797 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412798 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212799 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412800 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212801 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
12802 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
12803 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
12804 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412805 }
12806 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412807 std::unique_ptr<URLRequest> r(context.CreateRequest(
12808 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12809 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212810 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412811 FAIL() << "Callback should not be called unless request is sent";
12812 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212813 r->SetResponseHeadersCallback(
12814 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
12815 FAIL() << "Callback should not be called unless request is sent";
12816 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412817 r->Start();
Wez2a31b222018-06-07 22:07:1512818 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412819 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412820 }
12821}
12822
Andrey Kosyakov2e893e62017-08-31 17:00:5212823TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412824 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5212825 HttpRawRequestHeaders raw_req_headers;
12826 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12827
Andrey Kosyakov83a6eee2017-08-14 19:20:0412828 TestURLRequestContext context;
12829 TestDelegate delegate;
12830 HttpRequestHeaders extra_headers;
12831 extra_headers.SetHeader("X-Foo", "bar");
Andrey Kosyakov83a6eee2017-08-14 19:20:0412832 GURL url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:0712833 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412834 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12835 r->SetExtraRequestHeaders(extra_headers);
12836 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5212837 base::Unretained(&raw_req_headers)));
12838 r->SetResponseHeadersCallback(base::Bind(
12839 [](scoped_refptr<const HttpResponseHeaders>* left,
12840 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12841 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412842 r->Start();
Wez0e717112018-06-18 23:09:2212843 delegate.RunUntilRedirect();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412844
12845 ASSERT_EQ(1, delegate.received_redirect_count());
12846 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212847 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412848 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212849 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412850 EXPECT_EQ("gzip, deflate", value);
12851 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5212852 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
12853 raw_req_headers.request_line());
12854 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
12855 EXPECT_EQ(302, raw_resp_headers->response_code());
12856 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412857
Andrey Kosyakov2e893e62017-08-31 17:00:5212858 raw_req_headers = HttpRawRequestHeaders();
12859 raw_resp_headers = nullptr;
Arthur Sonzognib8465ff72019-01-04 18:44:3512860 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
12861 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:1512862 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212863 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412864 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212865 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412866 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212867 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
12868 raw_req_headers.request_line());
12869 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412870}
12871
Andrey Kosyakov2e893e62017-08-31 17:00:5212872TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412873 TestDelegate request_delegate;
12874
Ryan Sleevib8449e02018-07-15 04:31:0712875 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412876 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
12877 TRAFFIC_ANNOTATION_FOR_TESTS));
12878 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
12879 FAIL() << "Callback should not be called unless request is sent";
12880 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212881 r->SetResponseHeadersCallback(
12882 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12883 FAIL() << "Callback should not be called unless request is sent";
12884 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412885 r->Start();
Wez2a31b222018-06-07 22:07:1512886 request_delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412887 EXPECT_FALSE(r->is_pending());
12888}
12889
Andrey Kosyakov2e893e62017-08-31 17:00:5212890TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412891 ASSERT_TRUE(http_test_server()->Start());
12892 GURL url(http_test_server()->GetURL("/auth-basic"));
12893
12894 TestURLRequestContext context;
12895 TestDelegate delegate;
12896
12897 delegate.set_credentials(AuthCredentials(kUser, kSecret));
12898 HttpRequestHeaders extra_headers;
12899 extra_headers.SetHeader("X-Foo", "bar");
12900
Andrey Kosyakov2e893e62017-08-31 17:00:5212901 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
12902 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0412903
Andrey Kosyakov2e893e62017-08-31 17:00:5212904 using RespHeadersVector =
12905 std::vector<scoped_refptr<const HttpResponseHeaders>>;
12906 RespHeadersVector raw_resp_headers;
12907
12908 auto req_headers_callback = base::Bind(
12909 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
12910 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
12911 },
12912 &raw_req_headers);
12913 auto resp_headers_callback = base::Bind(
12914 [](RespHeadersVector* vec,
12915 scoped_refptr<const HttpResponseHeaders> headers) {
12916 vec->push_back(headers);
12917 },
12918 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412919 std::unique_ptr<URLRequest> r(context.CreateRequest(
12920 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12921 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212922 r->SetRequestHeadersCallback(req_headers_callback);
12923 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412924 r->Start();
Wez2a31b222018-06-07 22:07:1512925 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412926 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5212927 ASSERT_EQ(raw_req_headers.size(), 2u);
12928 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412929 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212930 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
12931 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412932 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212933 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
12934 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412935 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212936 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
12937 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
12938 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
12939 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
12940
12941 std::unique_ptr<URLRequest> r2(context.CreateRequest(
12942 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12943 r2->SetExtraRequestHeaders(extra_headers);
12944 r2->SetRequestHeadersCallback(req_headers_callback);
12945 r2->SetResponseHeadersCallback(resp_headers_callback);
12946 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
12947 r2->Start();
Wez2a31b222018-06-07 22:07:1512948 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212949 EXPECT_FALSE(r2->is_pending());
12950 ASSERT_EQ(raw_req_headers.size(), 3u);
12951 ASSERT_EQ(raw_resp_headers.size(), 3u);
12952 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
12953 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
12954 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
12955 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412956}
12957
Andrey Kosyakov2e893e62017-08-31 17:00:5212958TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412959 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
12960 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712961 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412962 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12963 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5212964 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0412965 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212966 r->SetResponseHeadersCallback(
12967 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12968 FAIL() << "Callback should not be called for non-HTTP schemes";
12969 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412970 r->Start();
Wez2a31b222018-06-07 22:07:1512971 d.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412972 EXPECT_FALSE(r->is_pending());
12973}
12974
Carlos ILaef65d62018-06-04 21:24:1312975TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
12976 TestDelegate d;
12977 BlockingNetworkDelegate network_delegate(
12978 BlockingNetworkDelegate::SYNCHRONOUS);
12979 const GURL kOriginalUrl("https://original.test");
12980 const GURL kRedirectUrl("http://redirect.test");
12981 network_delegate.set_redirect_url(kRedirectUrl);
12982 TestURLRequestContext context(true /* delay_initialization */);
12983 context.set_network_delegate(&network_delegate);
12984 context.Init();
12985
12986 std::unique_ptr<URLRequest> r(context.CreateRequest(
12987 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12988 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1312989 r->Start();
Wez0e717112018-06-18 23:09:2212990 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1312991 GURL::Replacements replacements;
12992 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12993 // was set.
12994 replacements.SetSchemeStr("https");
12995 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12996 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4412997 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1312998}
12999
13000TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
13001 TestDelegate d;
13002 BlockingNetworkDelegate network_delegate(
13003 BlockingNetworkDelegate::SYNCHRONOUS);
13004 const GURL kOriginalUrl("https://original.test");
13005 const GURL kRedirectUrl("http://redirect.test:80");
13006 network_delegate.set_redirect_url(kRedirectUrl);
13007 TestURLRequestContext context(true /* delay_initialization */);
13008 context.set_network_delegate(&network_delegate);
13009 context.Init();
13010
13011 std::unique_ptr<URLRequest> r(context.CreateRequest(
13012 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13013 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1313014 r->Start();
Wez0e717112018-06-18 23:09:2213015 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313016 GURL::Replacements replacements;
13017 // The URL host should have not been changed.
13018 EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
13019 // The scheme should now be https, and the effective port should now be 443.
13020 EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
13021 EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
Carlos IL0d67fc72018-06-22 17:18:4413022 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313023}
13024
13025TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
13026 TestDelegate d;
13027 BlockingNetworkDelegate network_delegate(
13028 BlockingNetworkDelegate::SYNCHRONOUS);
13029 const GURL kOriginalUrl("https://original.test");
13030 const GURL kRedirectUrl("http://redirect.test:1234");
13031 network_delegate.set_redirect_url(kRedirectUrl);
13032 TestURLRequestContext context(true /* delay_initialization */);
13033 context.set_network_delegate(&network_delegate);
13034 context.Init();
13035
13036 std::unique_ptr<URLRequest> r(context.CreateRequest(
13037 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13038 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1313039 r->Start();
Wez0e717112018-06-18 23:09:2213040 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313041 GURL::Replacements replacements;
13042 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
13043 // was set, nonstandard port should not have been modified.
13044 replacements.SetSchemeStr("https");
13045 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
13046 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4413047 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313048}
13049
13050TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
13051 TestDelegate d;
13052 BlockingNetworkDelegate network_delegate(
13053 BlockingNetworkDelegate::SYNCHRONOUS);
13054 const GURL kOriginalUrl("https://original.test");
13055 const GURL kRedirectUrl("http://redirect.test");
13056 network_delegate.set_redirect_url(kRedirectUrl);
13057 TestURLRequestContext context(true /* delay_initialization */);
13058 context.set_network_delegate(&network_delegate);
13059 context.Init();
13060 std::unique_ptr<URLRequest> r(context.CreateRequest(
13061 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13062 r->set_upgrade_if_insecure(false);
Carlos ILaef65d62018-06-04 21:24:1313063 r->Start();
Wez0e717112018-06-18 23:09:2213064 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313065 // The redirect URL should not be changed if the upgrade_if_insecure flag is
13066 // not set.
13067 EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4413068 EXPECT_FALSE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313069}
13070
Paul Jensen60e45532018-02-19 16:04:1813071// Test that URLRequests get properly tagged.
13072#if defined(OS_ANDROID)
13073TEST_F(URLRequestTestHTTP, TestTagging) {
Peter Collingbourne8ccab722019-02-12 18:10:4813074 if (!CanGetTaggedBytes()) {
13075 DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
13076 return;
13077 }
13078
Paul Jensen60e45532018-02-19 16:04:1813079 ASSERT_TRUE(http_test_server()->Start());
13080
13081 // The tag under which the system reports untagged traffic.
13082 static const int32_t UNTAGGED_TAG = 0;
13083
13084 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
13085
13086 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
13087 TestDelegate delegate;
Ryan Sleevib8449e02018-07-15 04:31:0713088 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Paul Jensen60e45532018-02-19 16:04:1813089 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
13090 TRAFFIC_ANNOTATION_FOR_TESTS));
13091 EXPECT_EQ(SocketTag(), req->socket_tag());
13092 req->Start();
Wez2a31b222018-06-07 22:07:1513093 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1813094
13095 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
13096
13097 int32_t tag_val1 = 0x12345678;
13098 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
13099 old_traffic = GetTaggedBytes(tag_val1);
13100
13101 // Test specific tag value.
Ryan Sleevib8449e02018-07-15 04:31:0713102 req = default_context().CreateRequest(http_test_server()->GetURL("/"),
13103 DEFAULT_PRIORITY, &delegate,
13104 TRAFFIC_ANNOTATION_FOR_TESTS);
Paul Jensen60e45532018-02-19 16:04:1813105 req->set_socket_tag(tag1);
13106 EXPECT_EQ(tag1, req->socket_tag());
13107 req->Start();
Wez2a31b222018-06-07 22:07:1513108 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1813109
13110 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
13111}
13112#endif
13113
Steven Valdez1c1859172019-04-10 15:33:2813114// Provides a response to the 0RTT request indicating whether it was received
13115// as early data, sending HTTP_TOO_EARLY if enabled.
13116class ZeroRTTResponse : public test_server::BasicHttpResponse {
13117 public:
13118 ZeroRTTResponse(bool zero_rtt, bool send_too_early)
13119 : zero_rtt_(zero_rtt), send_too_early_(send_too_early) {}
13120 ~ZeroRTTResponse() override {}
13121
13122 void SendResponse(const test_server::SendBytesCallback& send,
13123 const test_server::SendCompleteCallback& done) override {
13124 AddCustomHeader("Vary", "Early-Data");
13125 set_content_type("text/plain");
13126 AddCustomHeader("Cache-Control", "no-cache");
13127 if (zero_rtt_) {
13128 if (send_too_early_)
13129 set_code(HTTP_TOO_EARLY);
13130 set_content("1");
13131 } else {
13132 set_content("0");
13133 }
13134
13135 // Since the EmbeddedTestServer doesn't keep the socket open by default,
13136 // it is explicitly kept alive to allow the remaining leg of the 0RTT
13137 // handshake to be received after the early data.
13138 send.Run(ToResponseString(), base::DoNothing());
13139 }
13140
13141 private:
13142 bool zero_rtt_;
13143 bool send_too_early_;
13144
13145 DISALLOW_COPY_AND_ASSIGN(ZeroRTTResponse);
13146};
13147
13148std::unique_ptr<test_server::HttpResponse> HandleZeroRTTRequest(
13149 const test_server::HttpRequest& request) {
13150 if (request.GetURL().path() != "/zerortt")
13151 return nullptr;
13152 auto iter = request.headers.find("Early-Data");
13153 bool zero_rtt = iter != request.headers.end() && iter->second == "1";
13154 return std::make_unique<ZeroRTTResponse>(zero_rtt, false);
13155}
13156
13157class HTTPSEarlyDataTest : public TestWithScopedTaskEnvironment {
13158 public:
13159 HTTPSEarlyDataTest()
13160 : context_(true), test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
13161 auto params = std::make_unique<HttpNetworkSession::Params>();
13162 params->enable_early_data = true;
13163 context_.set_http_network_session_params(std::move(params));
13164
13165 context_.set_network_delegate(&network_delegate_);
13166 cert_verifier_.set_default_result(OK);
13167 context_.set_cert_verifier(&cert_verifier_);
13168
13169 ssl_config_service_ = std::make_unique<TestSSLConfigService>();
13170 ssl_config_service_->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
13171 context_.set_ssl_config_service(ssl_config_service_.get());
13172
13173 context_.Init();
13174
13175 ssl_config_.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
13176 ssl_config_.early_data_enabled = true;
13177 test_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config_);
13178 test_server_.AddDefaultHandlers(
13179 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
13180 test_server_.RegisterRequestHandler(
13181 base::BindRepeating(&HandleZeroRTTRequest));
13182 }
13183
13184 ~HTTPSEarlyDataTest() override = default;
13185
13186 void ResetSSLConfig(net::EmbeddedTestServer::ServerCertificate cert,
13187 uint16_t version) {
13188 ssl_config_.version_max = version;
13189 test_server_.ResetSSLConfig(cert, ssl_config_);
13190 }
13191
13192 protected:
13193 MockCertVerifier cert_verifier_;
13194 TestNetworkDelegate network_delegate_; // Must outlive URLRequest.
13195 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
13196 TestURLRequestContext context_;
13197
13198 SSLServerConfig ssl_config_;
13199 EmbeddedTestServer test_server_;
13200};
13201
13202// TLSEarlyDataTest tests that we handle early data correctly.
13203TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTest) {
13204 ASSERT_TRUE(test_server_.Start());
13205 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13206
13207 {
13208 TestDelegate d;
13209 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13210 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13211 TRAFFIC_ANNOTATION_FOR_TESTS));
13212 r->Start();
13213 EXPECT_TRUE(r->is_pending());
13214
13215 base::RunLoop().Run();
13216
13217 EXPECT_EQ(1, d.response_started_count());
13218
13219 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13220 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13221 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13222 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13223 r->ssl_info().cert.get()));
13224
13225 // The Early-Data header should be omitted in the initial request, and the
13226 // handler should return "0".
13227 EXPECT_EQ("0", d.data_received());
13228 }
13229
13230 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13231
13232 {
13233 TestDelegate d;
13234 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13235 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13236 TRAFFIC_ANNOTATION_FOR_TESTS));
13237
13238 r->Start();
13239 EXPECT_TRUE(r->is_pending());
13240
13241 base::RunLoop().Run();
13242
13243 EXPECT_EQ(1, d.response_started_count());
13244
13245 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13246 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13247 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13248 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13249 r->ssl_info().cert.get()));
13250
13251 // The Early-Data header should be a single '1' in the resumed request, and
13252 // the handler should return "1".
13253 EXPECT_EQ("1", d.data_received());
13254 }
13255}
13256
13257// TLSEarlyDataTest tests that we handle early data correctly for POST.
13258TEST_F(HTTPSEarlyDataTest, TLSEarlyDataPOSTTest) {
13259 ASSERT_TRUE(test_server_.Start());
13260 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13261
13262 {
13263 TestDelegate d;
13264 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13265 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13266 TRAFFIC_ANNOTATION_FOR_TESTS));
13267 r->Start();
13268 EXPECT_TRUE(r->is_pending());
13269
13270 base::RunLoop().Run();
13271
13272 EXPECT_EQ(1, d.response_started_count());
13273
13274 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13275 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13276 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13277 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13278 r->ssl_info().cert.get()));
13279
13280 // The Early-Data header should be omitted in the initial request, and the
13281 // handler should return "0".
13282 EXPECT_EQ("0", d.data_received());
13283 }
13284
13285 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13286
13287 {
13288 TestDelegate d;
13289 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13290 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13291 TRAFFIC_ANNOTATION_FOR_TESTS));
13292 r->set_method("POST");
13293 r->Start();
13294 EXPECT_TRUE(r->is_pending());
13295
13296 base::RunLoop().Run();
13297
13298 EXPECT_EQ(1, d.response_started_count());
13299
13300 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13301 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13302 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13303 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13304 r->ssl_info().cert.get()));
13305
13306 // The Early-Data header should be omitted in the request, since we don't
13307 // send POSTs over early data, and the handler should return "0".
13308 EXPECT_EQ("0", d.data_received());
13309 }
13310}
13311
13312std::unique_ptr<test_server::HttpResponse> HandleTooEarly(
13313 bool* sent_425,
13314 const test_server::HttpRequest& request) {
13315 if (request.GetURL().path() != "/tooearly")
13316 return nullptr;
13317 auto iter = request.headers.find("Early-Data");
13318 bool zero_rtt = iter != request.headers.end() && iter->second == "1";
13319 if (zero_rtt)
13320 *sent_425 = true;
13321 return std::make_unique<ZeroRTTResponse>(zero_rtt, true);
13322}
13323
13324// Test that we handle 425 (Too Early) correctly.
13325TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTooEarlyTest) {
13326 bool sent_425 = false;
13327 test_server_.RegisterRequestHandler(
13328 base::BindRepeating(&HandleTooEarly, base::Unretained(&sent_425)));
13329 ASSERT_TRUE(test_server_.Start());
13330 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13331
13332 {
13333 TestDelegate d;
13334 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13335 test_server_.GetURL("/tooearly"), DEFAULT_PRIORITY, &d,
13336 TRAFFIC_ANNOTATION_FOR_TESTS));
13337 r->Start();
13338 EXPECT_TRUE(r->is_pending());
13339
13340 d.RunUntilComplete();
13341
13342 EXPECT_EQ(1, d.response_started_count());
13343
13344 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13345 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13346 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13347 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13348 r->ssl_info().cert.get()));
13349
13350 // The Early-Data header should be omitted in the initial request, and the
13351 // handler should return "0".
13352 EXPECT_EQ("0", d.data_received());
13353 EXPECT_FALSE(sent_425);
13354 }
13355
13356 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13357
13358 {
13359 TestDelegate d;
13360 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13361 test_server_.GetURL("/tooearly"), DEFAULT_PRIORITY, &d,
13362 TRAFFIC_ANNOTATION_FOR_TESTS));
13363
13364 r->Start();
13365 EXPECT_TRUE(r->is_pending());
13366
13367 d.RunUntilComplete();
13368
13369 EXPECT_EQ(1, d.response_started_count());
13370
13371 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13372 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13373 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13374 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13375 r->ssl_info().cert.get()));
13376
13377 // The resumption request will encounter a 425 error and retry without early
13378 // data, and the handler should return "0".
13379 EXPECT_EQ("0", d.data_received());
13380 EXPECT_TRUE(sent_425);
13381 }
13382}
13383
13384// TLSEarlyDataRejectTest tests that we gracefully handle an early data reject
13385// and retry without early data.
13386TEST_F(HTTPSEarlyDataTest, TLSEarlyDataRejectTest) {
13387 ASSERT_TRUE(test_server_.Start());
13388 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13389
13390 {
13391 TestDelegate d;
13392 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13393 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13394 TRAFFIC_ANNOTATION_FOR_TESTS));
13395
13396 r->Start();
13397 EXPECT_TRUE(r->is_pending());
13398
13399 d.RunUntilComplete();
13400
13401 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13402 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13403 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13404 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13405 r->ssl_info().cert.get()));
13406
13407 // The Early-Data header should be omitted in the initial request, and the
13408 // handler should return "0".
13409 EXPECT_EQ("0", d.data_received());
13410 }
13411
13412 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13413
13414 // The certificate in the resumption is changed to confirm that the
13415 // certificate change is observed.
13416 scoped_refptr<X509Certificate> old_cert = test_server_.GetCertificate();
13417 ResetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED,
13418 SSL_PROTOCOL_VERSION_TLS1_3);
13419
13420 {
13421 TestDelegate d;
13422 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13423 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13424 TRAFFIC_ANNOTATION_FOR_TESTS));
13425
13426 r->Start();
13427 EXPECT_TRUE(r->is_pending());
13428
13429 d.RunUntilComplete();
13430
13431 EXPECT_EQ(1, d.response_started_count());
13432
13433 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13434 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13435 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13436 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13437 r->ssl_info().cert.get()));
13438 EXPECT_FALSE(old_cert->EqualsIncludingChain(r->ssl_info().cert.get()));
13439
13440 // The Early-Data header should be omitted in the rejected request, and the
13441 // handler should return "0".
13442 EXPECT_EQ("0", d.data_received());
13443 }
13444}
13445
13446// TLSEarlyDataTLS12RejectTest tests that we gracefully handle an early data
13447// reject from a TLS 1.2 server and retry without early data.
13448TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTLS12RejectTest) {
13449 ASSERT_TRUE(test_server_.Start());
13450 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13451
13452 {
13453 TestDelegate d;
13454 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13455 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13456 TRAFFIC_ANNOTATION_FOR_TESTS));
13457
13458 r->Start();
13459 EXPECT_TRUE(r->is_pending());
13460
13461 d.RunUntilComplete();
13462
13463 EXPECT_EQ(1, d.response_started_count());
13464
13465 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13466 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13467 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13468 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13469 r->ssl_info().cert.get()));
13470
13471 // The Early-Data header should be omitted in the initial request, and the
13472 // handler should return "0".
13473 EXPECT_EQ("0", d.data_received());
13474 }
13475
13476 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13477
13478 // The certificate in the resumption is changed to confirm that the
13479 // certificate change is observed.
13480 scoped_refptr<X509Certificate> old_cert = test_server_.GetCertificate();
13481 ResetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED,
13482 SSL_PROTOCOL_VERSION_TLS1_2);
13483
13484 {
13485 TestDelegate d;
13486 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13487 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13488 TRAFFIC_ANNOTATION_FOR_TESTS));
13489
13490 r->Start();
13491 EXPECT_TRUE(r->is_pending());
13492
13493 d.RunUntilComplete();
13494
13495 EXPECT_EQ(1, d.response_started_count());
13496
13497 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_2,
13498 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13499 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13500 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13501 r->ssl_info().cert.get()));
13502 EXPECT_FALSE(old_cert->EqualsIncludingChain(r->ssl_info().cert.get()));
13503
13504 // The Early-Data header should be omitted in the rejected request, and the
13505 // handler should return "0".
13506 EXPECT_EQ("0", d.data_received());
13507 }
13508}
13509
Emily Stark08f6c972019-05-28 17:24:2713510// Tests that AuthChallengeInfo is available on the request.
13511TEST_F(URLRequestTestHTTP, AuthChallengeInfo) {
13512 ASSERT_TRUE(http_test_server()->Start());
13513 GURL url(http_test_server()->GetURL("/auth-basic"));
13514
13515 TestURLRequestContext context;
13516 TestDelegate delegate;
13517
13518 std::unique_ptr<URLRequest> r(context.CreateRequest(
13519 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
13520 r->Start();
13521 delegate.RunUntilComplete();
13522 ASSERT_TRUE(r->auth_challenge_info().has_value());
13523 EXPECT_FALSE(r->auth_challenge_info()->is_proxy);
13524 EXPECT_EQ(url::Origin::Create(url), r->auth_challenge_info()->challenger);
13525 EXPECT_EQ("basic", r->auth_challenge_info()->scheme);
13526 EXPECT_EQ("testrealm", r->auth_challenge_info()->realm);
13527 EXPECT_EQ("Basic realm=\"testrealm\"", r->auth_challenge_info()->challenge);
13528 EXPECT_EQ("/auth-basic", r->auth_challenge_info()->path);
13529}
13530
[email protected]7461a402011-03-24 23:19:5113531} // namespace net