blob: d70016506fa96116c4b09de8e6296d2a4eab6db8 [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"
Matt Menke0743e342019-06-11 20:48:1046#include "base/test/bind_test_util.h"
Devlin Cronine4bcb40e2018-06-05 18:02:4747#include "base/test/metrics/histogram_tester.h"
Emily Stark4cfecf072017-08-08 01:05:5148#include "base/test/scoped_feature_list.h"
gabf767595f2016-05-11 18:50:3549#include "base/threading/thread_task_runner_handle.h"
estark06e0dac2015-08-07 21:56:0150#include "base/values.h"
mmenkefd9d15c2017-06-29 13:45:5451#include "build/buildflag.h"
mmenkecbc2b712014-10-09 20:29:0752#include "net/base/chunked_upload_data_stream.h"
tfarina43a416b2016-01-06 21:48:0753#include "net/base/directory_listing.h"
mmenkecbc2b712014-10-09 20:29:0754#include "net/base/elements_upload_data_stream.h"
David Benjamina7fde612019-03-15 14:20:5855#include "net/base/escape.h"
Mike Westfbd44112019-05-08 18:23:3756#include "net/base/features.h"
Aaron Tagliaboschi028009e2019-03-07 16:28:0657#include "net/base/layered_network_delegate.h"
initial.commit586acc5fe2008-07-26 22:42:5258#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2559#include "net/base/load_timing_info.h"
60#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0661#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5262#include "net/base/net_module.h"
Lily Houghton582d4622018-01-22 22:43:4063#include "net/base/proxy_server.h"
[email protected]2ca01e52013-10-31 22:05:1964#include "net/base/request_priority.h"
zhongyi18ddddd2017-02-03 19:06:3665#include "net/base/test_completion_callback.h"
[email protected]f288ef02012-12-15 20:28:2866#include "net/base/upload_bytes_element_reader.h"
67#include "net/base/upload_data_stream.h"
68#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4469#include "net/base/url_util.h"
Matt Muellera4aaa9d2019-04-24 21:09:1470#include "net/cert/cert_net_fetcher.h"
Ryan Sleevib369d712018-08-20 16:43:2271#include "net/cert/crl_set.h"
rsleevid6de8302016-06-21 01:33:2072#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4773#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3674#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1175#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2476#include "net/cert/mock_cert_verifier.h"
zhongyi18ddddd2017-02-03 19:06:3677#include "net/cert/multi_log_ct_verifier.h"
eranmdcec9632016-10-10 14:16:1078#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1179#include "net/cert/test_root_certs.h"
Matt Muellera4aaa9d2019-04-24 21:09:1480#include "net/cert_net/cert_net_fetcher_impl.h"
Aaron Tagliaboschifd4f3f012019-05-30 23:05:5481#include "net/cookies/canonical_cookie_test_helpers.h"
[email protected]aa84a7e2012-03-15 21:29:0682#include "net/cookies/cookie_monster.h"
83#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5284#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5385#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3886#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5287#include "net/http/http_cache.h"
88#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1989#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2590#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2191#include "net/http/http_response_headers.h"
Matt Menke609160742019-08-02 18:47:2692#include "net/http/http_server_properties.h"
[email protected]e50efea2014-03-24 18:41:0093#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0094#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1995#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5196#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4697#include "net/log/test_net_log_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"
David Benjamin151ec6b2019-08-02 19:38:52108#include "net/ssl/test_ssl_config_service.h"
[email protected]6e7845ae2013-03-29 21:48:11109#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:36110#include "net/test/embedded_test_server/embedded_test_server.h"
111#include "net/test/embedded_test_server/http_request.h"
112#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:01113#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21114#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43115#include "net/test/test_data_directory.h"
Bence Béky98447b12018-05-08 03:14:01116#include "net/test/test_with_scoped_task_environment.h"
mmenkefb18c772015-09-30 22:22:50117#include "net/test/url_request/url_request_failed_job.h"
Carlos ILaef65d62018-06-04 21:24:13118#include "net/test/url_request/url_request_mock_http_job.h"
rhalavatib7bd7c792017-04-27 05:25:16119#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34120#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43121#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52122#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50123#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14124#include "net/url_request/url_request_http_job.h"
Thiemo Nagel0793b9c532018-04-18 16:57:58125#include "net/url_request/url_request_http_job_histogram.h"
bengr1bf8e942014-11-07 01:36:50126#include "net/url_request/url_request_intercepting_job_factory.h"
127#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49128#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51129#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47130#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44131#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01132#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52133#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15134#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52135
brettwa1228ebb2016-10-28 03:51:34136#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55137#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29138#include "net/url_request/file_protocol_handler.h"
139#include "net/url_request/url_request_file_dir_job.h"
140#endif
141
brettwa1228ebb2016-10-28 03:51:34142#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
Emily Stark01227982019-06-06 18:45:56143#include "net/ftp/ftp_auth_cache.h"
mmenke9f2ec60c2015-06-01 20:59:47144#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29145#include "net/url_request/ftp_protocol_handler.h"
146#endif
147
[email protected]dffe8242012-03-20 15:14:27148#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48149#include "base/win/scoped_com_initializer.h"
[email protected]dffe8242012-03-20 15:14:27150#endif
151
Matt Mueller7f60dc42019-04-26 22:47:10152#if defined(OS_MACOSX)
153#include "base/mac/mac_util.h"
154#endif
155
mmenkefd9d15c2017-06-29 13:45:54156#if BUILDFLAG(ENABLE_REPORTING)
Julia Tuttlecba7d222018-02-23 19:37:27157#include "net/network_error_logging/network_error_logging_service.h"
Lily Chenfec60d92019-01-24 01:16:42158#include "net/network_error_logging/network_error_logging_test_util.h"
mmenkefd9d15c2017-06-29 13:45:54159#endif // BUILDFLAG(ENABLE_REPORTING)
160
Eric Romanefddd0a2017-10-10 02:14:25161#if defined(USE_NSS_CERTS)
162#include "net/cert_net/nss_ocsp.h"
163#endif
164
robpercival214763f2016-07-01 23:27:01165using net::test::IsError;
166using net::test::IsOk;
167
[email protected]ad65a3e2013-12-25 18:18:01168using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33169using base::Time;
halton.huoe4e45742014-12-08 07:55:46170using std::string;
[email protected]e1acf6f2008-10-27 20:43:33171
[email protected]7461a402011-03-24 23:19:51172namespace net {
173
initial.commit586acc5fe2008-07-26 22:42:52174namespace {
175
Martijn Croonenb1383da2017-10-11 11:56:35176namespace test_default {
177#include "net/http/transport_security_state_static_unittest_default.h"
xunjieli815ad5b2017-07-18 15:51:35178}
179
[email protected]42cba2fb2013-03-29 19:58:57180const base::string16 kChrome(ASCIIToUTF16("chrome"));
181const base::string16 kSecret(ASCIIToUTF16("secret"));
182const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44183
mmenke9f2ec60c2015-06-01 20:59:47184const base::FilePath::CharType kTestFilePath[] =
185 FILE_PATH_LITERAL("net/data/url_request_unittest");
186
Sergey Ulanovc4580e72017-09-13 23:30:11187#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
188 !defined(OS_FUCHSIA)
mmenke9f2ec60c2015-06-01 20:59:47189// Test file used in most FTP tests.
190const char kFtpTestFile[] = "BullRunSpeech.txt";
191#endif
192
[email protected]2bba3252013-04-08 19:50:59193// Tests load timing information in the case a fresh connection was used, with
194// no proxy.
[email protected]cba24642014-08-15 20:49:59195void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25196 int connect_timing_flags) {
197 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19198 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25199
200 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
201 EXPECT_FALSE(load_timing_info.request_start.is_null());
202
203 EXPECT_LE(load_timing_info.request_start,
204 load_timing_info.connect_timing.connect_start);
205 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
206 connect_timing_flags);
207 EXPECT_LE(load_timing_info.connect_timing.connect_end,
208 load_timing_info.send_start);
209 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38210 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
211 EXPECT_LE(load_timing_info.receive_headers_start,
212 load_timing_info.receive_headers_end);
[email protected]58e32bb2013-01-21 18:23:25213
[email protected]58e32bb2013-01-21 18:23:25214 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
215 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
216}
217
[email protected]2bba3252013-04-08 19:50:59218// Same as above, but with proxy times.
219void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59220 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59221 int connect_timing_flags) {
222 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19223 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59224
225 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
226 EXPECT_FALSE(load_timing_info.request_start.is_null());
227
228 EXPECT_LE(load_timing_info.request_start,
229 load_timing_info.proxy_resolve_start);
230 EXPECT_LE(load_timing_info.proxy_resolve_start,
231 load_timing_info.proxy_resolve_end);
232 EXPECT_LE(load_timing_info.proxy_resolve_end,
233 load_timing_info.connect_timing.connect_start);
234 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
235 connect_timing_flags);
236 EXPECT_LE(load_timing_info.connect_timing.connect_end,
237 load_timing_info.send_start);
238 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38239 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
240 EXPECT_LE(load_timing_info.receive_headers_start,
241 load_timing_info.receive_headers_end);
[email protected]2bba3252013-04-08 19:50:59242}
243
244// Same as above, but with a reused socket and proxy times.
245void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59246 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59247 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19248 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59249
250 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
251 EXPECT_FALSE(load_timing_info.request_start.is_null());
252
253 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
254
255 EXPECT_LE(load_timing_info.request_start,
256 load_timing_info.proxy_resolve_start);
257 EXPECT_LE(load_timing_info.proxy_resolve_start,
258 load_timing_info.proxy_resolve_end);
259 EXPECT_LE(load_timing_info.proxy_resolve_end,
260 load_timing_info.send_start);
261 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38262 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
263 EXPECT_LE(load_timing_info.receive_headers_start,
264 load_timing_info.receive_headers_end);
[email protected]2bba3252013-04-08 19:50:59265}
266
brettwa1228ebb2016-10-28 03:51:34267#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25268// Tests load timing information in the case of a cache hit, when no cache
269// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17270base::StringPiece TestNetResourceProvider(int key) {
271 return "header";
272}
273
274void FillBuffer(char* buffer, size_t len) {
275 static bool called = false;
276 if (!called) {
277 called = true;
278 int seed = static_cast<int>(Time::Now().ToInternalValue());
279 srand(seed);
280 }
281
282 for (size_t i = 0; i < len; i++) {
283 buffer[i] = static_cast<char>(rand());
284 if (!buffer[i])
285 buffer[i] = 'g';
286 }
287}
xunjielia6888202015-04-14 21:34:25288#endif
[email protected]e3a85452013-11-14 01:46:17289
Matt Menke0743e342019-06-11 20:48:10290CookieList GetAllCookies(URLRequestContext* request_context) {
291 CookieList cookie_list;
292 base::RunLoop run_loop;
293 request_context->cookie_store()->GetAllCookiesAsync(
294 base::BindLambdaForTesting([&](const CookieList& cookies,
295 const CookieStatusList& excluded_list) {
296 cookie_list = cookies;
297 run_loop.Quit();
298 }));
299 run_loop.Run();
300 return cookie_list;
301}
302
[email protected]3b23a222013-05-15 21:33:25303void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59304 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25305 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19306 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25307
308 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
309 EXPECT_FALSE(load_timing_info.request_start.is_null());
310
311 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
312 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
313 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:38314 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
315 EXPECT_LE(load_timing_info.receive_headers_start,
316 load_timing_info.receive_headers_end);
[email protected]3b23a222013-05-15 21:33:25317
318 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
319 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
320}
321
Sergey Ulanovc4580e72017-09-13 23:30:11322#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
323 !defined(OS_FUCHSIA)
[email protected]3b23a222013-05-15 21:33:25324// Tests load timing in the case that there is no HTTP response. This can be
325// used to test in the case of errors or non-HTTP requests.
326void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59327 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25328 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19329 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25330
331 // Only the request times should be non-null.
332 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
333 EXPECT_FALSE(load_timing_info.request_start.is_null());
334
335 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
336
337 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
338 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
339 EXPECT_TRUE(load_timing_info.send_start.is_null());
340 EXPECT_TRUE(load_timing_info.send_end.is_null());
Andrew Comminos1f2ff1cc2018-12-14 05:22:38341 EXPECT_TRUE(load_timing_info.receive_headers_start.is_null());
[email protected]58e32bb2013-01-21 18:23:25342 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
343}
xunjielia6888202015-04-14 21:34:25344#endif
[email protected]58e32bb2013-01-21 18:23:25345
mmenkeed0498b2015-12-08 23:20:42346// Job that allows monitoring of its priority.
347class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
348 public:
349 // The latest priority of the job is always written to |request_priority_|.
350 PriorityMonitoringURLRequestJob(URLRequest* request,
351 NetworkDelegate* network_delegate,
352 RequestPriority* request_priority)
353 : URLRequestTestJob(request, network_delegate),
354 request_priority_(request_priority) {
355 *request_priority_ = DEFAULT_PRIORITY;
356 }
357
358 void SetPriority(RequestPriority priority) override {
359 *request_priority_ = priority;
360 URLRequestTestJob::SetPriority(priority);
361 }
362
363 private:
364 RequestPriority* const request_priority_;
365};
366
[email protected]71c64f62008-11-15 04:36:51367// Do a case-insensitive search through |haystack| for |needle|.
368bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50369 std::string::const_iterator it = std::search(
370 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
371 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51372 return it != haystack.end();
373}
374
danakj8522a25b2016-04-16 00:17:36375std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
376 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28377 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48378 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23379}
380
[email protected]96adadb2010-08-28 01:16:17381// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51382void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17383 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14384 uint16_t cipher_suite =
385 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29386 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17387}
388
[email protected]79e1fd62013-06-20 06:50:04389void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
390 const GURL& host_url) {
391 std::string sent_value;
392
393 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
394 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
395
396 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
397 EXPECT_EQ("keep-alive", sent_value);
398}
399
[email protected]dc5a5cf2012-09-26 02:49:30400// A network delegate that allows the user to choose a subset of request stages
401// to block in. When blocking, the delegate can do one of the following:
402// * synchronously return a pre-specified error code, or
403// * asynchronously return that value via an automatically called callback,
404// or
405// * block and wait for the user to do a callback.
406// Additionally, the user may also specify a redirect URL -- then each request
407// with the current URL different from the redirect target will be redirected
408// to that target, in the on-before-URL-request stage, independent of whether
409// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12410class BlockingNetworkDelegate : public TestNetworkDelegate {
411 public:
[email protected]dc5a5cf2012-09-26 02:49:30412 // Stages in which the delegate can block.
413 enum Stage {
[email protected]9045b8822012-01-13 20:35:35414 NOT_BLOCKED = 0,
415 ON_BEFORE_URL_REQUEST = 1 << 0,
416 ON_BEFORE_SEND_HEADERS = 1 << 1,
417 ON_HEADERS_RECEIVED = 1 << 2,
418 ON_AUTH_REQUIRED = 1 << 3
419 };
420
[email protected]dc5a5cf2012-09-26 02:49:30421 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59422 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30423 enum BlockMode {
424 SYNCHRONOUS, // No callback, returns specified return values.
425 AUTO_CALLBACK, // |this| posts a task to run the callback using the
426 // specified return codes.
427 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
428 // |auth_retval_| are ignored. In every blocking stage the
429 // message loop is quit.
430 };
431
432 // Creates a delegate which does not block at all.
433 explicit BlockingNetworkDelegate(BlockMode block_mode);
434
Wez2a31b222018-06-07 22:07:15435 // Runs the message loop until the delegate blocks.
436 void RunUntilBlocked();
437
[email protected]dc5a5cf2012-09-26 02:49:30438 // For users to trigger a callback returning |response|.
439 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
440 // Only call if |block_mode_| == USER_CALLBACK.
441 void DoCallback(int response);
442 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
443
444 // Setters.
445 void set_retval(int retval) {
446 ASSERT_NE(USER_CALLBACK, block_mode_);
447 ASSERT_NE(ERR_IO_PENDING, retval);
448 ASSERT_NE(OK, retval);
449 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35450 }
451
[email protected]dc5a5cf2012-09-26 02:49:30452 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
453 // |auth_credentials_| will be passed with the response.
454 void set_auth_retval(AuthRequiredResponse auth_retval) {
455 ASSERT_NE(USER_CALLBACK, block_mode_);
456 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
457 auth_retval_ = auth_retval;
458 }
459 void set_auth_credentials(const AuthCredentials& auth_credentials) {
460 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35461 }
462
[email protected]dc5a5cf2012-09-26 02:49:30463 void set_redirect_url(const GURL& url) {
464 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35465 }
466
[email protected]dc5a5cf2012-09-26 02:49:30467 void set_block_on(int block_on) {
468 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35469 }
470
[email protected]dc5a5cf2012-09-26 02:49:30471 // Allows the user to check in which state did we block.
472 Stage stage_blocked_for_callback() const {
473 EXPECT_EQ(USER_CALLBACK, block_mode_);
474 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35475 }
476
477 private:
Wez2a31b222018-06-07 22:07:15478 void OnBlocked();
479
David Benjamind1f287bf2018-06-12 01:57:20480 void RunCallback(int response, CompletionOnceCallback callback);
481 void RunAuthCallback(AuthRequiredResponse response, AuthCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30482
[email protected]9045b8822012-01-13 20:35:35483 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20484 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20485 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:20486 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35487
ryansturm2343cb62016-06-15 01:09:00488 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20489 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:00490 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35491
dchengb03027d2014-10-21 12:00:20492 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35493 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20494 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32495 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16496 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13497 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35498
dchengb03027d2014-10-21 12:00:20499 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35500 URLRequest* request,
501 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20502 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:13503 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35504
[email protected]dc5a5cf2012-09-26 02:49:30505 // Resets the callbacks and |stage_blocked_for_callback_|.
506 void Reset();
[email protected]9045b8822012-01-13 20:35:35507
[email protected]dc5a5cf2012-09-26 02:49:30508 // Checks whether we should block in |stage|. If yes, returns an error code
509 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
David Benjamind1f287bf2018-06-12 01:57:20510 int MaybeBlockStage(Stage stage, CompletionOnceCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30511
512 // Configuration parameters, can be adjusted by public methods:
513 const BlockMode block_mode_;
514
515 // Values returned on blocking stages when mode is SYNCHRONOUS or
516 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
517 int retval_; // To be returned in non-auth stages.
518 AuthRequiredResponse auth_retval_;
519
[email protected]5f714132014-03-26 10:41:16520 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30521 int block_on_; // Bit mask: in which stages to block.
522
523 // |auth_credentials_| will be copied to |*target_auth_credential_| on
524 // callback.
525 AuthCredentials auth_credentials_;
526 AuthCredentials* target_auth_credentials_;
527
528 // Internal variables, not set by not the user:
529 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
530 // USER_CALLBACK).
531 Stage stage_blocked_for_callback_;
532
533 // Callback objects stored during blocking stages.
David Benjamind1f287bf2018-06-12 01:57:20534 CompletionOnceCallback callback_;
[email protected]9045b8822012-01-13 20:35:35535 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30536
Wez2a31b222018-06-07 22:07:15537 // Closure to run to exit RunUntilBlocked().
538 base::OnceClosure on_blocked_;
539
Jeremy Romand54000b22019-07-08 18:40:16540 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_{this};
[email protected]dc5a5cf2012-09-26 02:49:30541
542 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35543};
544
[email protected]dc5a5cf2012-09-26 02:49:30545BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
546 : block_mode_(block_mode),
547 retval_(OK),
548 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
549 block_on_(0),
Raul Tambre94493c652019-03-11 17:18:35550 target_auth_credentials_(nullptr),
Jeremy Romand54000b22019-07-08 18:40:16551 stage_blocked_for_callback_(NOT_BLOCKED) {}
[email protected]dc5a5cf2012-09-26 02:49:30552
Wez2a31b222018-06-07 22:07:15553void BlockingNetworkDelegate::RunUntilBlocked() {
554 base::RunLoop run_loop;
555 on_blocked_ = run_loop.QuitClosure();
556 run_loop.Run();
557}
558
[email protected]dc5a5cf2012-09-26 02:49:30559void BlockingNetworkDelegate::DoCallback(int response) {
560 ASSERT_EQ(USER_CALLBACK, block_mode_);
561 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
562 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20563 CompletionOnceCallback callback = std::move(callback_);
[email protected]dc5a5cf2012-09-26 02:49:30564 Reset();
Wez2a31b222018-06-07 22:07:15565
566 // |callback| may trigger completion of a request, so post it as a task, so
567 // it will run under a subsequent TestDelegate::RunUntilComplete() loop.
568 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20569 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
570 weak_factory_.GetWeakPtr(), response,
571 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30572}
573
574void BlockingNetworkDelegate::DoAuthCallback(
575 NetworkDelegate::AuthRequiredResponse response) {
576 ASSERT_EQ(USER_CALLBACK, block_mode_);
577 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20578 AuthCallback auth_callback = std::move(auth_callback_);
[email protected]dc5a5cf2012-09-26 02:49:30579 Reset();
David Benjamind1f287bf2018-06-12 01:57:20580 RunAuthCallback(response, std::move(auth_callback));
[email protected]dc5a5cf2012-09-26 02:49:30581}
582
Wez2a31b222018-06-07 22:07:15583void BlockingNetworkDelegate::OnBlocked() {
584 // If this fails due to |on_blocked_| being null then OnBlocked() was run by
585 // a RunLoop other than RunUntilBlocked(), indicating a bug in the calling
586 // test.
587 std::move(on_blocked_).Run();
588}
589
[email protected]dc5a5cf2012-09-26 02:49:30590void BlockingNetworkDelegate::RunCallback(int response,
David Benjamind1f287bf2018-06-12 01:57:20591 CompletionOnceCallback callback) {
592 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30593}
594
595void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
David Benjamind1f287bf2018-06-12 01:57:20596 AuthCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30597 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
Raul Tambre94493c652019-03-11 17:18:35598 ASSERT_TRUE(target_auth_credentials_ != nullptr);
[email protected]dc5a5cf2012-09-26 02:49:30599 *target_auth_credentials_ = auth_credentials_;
600 }
David Benjamind1f287bf2018-06-12 01:57:20601 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30602}
603
David Benjamind1f287bf2018-06-12 01:57:20604int BlockingNetworkDelegate::OnBeforeURLRequest(URLRequest* request,
605 CompletionOnceCallback callback,
606 GURL* new_url) {
[email protected]dc5a5cf2012-09-26 02:49:30607 if (redirect_url_ == request->url())
608 return OK; // We've already seen this request and redirected elsewhere.
609
David Benjamind1f287bf2018-06-12 01:57:20610 // TestNetworkDelegate always completes synchronously.
611 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
612 request, base::NullCallback(), new_url));
[email protected]dc5a5cf2012-09-26 02:49:30613
614 if (!redirect_url_.is_empty())
615 *new_url = redirect_url_;
616
David Benjamind1f287bf2018-06-12 01:57:20617 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30618}
619
ryansturm2343cb62016-06-15 01:09:00620int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30621 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20622 CompletionOnceCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30623 HttpRequestHeaders* headers) {
David Benjamind1f287bf2018-06-12 01:57:20624 // TestNetworkDelegate always completes synchronously.
625 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
626 request, base::NullCallback(), headers));
[email protected]dc5a5cf2012-09-26 02:49:30627
David Benjamind1f287bf2018-06-12 01:57:20628 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30629}
630
631int BlockingNetworkDelegate::OnHeadersReceived(
632 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20633 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32634 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16635 scoped_refptr<HttpResponseHeaders>* override_response_headers,
636 GURL* allowed_unsafe_redirect_url) {
David Benjamind1f287bf2018-06-12 01:57:20637 // TestNetworkDelegate always completes synchronously.
638 CHECK_NE(ERR_IO_PENDING,
639 TestNetworkDelegate::OnHeadersReceived(
640 request, base::NullCallback(), original_response_headers,
641 override_response_headers, allowed_unsafe_redirect_url));
[email protected]dc5a5cf2012-09-26 02:49:30642
David Benjamind1f287bf2018-06-12 01:57:20643 return MaybeBlockStage(ON_HEADERS_RECEIVED, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30644}
645
646NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
647 URLRequest* request,
648 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20649 AuthCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30650 AuthCredentials* credentials) {
David Benjamind1f287bf2018-06-12 01:57:20651 // TestNetworkDelegate always completes synchronously.
652 CHECK_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING,
653 TestNetworkDelegate::OnAuthRequired(
654 request, auth_info, base::NullCallback(), credentials));
[email protected]dc5a5cf2012-09-26 02:49:30655 // Check that the user has provided callback for the previous blocked stage.
656 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
657
658 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
659 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
660 }
661
662 target_auth_credentials_ = credentials;
663
664 switch (block_mode_) {
665 case SYNCHRONOUS:
666 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
667 *target_auth_credentials_ = auth_credentials_;
668 return auth_retval_;
669
670 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45671 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20672 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunAuthCallback,
673 weak_factory_.GetWeakPtr(), auth_retval_,
674 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30675 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
676
677 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20678 auth_callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30679 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
Wez2a31b222018-06-07 22:07:15680 // We may reach here via a callback prior to RunUntilBlocked(), so post
681 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45682 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15683 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
684 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30685 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
686 }
687 NOTREACHED();
688 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
689}
690
691void BlockingNetworkDelegate::Reset() {
692 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
693 stage_blocked_for_callback_ = NOT_BLOCKED;
694 callback_.Reset();
695 auth_callback_.Reset();
696}
697
698int BlockingNetworkDelegate::MaybeBlockStage(
699 BlockingNetworkDelegate::Stage stage,
David Benjamind1f287bf2018-06-12 01:57:20700 CompletionOnceCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30701 // Check that the user has provided callback for the previous blocked stage.
702 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
703
704 if ((block_on_ & stage) == 0) {
705 return OK;
706 }
707
708 switch (block_mode_) {
709 case SYNCHRONOUS:
710 EXPECT_NE(OK, retval_);
711 return retval_;
712
713 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45714 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20715 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
716 weak_factory_.GetWeakPtr(), retval_,
717 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30718 return ERR_IO_PENDING;
719
720 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20721 callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30722 stage_blocked_for_callback_ = stage;
Wez2a31b222018-06-07 22:07:15723 // We may reach here via a callback prior to RunUntilBlocked(), so post
724 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45725 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15726 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
727 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30728 return ERR_IO_PENDING;
729 }
730 NOTREACHED();
731 return 0;
732}
733
[email protected]d5a4dd62012-05-23 01:41:04734class TestURLRequestContextWithProxy : public TestURLRequestContext {
735 public:
736 // Does not own |delegate|.
737 TestURLRequestContextWithProxy(const std::string& proxy,
Matt Menke39e6de62019-06-27 20:11:39738 NetworkDelegate* delegate,
739 bool delay_initialization = false)
[email protected]d5a4dd62012-05-23 01:41:04740 : TestURLRequestContext(true) {
Lily Houghton8c2f97d2018-01-22 05:06:59741 context_storage_.set_proxy_resolution_service(
Ramin Halavatica8d5252018-03-12 05:33:49742 ProxyResolutionService::CreateFixed(proxy,
743 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]d5a4dd62012-05-23 01:41:04744 set_network_delegate(delegate);
Matt Menke39e6de62019-06-27 20:11:39745 if (!delay_initialization)
746 Init();
[email protected]d5a4dd62012-05-23 01:41:04747 }
Chris Watkins7a41d3552017-12-01 02:13:27748 ~TestURLRequestContextWithProxy() override = default;
[email protected]d5a4dd62012-05-23 01:41:04749};
750
stefanocsbd5be5202016-06-10 03:37:55751// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01752// URI and report to be sent.
753class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55754 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01755 public:
Chris Watkins7a41d3552017-12-01 02:13:27756 MockCertificateReportSender() = default;
757 ~MockCertificateReportSender() override = default;
estark06e0dac2015-08-07 21:56:01758
meacer5d4dc5a2017-04-27 20:37:48759 void Send(const GURL& report_uri,
760 base::StringPiece content_type,
761 base::StringPiece report,
762 const base::Callback<void()>& success_callback,
763 const base::Callback<void(const GURL&, int, int)>& error_callback)
764 override {
estark06e0dac2015-08-07 21:56:01765 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44766 report.CopyToString(&latest_report_);
767 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01768 }
estark06e0dac2015-08-07 21:56:01769 const GURL& latest_report_uri() { return latest_report_uri_; }
770 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44771 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01772
773 private:
774 GURL latest_report_uri_;
775 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44776 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01777};
778
dadrian612337a2016-07-20 22:36:58779// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
780// This is needed because after the certificate failure, the URLRequest will
781// retry the connection, and return a partial SSLInfo with a cached cert status.
782// The partial SSLInfo does not have the OCSP information filled out.
783class OCSPErrorTestDelegate : public TestDelegate {
784 public:
785 void OnSSLCertificateError(URLRequest* request,
Emily Stark79fba5842019-04-25 04:59:36786 int net_error,
dadrian612337a2016-07-20 22:36:58787 const SSLInfo& ssl_info,
788 bool fatal) override {
789 ssl_info_ = ssl_info;
790 on_ssl_certificate_error_called_ = true;
Emily Stark79fba5842019-04-25 04:59:36791 TestDelegate::OnSSLCertificateError(request, net_error, ssl_info, fatal);
dadrian612337a2016-07-20 22:36:58792 }
793
794 bool on_ssl_certificate_error_called() {
795 return on_ssl_certificate_error_called_;
796 }
797
798 SSLInfo ssl_info() { return ssl_info_; }
799
800 private:
801 bool on_ssl_certificate_error_called_ = false;
802 SSLInfo ssl_info_;
803};
804
[email protected]d5a4dd62012-05-23 01:41:04805} // namespace
806
[email protected]a592c0432012-12-01 18:10:29807// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
Gabriel Charette694c3c332019-08-19 14:53:05808class URLRequestTest : public PlatformTest, public WithTaskEnvironment {
[email protected]abb26092010-11-11 22:19:00809 public:
Ryan Sleevib8449e02018-07-15 04:31:07810 URLRequestTest()
811 : default_context_(std::make_unique<TestURLRequestContext>(true)) {
812 default_context_->set_network_delegate(&default_network_delegate_);
813 default_context_->set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50814 job_factory_impl_ = new URLRequestJobFactoryImpl();
815 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50816 }
bengr1bf8e942014-11-07 01:36:50817
dcheng67be2b1f2014-10-27 21:47:29818 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18819 // URLRequestJobs may post clean-up tasks on destruction.
820 base::RunLoop().RunUntilIdle();
Martijn Croonenb1383da2017-10-11 11:56:35821
822 SetTransportSecurityStateSourceForTesting(nullptr);
[email protected]e4034ad2013-09-20 08:36:18823 }
[email protected]87a09a92011-07-14 15:50:50824
dcheng2339883c2014-12-23 00:23:05825 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50826 SetUpFactory();
Ryan Sleevib8449e02018-07-15 04:31:07827 default_context_->set_job_factory(job_factory_.get());
828 default_context_->Init();
bengr1bf8e942014-11-07 01:36:50829 PlatformTest::SetUp();
830 }
831
Ryan Sleevib8449e02018-07-15 04:31:07832 void TearDown() override { default_context_.reset(); }
833
bengr1bf8e942014-11-07 01:36:50834 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20835 job_factory_impl_->SetProtocolHandler(
Bence Béky8f9d7d3952017-10-09 19:58:04836 "data", std::make_unique<DataProtocolHandler>());
brettwa1228ebb2016-10-28 03:51:34837#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50838 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19839 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07840 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50841#endif
842 }
843
844 TestNetworkDelegate* default_network_delegate() {
845 return &default_network_delegate_;
846 }
847
Ryan Sleevib8449e02018-07-15 04:31:07848 TestURLRequestContext& default_context() const { return *default_context_; }
bengr1bf8e942014-11-07 01:36:50849
[email protected]3c5ca8c2011-09-29 01:14:51850 // Adds the TestJobInterceptor to the default context.
851 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23852 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20853 job_factory_impl_->SetProtocolHandler("http", nullptr);
854 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36855 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23856 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51857 }
858
Sergey Ulanov2e49f492017-09-14 19:37:51859 // Creates a temp test file and writes |data| to the file. The file will be
860 // deleted after the test completes.
861 void CreateTestFile(const char* data,
862 size_t data_size,
863 base::FilePath* test_file) {
864 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
865 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
866 // now, Mac and Android bots return a path with a symbolic link.
867 base::FilePath absolute_temp_dir =
868 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
869
870 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
871 ASSERT_EQ(static_cast<int>(data_size),
872 base::WriteFile(*test_file, data, data_size));
873 }
874
[email protected]87a09a92011-07-14 15:50:50875 protected:
vishal.b62985ca92015-04-17 08:45:51876 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24877 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50878 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36879 std::unique_ptr<URLRequestJobFactory> job_factory_;
Ryan Sleevib8449e02018-07-15 04:31:07880 std::unique_ptr<TestURLRequestContext> default_context_;
Sergey Ulanov2e49f492017-09-14 19:37:51881 base::ScopedTempDir temp_dir_;
[email protected]7a0bb4bf2008-11-19 21:41:48882};
883
satoruxddac0442017-05-29 06:06:18884// This NetworkDelegate is picky about what files are accessible. Only
Ryan Sleevia9d6aa62019-07-26 13:32:18885// allowlisted files are allowed.
satoruxddac0442017-05-29 06:06:18886class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
887 public:
Chris Watkins7a41d3552017-12-01 02:13:27888 CookieBlockingNetworkDelegate() = default;
satoruxddac0442017-05-29 06:06:18889
Ryan Sleevia9d6aa62019-07-26 13:32:18890 // Adds |directory| to the access allow list.
891 void AddToAllowlist(const base::FilePath& directory) {
892 allowlist_.insert(directory);
satoruxddac0442017-05-29 06:06:18893 }
894
895 private:
Ryan Sleevia9d6aa62019-07-26 13:32:18896 // Returns true if |path| matches the allow list.
satoruxddac0442017-05-29 06:06:18897 bool OnCanAccessFileInternal(const base::FilePath& path) const {
Ryan Sleevia9d6aa62019-07-26 13:32:18898 for (const auto& directory : allowlist_) {
satoruxddac0442017-05-29 06:06:18899 if (directory == path || directory.IsParent(path))
900 return true;
901 }
902 return false;
903 }
904
905 // Returns true only if both |original_path| and |absolute_path| match the
Ryan Sleevia9d6aa62019-07-26 13:32:18906 // allow list.
satoruxddac0442017-05-29 06:06:18907 bool OnCanAccessFile(const URLRequest& request,
908 const base::FilePath& original_path,
909 const base::FilePath& absolute_path) const override {
910 return (OnCanAccessFileInternal(original_path) &&
911 OnCanAccessFileInternal(absolute_path));
912 }
913
Ryan Sleevia9d6aa62019-07-26 13:32:18914 std::set<base::FilePath> allowlist_;
satoruxddac0442017-05-29 06:06:18915
916 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
917};
918
[email protected]316c1e5e2012-09-12 15:17:44919TEST_F(URLRequestTest, AboutBlankTest) {
920 TestDelegate d;
921 {
rhalavatib7bd7c792017-04-27 05:25:16922 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:07923 default_context().CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
924 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44925
[email protected]f7022f32014-08-21 16:32:19926 r->Start();
927 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44928
Wez2a31b222018-06-07 22:07:15929 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44930
[email protected]f7022f32014-08-21 16:32:19931 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44932 EXPECT_FALSE(d.received_data_before_response());
933 EXPECT_EQ(d.bytes_received(), 0);
Tsuyoshi Horo01faed62019-02-20 22:11:37934 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
935 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04936
937 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19938 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44939 }
940}
941
942TEST_F(URLRequestTest, DataURLImageTest) {
943 TestDelegate d;
944 {
945 // Use our nice little Chrome logo.
Ryan Sleevib8449e02018-07-15 04:31:07946 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
danakj8522a25b2016-04-16 00:17:36947 GURL("data:image/png;base64,"
948 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
949 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
950 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
951 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
952 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
953 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
954 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
955 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
956 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
957 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
958 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
959 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
960 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
961 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
962 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
963 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
964 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
965 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
966 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16967 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44968
[email protected]f7022f32014-08-21 16:32:19969 r->Start();
970 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44971
Wez2a31b222018-06-07 22:07:15972 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44973
[email protected]f7022f32014-08-21 16:32:19974 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44975 EXPECT_FALSE(d.received_data_before_response());
976 EXPECT_EQ(d.bytes_received(), 911);
Tsuyoshi Horo01faed62019-02-20 22:11:37977 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
978 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:04979
980 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19981 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44982 }
983}
984
brettwa1228ebb2016-10-28 03:51:34985#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44986TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51987 const char kTestFileContent[] = "Hello";
988 base::FilePath test_file;
989 ASSERT_NO_FATAL_FAILURE(
990 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04991
Sergey Ulanov2e49f492017-09-14 19:37:51992 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:44993
994 TestDelegate d;
995 {
Ryan Sleevib8449e02018-07-15 04:31:07996 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:51997 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44998
[email protected]f7022f32014-08-21 16:32:19999 r->Start();
1000 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441001
Wez2a31b222018-06-07 22:07:151002 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441003
[email protected]f7022f32014-08-21 16:32:191004 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441005 EXPECT_EQ(1, d.response_started_count());
1006 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:511007 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
Tsuyoshi Horo01faed62019-02-20 22:11:371008 EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
1009 EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:041010
1011 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:191012 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:441013 }
1014}
1015
[email protected]ba40bb762012-12-17 07:11:041016TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:511017 const char kTestFileContent[] = "Hello";
1018 base::FilePath test_file;
1019 ASSERT_NO_FATAL_FAILURE(
1020 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
1021
1022 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:041023
1024 TestDelegate d;
1025 {
Ryan Sleevib8449e02018-07-15 04:31:071026 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511027 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:041028
[email protected]f7022f32014-08-21 16:32:191029 r->Start();
1030 EXPECT_TRUE(r->is_pending());
1031 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:041032 }
[email protected]79e1fd62013-06-20 06:50:041033 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:041034 // destroyed.
[email protected]255620da2013-08-19 13:14:291035 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041036}
1037
[email protected]316c1e5e2012-09-12 15:17:441038TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1039 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361040 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441041 FillBuffer(buffer.get(), buffer_size);
1042
Sergey Ulanov2e49f492017-09-14 19:37:511043 base::FilePath test_file;
1044 ASSERT_NO_FATAL_FAILURE(
1045 CreateTestFile(buffer.get(), buffer_size, &test_file));
1046 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441047
1048 const size_t first_byte_position = 500;
1049 const size_t last_byte_position = buffer_size - first_byte_position;
1050 const size_t content_length = last_byte_position - first_byte_position + 1;
1051 std::string partial_buffer_string(buffer.get() + first_byte_position,
1052 buffer.get() + last_byte_position + 1);
1053
1054 TestDelegate d;
1055 {
Ryan Sleevib8449e02018-07-15 04:31:071056 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161057 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441058
1059 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381060 headers.SetHeader(
1061 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591062 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381063 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191064 r->SetExtraRequestHeaders(headers);
1065 r->Start();
1066 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441067
Wez2a31b222018-06-07 22:07:151068 d.RunUntilComplete();
1069
[email protected]f7022f32014-08-21 16:32:191070 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441071 EXPECT_EQ(1, d.response_started_count());
1072 EXPECT_FALSE(d.received_data_before_response());
1073 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1074 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1075 EXPECT_TRUE(partial_buffer_string == d.data_received());
1076 }
[email protected]316c1e5e2012-09-12 15:17:441077}
1078
1079TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1080 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361081 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441082 FillBuffer(buffer.get(), buffer_size);
1083
Sergey Ulanov2e49f492017-09-14 19:37:511084 base::FilePath test_file;
1085 ASSERT_NO_FATAL_FAILURE(
1086 CreateTestFile(buffer.get(), buffer_size, &test_file));
1087 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441088
1089 const size_t first_byte_position = 500;
1090 const size_t last_byte_position = buffer_size - 1;
1091 const size_t content_length = last_byte_position - first_byte_position + 1;
1092 std::string partial_buffer_string(buffer.get() + first_byte_position,
1093 buffer.get() + last_byte_position + 1);
1094
1095 TestDelegate d;
1096 {
Ryan Sleevib8449e02018-07-15 04:31:071097 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161098 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441099
1100 HttpRequestHeaders headers;
1101 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591102 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381103 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191104 r->SetExtraRequestHeaders(headers);
1105 r->Start();
1106 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441107
[email protected]255620da2013-08-19 13:14:291108 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191109 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441110 EXPECT_EQ(1, d.response_started_count());
1111 EXPECT_FALSE(d.received_data_before_response());
1112 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1113 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1114 EXPECT_TRUE(partial_buffer_string == d.data_received());
1115 }
[email protected]316c1e5e2012-09-12 15:17:441116}
1117
1118TEST_F(URLRequestTest, FileTestMultipleRanges) {
1119 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361120 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441121 FillBuffer(buffer.get(), buffer_size);
1122
Sergey Ulanov2e49f492017-09-14 19:37:511123 base::FilePath test_file;
1124 ASSERT_NO_FATAL_FAILURE(
1125 CreateTestFile(buffer.get(), buffer_size, &test_file));
1126 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441127
1128 TestDelegate d;
1129 {
Ryan Sleevib8449e02018-07-15 04:31:071130 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161131 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441132
1133 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381134 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191135 r->SetExtraRequestHeaders(headers);
1136 r->Start();
1137 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441138
Wez2a31b222018-06-07 22:07:151139 d.RunUntilComplete();
1140
[email protected]316c1e5e2012-09-12 15:17:441141 EXPECT_TRUE(d.request_failed());
1142 }
[email protected]316c1e5e2012-09-12 15:17:441143}
1144
[email protected]3ca8b362013-11-11 22:18:071145TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511146 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071147 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511148 ASSERT_NO_FATAL_FAILURE(
1149 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1150
satoruxddac0442017-05-29 06:06:181151 // The directory part of the path returned from CreateTemporaryFileInDir()
1152 // can be slightly different from |absolute_temp_dir| on Windows.
1153 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1154 // Hence the test should use the directory name of |test_file|, rather than
Ryan Sleevia9d6aa62019-07-26 13:32:181155 // |absolute_temp_dir|, for allowlisting.
satoruxddac0442017-05-29 06:06:181156 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591157 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071158 {
1159 TestDelegate d;
satoruxddac0442017-05-29 06:06:181160 CookieBlockingNetworkDelegate network_delegate;
Ryan Sleevia9d6aa62019-07-26 13:32:181161 network_delegate.AddToAllowlist(real_temp_dir);
Ryan Sleevib8449e02018-07-15 04:31:071162 default_context().set_network_delegate(&network_delegate);
1163 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161164 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191165 r->Start();
Wez2a31b222018-06-07 22:07:151166 d.RunUntilComplete();
Ryan Sleevia9d6aa62019-07-26 13:32:181167 // This should be allowed as the file path is allowlisted.
[email protected]3ca8b362013-11-11 22:18:071168 EXPECT_FALSE(d.request_failed());
1169 EXPECT_EQ(test_data, d.data_received());
1170 }
1171
1172 {
1173 TestDelegate d;
satoruxddac0442017-05-29 06:06:181174 CookieBlockingNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:071175 default_context().set_network_delegate(&network_delegate);
1176 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161177 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191178 r->Start();
Wez2a31b222018-06-07 22:07:151179 d.RunUntilComplete();
Ryan Sleevia9d6aa62019-07-26 13:32:181180 // This should be rejected as the file path is not allowlisted.
[email protected]3ca8b362013-11-11 22:18:071181 EXPECT_TRUE(d.request_failed());
1182 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181183 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071184 }
1185}
1186
Wez35539132018-07-17 11:26:051187#if defined(OS_POSIX) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181188
1189TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511190 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181191 // Get an absolute path since temp_dir can contain a symbolic link.
1192 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511193 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181194
Ryan Sleevia9d6aa62019-07-26 13:32:181195 // Create a good directory (will be allowlisted) and a good file.
satoruxddac0442017-05-29 06:06:181196 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1197 ASSERT_TRUE(base::CreateDirectory(good_dir));
1198 base::FilePath good_file;
1199 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1200 std::string good_data("good");
1201 base::WriteFile(good_file, good_data.data(), good_data.size());
1202 // See the comment in AllowFileURLs() for why this is done.
1203 base::FilePath real_good_dir = good_file.DirName();
1204
Ryan Sleevia9d6aa62019-07-26 13:32:181205 // Create a bad directory (will not be allowlisted) and a bad file.
satoruxddac0442017-05-29 06:06:181206 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1207 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1208 base::FilePath bad_file;
1209 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1210 std::string bad_data("bad");
1211 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1212
1213 // This symlink will point to the good file. Access to the symlink will be
1214 // allowed as both the symlink and the destination file are in the same
1215 // good directory.
1216 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1217 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1218 GURL good_file_url = FilePathToFileURL(good_symlink);
1219 // This symlink will point to the bad file. Even though the symlink is in
1220 // the good directory, access to the symlink will be rejected since it
1221 // points to the bad file.
1222 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1223 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1224 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1225
1226 CookieBlockingNetworkDelegate network_delegate;
Ryan Sleevia9d6aa62019-07-26 13:32:181227 network_delegate.AddToAllowlist(real_good_dir);
satoruxddac0442017-05-29 06:06:181228 {
1229 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071230 default_context().set_network_delegate(&network_delegate);
1231 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371232 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181233 r->Start();
Wez2a31b222018-06-07 22:07:151234 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181235 // good_file_url should be allowed.
1236 EXPECT_FALSE(d.request_failed());
1237 EXPECT_EQ(good_data, d.data_received());
1238 }
1239
1240 {
1241 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071242 default_context().set_network_delegate(&network_delegate);
1243 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371244 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181245 r->Start();
Wez2a31b222018-06-07 22:07:151246 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181247 // bad_file_url should be rejected.
1248 EXPECT_TRUE(d.request_failed());
1249 EXPECT_EQ("", d.data_received());
1250 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1251 }
1252}
1253
1254TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511255 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181256 // Get an absolute path since temp_dir can contain a symbolic link.
1257 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511258 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181259
Ryan Sleevia9d6aa62019-07-26 13:32:181260 // Create a good directory (will be allowlisted).
satoruxddac0442017-05-29 06:06:181261 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1262 ASSERT_TRUE(base::CreateDirectory(good_dir));
1263
Ryan Sleevia9d6aa62019-07-26 13:32:181264 // Create a bad directory (will not be allowlisted).
satoruxddac0442017-05-29 06:06:181265 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1266 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1267
1268 // This symlink will point to the good directory. Access to the symlink
1269 // will be allowed as the symlink is in the good dir that'll be white
1270 // listed.
1271 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1272 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1273 GURL good_file_url = FilePathToFileURL(good_symlink);
1274 // This symlink will point to the bad directory. Even though the symlink is
1275 // in the good directory, access to the symlink will be rejected since it
1276 // points to the bad directory.
1277 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1278 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1279 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1280
1281 CookieBlockingNetworkDelegate network_delegate;
Ryan Sleevia9d6aa62019-07-26 13:32:181282 network_delegate.AddToAllowlist(good_dir);
satoruxddac0442017-05-29 06:06:181283 {
1284 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071285 default_context().set_network_delegate(&network_delegate);
1286 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371287 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181288 r->Start();
Wez2a31b222018-06-07 22:07:151289 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181290 // good_file_url should be allowed.
1291 EXPECT_FALSE(d.request_failed());
1292 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1293 }
1294
1295 {
1296 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071297 default_context().set_network_delegate(&network_delegate);
1298 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371299 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181300 r->Start();
Wez2a31b222018-06-07 22:07:151301 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181302 // bad_file_url should be rejected.
1303 EXPECT_TRUE(d.request_failed());
1304 EXPECT_EQ("", d.data_received());
1305 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1306 }
1307}
1308
Wez35539132018-07-17 11:26:051309#endif // defined(OS_POSIX)
[email protected]316c1e5e2012-09-12 15:17:441310
1311TEST_F(URLRequestTest, FileDirCancelTest) {
1312 // Put in mock resource provider.
1313 NetModule::SetResourceProvider(TestNetResourceProvider);
1314
1315 TestDelegate d;
1316 {
[email protected]6cdfd7f2013-02-08 20:40:151317 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:191318 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
[email protected]316c1e5e2012-09-12 15:17:441319 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1320 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1321
Ryan Sleevib8449e02018-07-15 04:31:071322 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161323 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1324 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191325 req->Start();
1326 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441327
1328 d.set_cancel_in_received_data_pending(true);
1329
Wez2a31b222018-06-07 22:07:151330 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441331 }
1332
1333 // Take out mock resource provider.
Raul Tambre94493c652019-03-11 17:18:351334 NetModule::SetResourceProvider(nullptr);
[email protected]316c1e5e2012-09-12 15:17:441335}
1336
[email protected]5f9581402013-10-30 13:08:321337TEST_F(URLRequestTest, FileDirOutputSanity) {
1338 // Verify the general sanity of the the output of the file:
1339 // directory lister by checking for the output of a known existing
1340 // file.
1341 const char sentinel_name[] = "filedir-sentinel";
1342
1343 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191344 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471345 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321346
1347 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161348 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071349 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1350 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191351 req->Start();
Wez2a31b222018-06-07 22:07:151352 d.RunUntilComplete();
[email protected]5f9581402013-10-30 13:08:321353
1354 // Generate entry for the sentinel file.
1355 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581356 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491357 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321358 EXPECT_GT(info.size, 0);
1359 std::string sentinel_output = GetDirectoryListingEntry(
1360 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181361 std::string(sentinel_name), false /* is_dir */, info.size,
1362
[email protected]5f9581402013-10-30 13:08:321363 info.last_modified);
1364
1365 ASSERT_LT(0, d.bytes_received());
1366 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501367 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321368 // Check for the entry generated for the "sentinel" file.
1369 const std::string& data = d.data_received();
1370 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1371}
1372
[email protected]316c1e5e2012-09-12 15:17:441373TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1374 // There is an implicit redirect when loading a file path that matches a
1375 // directory and does not end with a slash. Ensure that following such
1376 // redirects does not crash. See http://crbug.com/18686.
1377
[email protected]6cdfd7f2013-02-08 20:40:151378 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191379 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471380 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441381
1382 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161383 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071384 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1385 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191386 req->Start();
Wez2a31b222018-06-07 22:07:151387 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441388
1389 ASSERT_EQ(1, d.received_redirect_count());
1390 ASSERT_LT(0, d.bytes_received());
1391 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501392 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441393}
1394
1395#if defined(OS_WIN)
1396// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1397TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1398 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071399 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161400 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191401 req->Start();
Wez2a31b222018-06-07 22:07:151402 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441403
1404 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501405 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441406}
[email protected]5ecf7cb282014-05-11 01:49:551407#endif // defined(OS_WIN)
1408
brettwa1228ebb2016-10-28 03:51:341409#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551410
1411TEST_F(URLRequestTest, InvalidUrlTest) {
1412 TestDelegate d;
1413 {
rhalavatib7bd7c792017-04-27 05:25:161414 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:071415 default_context().CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1416 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551417
[email protected]f7022f32014-08-21 16:32:191418 r->Start();
1419 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551420
Wez2a31b222018-06-07 22:07:151421 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551422 EXPECT_TRUE(d.request_failed());
1423 }
1424}
1425
jochen0e3b3a62014-09-16 18:31:231426TEST_F(URLRequestTest, InvalidReferrerTest) {
1427 TestURLRequestContext context;
1428 TestNetworkDelegate network_delegate;
1429 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1430 context.set_network_delegate(&network_delegate);
1431 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361432 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161433 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1434 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231435 req->SetReferrer("https://somewhere.com/");
1436
1437 req->Start();
Wez2a31b222018-06-07 22:07:151438 d.RunUntilComplete();
jochen0e3b3a62014-09-16 18:31:231439 EXPECT_TRUE(d.request_failed());
1440}
1441
[email protected]5ecf7cb282014-05-11 01:49:551442#if defined(OS_WIN)
1443TEST_F(URLRequestTest, ResolveShortcutTest) {
1444 base::FilePath app_path;
Avi Drissman5c80d832018-05-01 17:01:191445 base::PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471446 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551447 app_path = app_path.AppendASCII("with-headers.html");
1448
jdoerrie6312bf62019-02-01 22:03:421449 base::string16 lnk_path = app_path.value() + FILE_PATH_LITERAL(".lnk");
[email protected]5ecf7cb282014-05-11 01:49:551450
1451 base::win::ScopedCOMInitializer com_initializer;
1452
1453 // Temporarily create a shortcut for test
1454 {
Robert Liaoc88f99d12017-10-17 21:48:331455 Microsoft::WRL::ComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161456 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
Raul Tambre94493c652019-03-11 17:18:351457 CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
Robert Liaoc88f99d12017-10-17 21:48:331458 Microsoft::WRL::ComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001459 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
jdoerriebacc1962019-02-07 13:39:221460 EXPECT_TRUE(SUCCEEDED(shell->SetPath(base::as_wcstr(app_path.value()))));
[email protected]5ecf7cb282014-05-11 01:49:551461 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
jdoerriebacc1962019-02-07 13:39:221462 EXPECT_TRUE(SUCCEEDED(persist->Save(base::as_wcstr(lnk_path), TRUE)));
[email protected]5ecf7cb282014-05-11 01:49:551463 }
1464
1465 TestDelegate d;
1466 {
Ryan Sleevib8449e02018-07-15 04:31:071467 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161468 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1469 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551470
[email protected]f7022f32014-08-21 16:32:191471 r->Start();
1472 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551473
Wez2a31b222018-06-07 22:07:151474 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551475
1476 WIN32_FILE_ATTRIBUTE_DATA data;
jdoerriebacc1962019-02-07 13:39:221477 GetFileAttributesEx(base::as_wcstr(app_path.value()), GetFileExInfoStandard,
jdoerrie6312bf62019-02-01 22:03:421478 &data);
jdoerriebacc1962019-02-07 13:39:221479 HANDLE file = CreateFile(base::as_wcstr(app_path.value()), GENERIC_READ,
Raul Tambre94493c652019-03-11 17:18:351480 FILE_SHARE_READ, nullptr, OPEN_EXISTING,
1481 FILE_ATTRIBUTE_NORMAL, nullptr);
[email protected]5ecf7cb282014-05-11 01:49:551482 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361483 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551484 DWORD read_size;
1485 BOOL result;
Raul Tambre94493c652019-03-11 17:18:351486 result =
1487 ReadFile(file, buffer.get(), data.nFileSizeLow, &read_size, nullptr);
[email protected]5ecf7cb282014-05-11 01:49:551488 std::string content(buffer.get(), read_size);
1489 CloseHandle(file);
1490
[email protected]f7022f32014-08-21 16:32:191491 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551492 EXPECT_EQ(1, d.received_redirect_count());
1493 EXPECT_EQ(content, d.data_received());
1494 }
1495
1496 // Clean the shortcut
jdoerriebacc1962019-02-07 13:39:221497 DeleteFile(base::as_wcstr(lnk_path));
[email protected]5ecf7cb282014-05-11 01:49:551498}
1499#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441500
1501// Custom URLRequestJobs for use with interceptor tests
1502class RestartTestJob : public URLRequestTestJob {
1503 public:
1504 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1505 : URLRequestTestJob(request, network_delegate, true) {}
1506 protected:
dchengb03027d2014-10-21 12:00:201507 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441508 private:
Chris Watkins7a41d3552017-12-01 02:13:271509 ~RestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441510};
1511
1512class CancelTestJob : public URLRequestTestJob {
1513 public:
1514 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1515 : URLRequestTestJob(request, network_delegate, true) {}
1516 protected:
dchengb03027d2014-10-21 12:00:201517 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441518 private:
Chris Watkins7a41d3552017-12-01 02:13:271519 ~CancelTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441520};
1521
1522class CancelThenRestartTestJob : public URLRequestTestJob {
1523 public:
1524 explicit CancelThenRestartTestJob(URLRequest* request,
1525 NetworkDelegate* network_delegate)
1526 : URLRequestTestJob(request, network_delegate, true) {
1527 }
1528 protected:
dchengb03027d2014-10-21 12:00:201529 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441530 request_->Cancel();
1531 this->NotifyRestartRequired();
1532 }
1533 private:
Chris Watkins7a41d3552017-12-01 02:13:271534 ~CancelThenRestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441535};
1536
bengr1bf8e942014-11-07 01:36:501537// An Interceptor for use with interceptor tests.
1538class MockURLRequestInterceptor : public URLRequestInterceptor {
1539 public:
1540 // Static getters for canned response header and data strings.
1541 static std::string ok_data() {
1542 return URLRequestTestJob::test_data_1();
1543 }
1544
1545 static std::string ok_headers() {
1546 return URLRequestTestJob::test_headers();
1547 }
1548
1549 static std::string redirect_data() {
1550 return std::string();
1551 }
1552
1553 static std::string redirect_headers() {
1554 return URLRequestTestJob::test_redirect_headers();
1555 }
1556
1557 static std::string error_data() {
1558 return std::string("ohhh nooooo mr. bill!");
1559 }
1560
1561 static std::string error_headers() {
1562 return URLRequestTestJob::test_error_headers();
1563 }
1564
1565 MockURLRequestInterceptor()
1566 : intercept_main_request_(false), restart_main_request_(false),
1567 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1568 simulate_main_network_error_(false),
1569 intercept_redirect_(false), cancel_redirect_request_(false),
1570 intercept_final_response_(false), cancel_final_request_(false),
1571 use_url_request_http_job_(false),
1572 did_intercept_main_(false), did_restart_main_(false),
1573 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1574 did_simulate_error_main_(false),
1575 did_intercept_redirect_(false), did_cancel_redirect_(false),
1576 did_intercept_final_(false), did_cancel_final_(false) {
1577 }
1578
Chris Watkins7a41d3552017-12-01 02:13:271579 ~MockURLRequestInterceptor() override = default;
bengr1bf8e942014-11-07 01:36:501580
1581 // URLRequestInterceptor implementation:
1582 URLRequestJob* MaybeInterceptRequest(
1583 URLRequest* request,
1584 NetworkDelegate* network_delegate) const override {
1585 if (restart_main_request_) {
1586 restart_main_request_ = false;
1587 did_restart_main_ = true;
1588 return new RestartTestJob(request, network_delegate);
1589 }
1590 if (cancel_main_request_) {
1591 cancel_main_request_ = false;
1592 did_cancel_main_ = true;
1593 return new CancelTestJob(request, network_delegate);
1594 }
1595 if (cancel_then_restart_main_request_) {
1596 cancel_then_restart_main_request_ = false;
1597 did_cancel_then_restart_main_ = true;
1598 return new CancelThenRestartTestJob(request, network_delegate);
1599 }
1600 if (simulate_main_network_error_) {
1601 simulate_main_network_error_ = false;
1602 did_simulate_error_main_ = true;
1603 if (use_url_request_http_job_) {
1604 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1605 }
1606 // This job will result in error since the requested URL is not one of the
1607 // URLs supported by these tests.
1608 return new URLRequestTestJob(request, network_delegate, true);
1609 }
1610 if (!intercept_main_request_)
1611 return nullptr;
1612 intercept_main_request_ = false;
1613 did_intercept_main_ = true;
1614 URLRequestTestJob* job = new URLRequestTestJob(request,
1615 network_delegate,
1616 main_headers_,
1617 main_data_,
1618 true);
1619 job->set_load_timing_info(main_request_load_timing_info_);
1620 return job;
1621 }
1622
1623 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1624 NetworkDelegate* network_delegate,
1625 const GURL& location) const override {
1626 if (cancel_redirect_request_) {
1627 cancel_redirect_request_ = false;
1628 did_cancel_redirect_ = true;
1629 return new CancelTestJob(request, network_delegate);
1630 }
1631 if (!intercept_redirect_)
1632 return nullptr;
1633 intercept_redirect_ = false;
1634 did_intercept_redirect_ = true;
1635 if (use_url_request_http_job_) {
1636 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1637 }
1638 return new URLRequestTestJob(request,
1639 network_delegate,
1640 redirect_headers_,
1641 redirect_data_,
1642 true);
1643 }
1644
1645 URLRequestJob* MaybeInterceptResponse(
1646 URLRequest* request,
1647 NetworkDelegate* network_delegate) const override {
1648 if (cancel_final_request_) {
1649 cancel_final_request_ = false;
1650 did_cancel_final_ = true;
1651 return new CancelTestJob(request, network_delegate);
1652 }
1653 if (!intercept_final_response_)
1654 return nullptr;
1655 intercept_final_response_ = false;
1656 did_intercept_final_ = true;
1657 if (use_url_request_http_job_) {
1658 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1659 }
1660 return new URLRequestTestJob(request,
1661 network_delegate,
1662 final_headers_,
1663 final_data_,
1664 true);
1665 }
1666
1667 void set_intercept_main_request(bool intercept_main_request) {
1668 intercept_main_request_ = intercept_main_request;
1669 }
1670
1671 void set_main_headers(const std::string& main_headers) {
1672 main_headers_ = main_headers;
1673 }
1674
1675 void set_main_data(const std::string& main_data) {
1676 main_data_ = main_data;
1677 }
1678
1679 void set_main_request_load_timing_info(
1680 const LoadTimingInfo& main_request_load_timing_info) {
1681 main_request_load_timing_info_ = main_request_load_timing_info;
1682 }
1683
1684 void set_restart_main_request(bool restart_main_request) {
1685 restart_main_request_ = restart_main_request;
1686 }
1687
1688 void set_cancel_main_request(bool cancel_main_request) {
1689 cancel_main_request_ = cancel_main_request;
1690 }
1691
1692 void set_cancel_then_restart_main_request(
1693 bool cancel_then_restart_main_request) {
1694 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1695 }
1696
1697 void set_simulate_main_network_error(bool simulate_main_network_error) {
1698 simulate_main_network_error_ = simulate_main_network_error;
1699 }
1700
1701 void set_intercept_redirect(bool intercept_redirect) {
1702 intercept_redirect_ = intercept_redirect;
1703 }
1704
1705 void set_redirect_headers(const std::string& redirect_headers) {
1706 redirect_headers_ = redirect_headers;
1707 }
1708
1709 void set_redirect_data(const std::string& redirect_data) {
1710 redirect_data_ = redirect_data;
1711 }
1712
1713 void set_cancel_redirect_request(bool cancel_redirect_request) {
1714 cancel_redirect_request_ = cancel_redirect_request;
1715 }
1716
1717 void set_intercept_final_response(bool intercept_final_response) {
1718 intercept_final_response_ = intercept_final_response;
1719 }
1720
1721 void set_final_headers(const std::string& final_headers) {
1722 final_headers_ = final_headers;
1723 }
1724
1725 void set_final_data(const std::string& final_data) {
1726 final_data_ = final_data;
1727 }
1728
1729 void set_cancel_final_request(bool cancel_final_request) {
1730 cancel_final_request_ = cancel_final_request;
1731 }
1732
1733 void set_use_url_request_http_job(bool use_url_request_http_job) {
1734 use_url_request_http_job_ = use_url_request_http_job;
1735 }
1736
1737 bool did_intercept_main() const {
1738 return did_intercept_main_;
1739 }
1740
1741 bool did_restart_main() const {
1742 return did_restart_main_;
1743 }
1744
1745 bool did_cancel_main() const {
1746 return did_cancel_main_;
1747 }
1748
1749 bool did_cancel_then_restart_main() const {
1750 return did_cancel_then_restart_main_;
1751 }
1752
1753 bool did_simulate_error_main() const {
1754 return did_simulate_error_main_;
1755 }
1756
1757 bool did_intercept_redirect() const {
1758 return did_intercept_redirect_;
1759 }
1760
1761 bool did_cancel_redirect() const {
1762 return did_cancel_redirect_;
1763 }
1764
1765 bool did_intercept_final() const {
1766 return did_intercept_final_;
1767 }
1768
1769 bool did_cancel_final() const {
1770 return did_cancel_final_;
1771 }
1772
1773 private:
1774 // Indicate whether to intercept the main request, and if so specify the
1775 // response to return and the LoadTimingInfo to use.
1776 mutable bool intercept_main_request_;
1777 mutable std::string main_headers_;
1778 mutable std::string main_data_;
1779 mutable LoadTimingInfo main_request_load_timing_info_;
1780
1781 // These indicate actions that can be taken within MaybeInterceptRequest.
1782 mutable bool restart_main_request_;
1783 mutable bool cancel_main_request_;
1784 mutable bool cancel_then_restart_main_request_;
1785 mutable bool simulate_main_network_error_;
1786
1787 // Indicate whether to intercept redirects, and if so specify the response to
1788 // return.
1789 mutable bool intercept_redirect_;
1790 mutable std::string redirect_headers_;
1791 mutable std::string redirect_data_;
1792
1793 // Cancel the request within MaybeInterceptRedirect.
1794 mutable bool cancel_redirect_request_;
1795
1796 // Indicate whether to intercept the final response, and if so specify the
1797 // response to return.
1798 mutable bool intercept_final_response_;
1799 mutable std::string final_headers_;
1800 mutable std::string final_data_;
1801
1802 // Cancel the final request within MaybeInterceptResponse.
1803 mutable bool cancel_final_request_;
1804
1805 // Instruct the interceptor to use a real URLRequestHTTPJob.
1806 mutable bool use_url_request_http_job_;
1807
1808 // These indicate if the interceptor did something or not.
1809 mutable bool did_intercept_main_;
1810 mutable bool did_restart_main_;
1811 mutable bool did_cancel_main_;
1812 mutable bool did_cancel_then_restart_main_;
1813 mutable bool did_simulate_error_main_;
1814 mutable bool did_intercept_redirect_;
1815 mutable bool did_cancel_redirect_;
1816 mutable bool did_intercept_final_;
1817 mutable bool did_cancel_final_;
1818};
1819
1820// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1821class URLRequestInterceptorTest : public URLRequestTest {
1822 public:
Raul Tambre94493c652019-03-11 17:18:351823 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:501824
1825 ~URLRequestInterceptorTest() override {
1826 // URLRequestJobs may post clean-up tasks on destruction.
1827 base::RunLoop().RunUntilIdle();
1828 }
1829
1830 void SetUpFactory() override {
1831 interceptor_ = new MockURLRequestInterceptor();
1832 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361833 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501834 }
1835
1836 MockURLRequestInterceptor* interceptor() const {
1837 return interceptor_;
1838 }
1839
1840 private:
1841 MockURLRequestInterceptor* interceptor_;
1842};
1843
1844TEST_F(URLRequestInterceptorTest, Intercept) {
1845 // Intercept the main request and respond with a simple response.
1846 interceptor()->set_intercept_main_request(true);
1847 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1848 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591849 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361850 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161851 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1852 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501853 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1854 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1855 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091856 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041857 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1858 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501859 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191860 req->Start();
Wez2a31b222018-06-07 22:07:151861 d.RunUntilComplete();
[email protected]2bba3252013-04-08 19:50:591862
bengr1bf8e942014-11-07 01:36:501863 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091864 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501865 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1866 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591867
bengr1bf8e942014-11-07 01:36:501868 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501869 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501870 EXPECT_EQ(200, req->response_headers()->response_code());
1871 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1872 EXPECT_EQ(1, d.response_started_count());
1873 EXPECT_EQ(0, d.received_redirect_count());
1874}
[email protected]2bba3252013-04-08 19:50:591875
bengr1bf8e942014-11-07 01:36:501876TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1877 // Intercept the main request and respond with a redirect.
1878 interceptor()->set_intercept_main_request(true);
1879 interceptor()->set_main_headers(
1880 MockURLRequestInterceptor::redirect_headers());
1881 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1882
1883 // Intercept that redirect and respond with a final OK response.
1884 interceptor()->set_intercept_redirect(true);
1885 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1886 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1887
1888 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361889 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161890 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1891 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501892 req->set_method("GET");
1893 req->Start();
Wez2a31b222018-06-07 22:07:151894 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501895
1896 // Check that the interceptor got called as expected.
1897 EXPECT_TRUE(interceptor()->did_intercept_main());
1898 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1899
1900 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501901 int status = d.request_status();
1902 EXPECT_EQ(OK, status);
1903 if (status == OK)
bengr1bf8e942014-11-07 01:36:501904 EXPECT_EQ(200, req->response_headers()->response_code());
1905
1906 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1907 EXPECT_EQ(1, d.response_started_count());
1908 EXPECT_EQ(0, d.received_redirect_count());
1909}
1910
1911TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1912 // Intercept the main request to generate a server error response.
1913 interceptor()->set_intercept_main_request(true);
1914 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1915 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1916
1917 // Intercept that error and respond with an OK response.
1918 interceptor()->set_intercept_final_response(true);
1919 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1920 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1921
1922 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361923 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161924 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1925 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501926 req->set_method("GET");
1927 req->Start();
Wez2a31b222018-06-07 22:07:151928 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501929
1930 // Check that the interceptor got called as expected.
1931 EXPECT_TRUE(interceptor()->did_intercept_main());
1932 EXPECT_TRUE(interceptor()->did_intercept_final());
1933
1934 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501935 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501936 EXPECT_EQ(200, req->response_headers()->response_code());
1937 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1938 EXPECT_EQ(1, d.response_started_count());
1939 EXPECT_EQ(0, d.received_redirect_count());
1940}
1941
1942TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1943 // Intercept the main request to simulate a network error.
1944 interceptor()->set_simulate_main_network_error(true);
1945
1946 // Intercept that error and respond with an OK response.
1947 interceptor()->set_intercept_final_response(true);
1948 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1949 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1950
1951 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361952 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161953 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1954 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501955 req->set_method("GET");
1956 req->Start();
Wez2a31b222018-06-07 22:07:151957 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501958
1959 // Check that the interceptor got called as expected.
1960 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1961 EXPECT_TRUE(interceptor()->did_intercept_final());
1962
1963 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501964 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501965 EXPECT_EQ(200, req->response_headers()->response_code());
1966 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1967 EXPECT_EQ(1, d.response_started_count());
1968 EXPECT_EQ(0, d.received_redirect_count());
1969}
1970
1971TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1972 // Restart the main request.
1973 interceptor()->set_restart_main_request(true);
1974
1975 // then intercept the new main request and respond with an OK response
1976 interceptor()->set_intercept_main_request(true);
1977 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1978 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1979
1980 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361981 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161982 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1983 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501984 req->set_method("GET");
1985 req->Start();
Wez2a31b222018-06-07 22:07:151986 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501987
1988 // Check that the interceptor got called as expected.
1989 EXPECT_TRUE(interceptor()->did_restart_main());
1990 EXPECT_TRUE(interceptor()->did_intercept_main());
1991
1992 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501993 int status = d.request_status();
1994 EXPECT_EQ(OK, status);
1995 if (status == OK)
bengr1bf8e942014-11-07 01:36:501996 EXPECT_EQ(200, req->response_headers()->response_code());
1997
1998 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1999 EXPECT_EQ(1, d.response_started_count());
2000 EXPECT_EQ(0, d.received_redirect_count());
2001}
2002
2003TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
2004 // Intercept the main request and cancel from within the restarted job.
2005 interceptor()->set_cancel_main_request(true);
2006
2007 // Set up to intercept the final response and override it with an OK response.
2008 interceptor()->set_intercept_final_response(true);
2009 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2010 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2011
2012 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362013 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162014 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2015 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502016 req->set_method("GET");
2017 req->Start();
Wez2a31b222018-06-07 22:07:152018 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502019
2020 // Check that the interceptor got called as expected.
2021 EXPECT_TRUE(interceptor()->did_cancel_main());
2022 EXPECT_FALSE(interceptor()->did_intercept_final());
2023
2024 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502025 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502026}
2027
2028TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2029 // Intercept the main request and respond with a redirect.
2030 interceptor()->set_intercept_main_request(true);
2031 interceptor()->set_main_headers(
2032 MockURLRequestInterceptor::redirect_headers());
2033 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2034
2035 // Intercept the redirect and cancel from within that job.
2036 interceptor()->set_cancel_redirect_request(true);
2037
2038 // Set up to intercept the final response and override it with an OK response.
2039 interceptor()->set_intercept_final_response(true);
2040 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2041 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2042
2043 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362044 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162045 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2046 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502047 req->set_method("GET");
2048 req->Start();
Wez2a31b222018-06-07 22:07:152049 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502050
2051 // Check that the interceptor got called as expected.
2052 EXPECT_TRUE(interceptor()->did_intercept_main());
2053 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2054 EXPECT_FALSE(interceptor()->did_intercept_final());
2055
2056 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502057 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502058}
2059
2060TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2061 // Intercept the main request to simulate a network error.
2062 interceptor()->set_simulate_main_network_error(true);
2063
2064 // Set up to intercept final the response and cancel from within that job.
2065 interceptor()->set_cancel_final_request(true);
2066
2067 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362068 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162069 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2070 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502071 req->set_method("GET");
2072 req->Start();
Wez2a31b222018-06-07 22:07:152073 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502074
2075 // Check that the interceptor got called as expected.
2076 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2077 EXPECT_TRUE(interceptor()->did_cancel_final());
2078
2079 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502080 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502081}
2082
2083TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2084 // Intercept the main request and cancel then restart from within that job.
2085 interceptor()->set_cancel_then_restart_main_request(true);
2086
2087 // Set up to intercept the final response and override it with an OK response.
2088 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502089 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2090 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502091
2092 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362093 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162094 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2095 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502096 req->set_method("GET");
2097 req->Start();
Wez2a31b222018-06-07 22:07:152098 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502099
2100 // Check that the interceptor got called as expected.
2101 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2102 EXPECT_FALSE(interceptor()->did_intercept_final());
2103
2104 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502105 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592106}
2107
2108// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2109// reused. |connect_time_flags| is used to indicate if there should be dns
2110// or SSL times, and |used_proxy| is used for proxy times.
2111LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2112 int connect_time_flags,
2113 bool used_proxy) {
2114 LoadTimingInfo load_timing;
2115 load_timing.socket_log_id = 1;
2116
2117 if (used_proxy) {
2118 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2119 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2120 }
2121
2122 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2123 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2124 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2125 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2126 }
2127 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2128 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2129 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2130 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2131 }
2132 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2133
2134 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2135 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382136 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2137 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592138 return load_timing;
2139}
2140
2141// Same as above, but in the case of a reused socket.
2142LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2143 bool used_proxy) {
2144 LoadTimingInfo load_timing;
2145 load_timing.socket_log_id = 1;
2146 load_timing.socket_reused = true;
2147
2148 if (used_proxy) {
2149 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2150 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2151 }
2152
2153 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2154 load_timing.send_end = now + base::TimeDelta::FromDays(10);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382155 load_timing.receive_headers_start = now + base::TimeDelta::FromDays(11);
2156 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(12);
[email protected]2bba3252013-04-08 19:50:592157 return load_timing;
2158}
2159
bengr1bf8e942014-11-07 01:36:502160LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2161 const LoadTimingInfo& job_load_timing,
2162 const URLRequestContext& context,
2163 MockURLRequestInterceptor* interceptor) {
2164 interceptor->set_intercept_main_request(true);
2165 interceptor->set_main_request_load_timing_info(job_load_timing);
2166 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162167 std::unique_ptr<URLRequest> req(
2168 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2169 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502170 req->Start();
Wez2a31b222018-06-07 22:07:152171 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502172
2173 LoadTimingInfo resulting_load_timing;
2174 req->GetLoadTimingInfo(&resulting_load_timing);
2175
2176 // None of these should be modified by the URLRequest.
2177 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2178 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2179 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2180 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
Andrew Comminos1f2ff1cc2018-12-14 05:22:382181 EXPECT_EQ(job_load_timing.receive_headers_start,
2182 resulting_load_timing.receive_headers_start);
bengr1bf8e942014-11-07 01:36:502183 EXPECT_EQ(job_load_timing.receive_headers_end,
2184 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572185 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2186 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502187
2188 return resulting_load_timing;
2189}
2190
[email protected]2bba3252013-04-08 19:50:592191// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502192TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592193 base::TimeTicks now = base::TimeTicks::Now();
2194 LoadTimingInfo job_load_timing =
2195 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2196
[email protected]2ca01e52013-10-31 22:05:192197 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502198 RunURLRequestInterceptorLoadTimingTest(
2199 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592200
2201 // Nothing should have been changed by the URLRequest.
2202 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2203 load_timing_result.proxy_resolve_start);
2204 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2205 load_timing_result.proxy_resolve_end);
2206 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2207 load_timing_result.connect_timing.dns_start);
2208 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2209 load_timing_result.connect_timing.dns_end);
2210 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2211 load_timing_result.connect_timing.connect_start);
2212 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2213 load_timing_result.connect_timing.connect_end);
2214 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2215 load_timing_result.connect_timing.ssl_start);
2216 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2217 load_timing_result.connect_timing.ssl_end);
2218
2219 // Redundant sanity check.
2220 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2221}
2222
2223// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502224TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592225 base::TimeTicks now = base::TimeTicks::Now();
2226 LoadTimingInfo job_load_timing =
2227 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2228
[email protected]2ca01e52013-10-31 22:05:192229 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502230 RunURLRequestInterceptorLoadTimingTest(
2231 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592232
2233 // Nothing should have been changed by the URLRequest.
2234 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2235 load_timing_result.proxy_resolve_start);
2236 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2237 load_timing_result.proxy_resolve_end);
2238 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2239 load_timing_result.connect_timing.dns_start);
2240 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2241 load_timing_result.connect_timing.dns_end);
2242 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2243 load_timing_result.connect_timing.connect_start);
2244 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2245 load_timing_result.connect_timing.connect_end);
2246 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2247 load_timing_result.connect_timing.ssl_start);
2248 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2249 load_timing_result.connect_timing.ssl_end);
2250
2251 // Redundant sanity check.
2252 TestLoadTimingNotReusedWithProxy(load_timing_result,
2253 CONNECT_TIMING_HAS_SSL_TIMES);
2254}
2255
2256// Make sure that URLRequest correctly adjusts proxy times when they're before
2257// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102258// the case of reusing a SPDY session. The connected socket is not considered
2259// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592260//
2261// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502262TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592263 base::TimeTicks now = base::TimeTicks::Now();
2264 LoadTimingInfo job_load_timing =
2265 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2266 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2267 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2268 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2269 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2270 job_load_timing.connect_timing.connect_start =
2271 now - base::TimeDelta::FromDays(2);
2272 job_load_timing.connect_timing.connect_end =
2273 now - base::TimeDelta::FromDays(1);
2274
[email protected]2ca01e52013-10-31 22:05:192275 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502276 RunURLRequestInterceptorLoadTimingTest(
2277 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592278
2279 // Proxy times, connect times, and DNS times should all be replaced with
2280 // request_start.
2281 EXPECT_EQ(load_timing_result.request_start,
2282 load_timing_result.proxy_resolve_start);
2283 EXPECT_EQ(load_timing_result.request_start,
2284 load_timing_result.proxy_resolve_end);
2285 EXPECT_EQ(load_timing_result.request_start,
2286 load_timing_result.connect_timing.dns_start);
2287 EXPECT_EQ(load_timing_result.request_start,
2288 load_timing_result.connect_timing.dns_end);
2289 EXPECT_EQ(load_timing_result.request_start,
2290 load_timing_result.connect_timing.connect_start);
2291 EXPECT_EQ(load_timing_result.request_start,
2292 load_timing_result.connect_timing.connect_end);
2293
2294 // Other times should have been left null.
2295 TestLoadTimingNotReusedWithProxy(load_timing_result,
2296 CONNECT_TIMING_HAS_DNS_TIMES);
2297}
2298
2299// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502300TEST_F(URLRequestInterceptorTest,
2301 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592302 base::TimeTicks now = base::TimeTicks::Now();
2303 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2304 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2305 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2306
[email protected]2ca01e52013-10-31 22:05:192307 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502308 RunURLRequestInterceptorLoadTimingTest(
2309 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592310
2311 // Proxy times and connect times should all be replaced with request_start.
2312 EXPECT_EQ(load_timing_result.request_start,
2313 load_timing_result.proxy_resolve_start);
2314 EXPECT_EQ(load_timing_result.request_start,
2315 load_timing_result.proxy_resolve_end);
2316
2317 // Other times should have been left null.
2318 TestLoadTimingReusedWithProxy(load_timing_result);
2319}
2320
2321// Make sure that URLRequest correctly adjusts connect times when they're before
2322// |request_start|, due to reusing a connected socket. The connected socket is
2323// not considered reused in this test (May be a preconnect).
2324//
2325// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502326TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592327 base::TimeTicks now = base::TimeTicks::Now();
2328 LoadTimingInfo job_load_timing =
2329 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2330 job_load_timing.connect_timing.connect_start =
2331 now - base::TimeDelta::FromDays(1);
2332 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2333 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2334 job_load_timing.connect_timing.connect_end =
2335 now - base::TimeDelta::FromDays(4);
2336
[email protected]2ca01e52013-10-31 22:05:192337 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502338 RunURLRequestInterceptorLoadTimingTest(
2339 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592340
2341 // Connect times, and SSL times should be replaced with request_start.
2342 EXPECT_EQ(load_timing_result.request_start,
2343 load_timing_result.connect_timing.connect_start);
2344 EXPECT_EQ(load_timing_result.request_start,
2345 load_timing_result.connect_timing.ssl_start);
2346 EXPECT_EQ(load_timing_result.request_start,
2347 load_timing_result.connect_timing.ssl_end);
2348 EXPECT_EQ(load_timing_result.request_start,
2349 load_timing_result.connect_timing.connect_end);
2350
2351 // Other times should have been left null.
2352 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2353}
2354
2355// Make sure that URLRequest correctly adjusts connect times when they're before
2356// |request_start|, due to reusing a connected socket in the case that there
2357// are also proxy times. The connected socket is not considered reused in this
2358// test (May be a preconnect).
2359//
2360// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502361TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592362 base::TimeTicks now = base::TimeTicks::Now();
2363 LoadTimingInfo job_load_timing =
2364 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2365 job_load_timing.connect_timing.connect_start =
2366 now - base::TimeDelta::FromDays(1);
2367 job_load_timing.connect_timing.connect_end =
2368 now - base::TimeDelta::FromDays(2);
2369
[email protected]2ca01e52013-10-31 22:05:192370 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502371 RunURLRequestInterceptorLoadTimingTest(
2372 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592373
2374 // Connect times should be replaced with proxy_resolve_end.
2375 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2376 load_timing_result.connect_timing.connect_start);
2377 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2378 load_timing_result.connect_timing.connect_end);
2379
2380 // Other times should have been left null.
2381 TestLoadTimingNotReusedWithProxy(load_timing_result,
2382 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2383}
2384
[email protected]316c1e5e2012-09-12 15:17:442385// Check that two different URL requests have different identifiers.
2386TEST_F(URLRequestTest, Identifiers) {
2387 TestDelegate d;
2388 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362389 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162390 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2391 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362392 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162393 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2394 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442395
mmenke19378d22014-09-09 04:12:592396 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442397}
2398
Matt Menke39e6de62019-06-27 20:11:392399TEST_F(URLRequestTest, NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442400 MockHostResolver host_resolver;
2401 host_resolver.rules()->AddSimulatedFailure("*");
2402
[email protected]ceefd7fd2012-11-29 00:36:242403 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
Matt Menke39e6de62019-06-27 20:11:392404 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate,
2405 true /* delay_initialization */);
2406 context.set_host_resolver(&host_resolver);
2407 context.Init();
[email protected]316c1e5e2012-09-12 15:17:442408
2409 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362410 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162411 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2412 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192413 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442414
[email protected]f7022f32014-08-21 16:32:192415 req->Start();
Wez2a31b222018-06-07 22:07:152416 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442417
2418 // Check we see a failed request.
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:222419 // The proxy server should be set before failure.
2420 EXPECT_EQ(ProxyServer::FromPacString("PROXY myproxy:70"),
2421 req->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:502422 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442423
2424 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012425 EXPECT_THAT(network_delegate.last_error(),
2426 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442427 EXPECT_EQ(1, network_delegate.completed_requests());
2428}
2429
[email protected]cba24642014-08-15 20:49:592430// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442431// content is empty.
2432TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2433 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072434 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162435 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192436 req->Start();
Wez2a31b222018-06-07 22:07:152437 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442438 EXPECT_EQ("", d.data_received());
2439 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2440}
2441
[email protected]5033ab82013-03-22 20:17:462442// Make sure that SetPriority actually sets the URLRequest's priority
2443// correctly, both before and after start.
2444TEST_F(URLRequestTest, SetPriorityBasic) {
2445 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072446 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162447 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2448 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192449 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462450
[email protected]f7022f32014-08-21 16:32:192451 req->SetPriority(LOW);
2452 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462453
[email protected]f7022f32014-08-21 16:32:192454 req->Start();
2455 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462456
[email protected]f7022f32014-08-21 16:32:192457 req->SetPriority(MEDIUM);
2458 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462459}
2460
2461// Make sure that URLRequest calls SetPriority on a job before calling
2462// Start on it.
2463TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2464 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072465 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162466 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2467 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192468 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462469
mmenkeed0498b2015-12-08 23:20:422470 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362471 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422472 req.get(), &default_network_delegate_, &job_priority));
2473 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2474 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462475
[email protected]f7022f32014-08-21 16:32:192476 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462477
[email protected]f7022f32014-08-21 16:32:192478 req->Start();
mmenkeed0498b2015-12-08 23:20:422479 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462480}
2481
2482// Make sure that URLRequest passes on its priority updates to its
2483// job.
2484TEST_F(URLRequestTest, SetJobPriority) {
2485 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072486 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162487 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2488 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462489
mmenkeed0498b2015-12-08 23:20:422490 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362491 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422492 req.get(), &default_network_delegate_, &job_priority));
2493 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462494
[email protected]f7022f32014-08-21 16:32:192495 req->SetPriority(LOW);
2496 req->Start();
mmenkeed0498b2015-12-08 23:20:422497 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462498
[email protected]f7022f32014-08-21 16:32:192499 req->SetPriority(MEDIUM);
2500 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422501 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462502}
2503
[email protected]bb1c4662013-11-14 00:00:072504// Setting the IGNORE_LIMITS load flag should be okay if the priority
2505// is MAXIMUM_PRIORITY.
2506TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2507 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072508 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162509 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2510 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192511 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072512
mmenkeed0498b2015-12-08 23:20:422513 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362514 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422515 req.get(), &default_network_delegate_, &job_priority));
2516 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072517
[email protected]f7022f32014-08-21 16:32:192518 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2519 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072520
[email protected]f7022f32014-08-21 16:32:192521 req->SetPriority(MAXIMUM_PRIORITY);
2522 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072523
[email protected]f7022f32014-08-21 16:32:192524 req->Start();
2525 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422526 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072527}
2528
nick5d570de92015-05-04 20:16:162529namespace {
2530
2531// Less verbose way of running a simple testserver for the tests below.
David Benjamin42116f62017-11-20 21:45:392532class HttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442533 public:
David Benjamin42116f62017-11-20 21:45:392534 explicit HttpTestServer(const base::FilePath& document_root) {
tommycli59a63432015-11-06 00:10:552535 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272536 }
tommycli59a63432015-11-06 00:10:552537
David Benjamin42116f62017-11-20 21:45:392538 HttpTestServer() { AddDefaultHandlers(base::FilePath()); }
tommycli59a63432015-11-06 00:10:552539};
tommyclieae5f75f2015-11-05 19:07:272540
nick5d570de92015-05-04 20:16:162541} // namespace
2542
[email protected]f2f31b32013-01-16 23:24:092543TEST_F(URLRequestTest, DelayedCookieCallback) {
David Benjamin42116f62017-11-20 21:45:392544 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442545 ASSERT_TRUE(test_server.Start());
2546
2547 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362548 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502549 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442550
2551 // Set up a cookie.
2552 {
2553 TestNetworkDelegate network_delegate;
2554 context.set_network_delegate(&network_delegate);
2555 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362556 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552557 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162558 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192559 req->Start();
Wez2a31b222018-06-07 22:07:152560 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442561 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2562 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2563 EXPECT_EQ(1, network_delegate.set_cookie_count());
2564 }
2565
2566 // Verify that the cookie is set.
2567 {
2568 TestNetworkDelegate network_delegate;
2569 context.set_network_delegate(&network_delegate);
2570 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362571 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162572 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2573 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192574 req->Start();
Wez2a31b222018-06-07 22:07:152575 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442576
2577 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2578 != std::string::npos);
2579 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2580 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2581 }
2582}
2583
Aaron Tagliaboschi028009e2019-03-07 16:28:062584class FilteringTestLayeredNetworkDelegate : public LayeredNetworkDelegate {
2585 public:
2586 FilteringTestLayeredNetworkDelegate(
2587 std::unique_ptr<NetworkDelegate> network_delegate)
2588 : LayeredNetworkDelegate(std::move((network_delegate))),
2589 set_cookie_called_count_(0),
Aaron Tagliaboschifd4f3f012019-05-30 23:05:542590 blocked_set_cookie_count_(0),
2591 block_get_cookies_(false),
2592 get_cookie_called_count_(0),
2593 blocked_get_cookie_count_(0) {}
Aaron Tagliaboschi028009e2019-03-07 16:28:062594 ~FilteringTestLayeredNetworkDelegate() override = default;
2595
2596 bool OnCanSetCookieInternal(const URLRequest& request,
2597 const net::CanonicalCookie& cookie,
2598 CookieOptions* options,
2599 bool allowed_from_caller) override {
2600 // Filter out cookies with the same name as |cookie_name_filter_| and
2601 // combine with |allowed_from_caller|.
2602 bool allowed =
2603 allowed_from_caller && !(cookie.Name() == cookie_name_filter_);
2604
2605 ++set_cookie_called_count_;
2606
2607 if (!allowed)
2608 ++blocked_set_cookie_count_;
2609
2610 return allowed;
2611 }
2612
2613 void SetCookieFilter(std::string filter) {
2614 cookie_name_filter_ = std::move(filter);
2615 }
2616
2617 int set_cookie_called_count() { return set_cookie_called_count_; }
2618
2619 int blocked_set_cookie_count() { return blocked_set_cookie_count_; }
2620
2621 void ResetSetCookieCalledCount() { set_cookie_called_count_ = 0; }
2622
2623 void ResetBlockedSetCookieCount() { blocked_set_cookie_count_ = 0; }
2624
Aaron Tagliaboschifd4f3f012019-05-30 23:05:542625 bool OnCanGetCookiesInternal(const URLRequest& request,
2626 const net::CookieList& cookie,
2627 bool allowed_from_caller) override {
2628 // Filter out cookies if |block_get_cookies_| is set and
2629 // combine with |allowed_from_caller|.
2630 bool allowed = allowed_from_caller && !block_get_cookies_;
2631
2632 ++get_cookie_called_count_;
2633
2634 if (!allowed)
2635 ++blocked_get_cookie_count_;
2636
2637 return allowed;
2638 }
2639
2640 void set_block_get_cookies() { block_get_cookies_ = true; }
2641
2642 void unset_block_get_cookies() { block_get_cookies_ = false; }
2643
2644 int get_cookie_called_count() const { return get_cookie_called_count_; }
2645
2646 int blocked_get_cookie_count() const { return blocked_get_cookie_count_; }
2647
2648 void ResetGetCookieCalledCount() { get_cookie_called_count_ = 0; }
2649
2650 void ResetBlockedGetCookieCount() { blocked_get_cookie_count_ = 0; }
2651
Aaron Tagliaboschi028009e2019-03-07 16:28:062652 private:
2653 std::string cookie_name_filter_;
2654 int set_cookie_called_count_;
2655 int blocked_set_cookie_count_;
Aaron Tagliaboschifd4f3f012019-05-30 23:05:542656
2657 bool block_get_cookies_;
2658 int get_cookie_called_count_;
2659 int blocked_get_cookie_count_;
Aaron Tagliaboschi028009e2019-03-07 16:28:062660};
2661
2662TEST_F(URLRequestTest, DelayedCookieCallbackAsync) {
2663 HttpTestServer test_server;
2664 ASSERT_TRUE(test_server.Start());
2665
2666 TestURLRequestContext async_context;
2667 std::unique_ptr<DelayedCookieMonster> delayed_cm =
2668 std::make_unique<DelayedCookieMonster>();
2669 async_context.set_cookie_store(delayed_cm.get());
2670 FilteringTestLayeredNetworkDelegate async_filter_network_delegate(
2671 std::make_unique<TestNetworkDelegate>());
2672 async_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
2673 async_context.set_network_delegate(&async_filter_network_delegate);
2674 TestDelegate async_delegate;
2675
2676 TestURLRequestContext sync_context;
2677 std::unique_ptr<CookieMonster> cm =
Nick Harper57142b1c2019-03-14 21:03:592678 std::make_unique<CookieMonster>(nullptr, nullptr);
Aaron Tagliaboschi028009e2019-03-07 16:28:062679 sync_context.set_cookie_store(cm.get());
2680 FilteringTestLayeredNetworkDelegate sync_filter_network_delegate(
2681 std::make_unique<TestNetworkDelegate>());
2682 sync_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
2683 sync_context.set_network_delegate(&sync_filter_network_delegate);
2684 TestDelegate sync_delegate;
2685
2686 // Add a secure cookie so we can try to set an insecure cookie and have
Lily Chen0f208ea2019-08-08 23:37:532687 // SetCanonicalCookie fail.
Aaron Tagliaboschi028009e2019-03-07 16:28:062688 GURL::Replacements replace_scheme;
2689 replace_scheme.SetSchemeStr("https");
2690 GURL url = test_server.base_url().ReplaceComponents(replace_scheme);
2691
Lily Chen0f208ea2019-08-08 23:37:532692 auto cookie1 = CanonicalCookie::Create(url, "AlreadySetCookie=1;Secure",
2693 base::Time::Now(),
2694 base::nullopt /* server_time */);
2695 delayed_cm->SetCanonicalCookieAsync(std::move(cookie1), url.scheme(),
2696 CookieOptions(),
2697 CookieStore::SetCookiesCallback());
2698 auto cookie2 = CanonicalCookie::Create(url, "AlreadySetCookie=1;Secure",
2699 base::Time::Now(),
2700 base::nullopt /* server_time */);
2701 cm->SetCanonicalCookieAsync(std::move(cookie2), url.scheme(), CookieOptions(),
2702 CookieStore::SetCookiesCallback());
Aaron Tagliaboschi028009e2019-03-07 16:28:062703
2704 std::vector<std::string> cookie_lines(
Lily Chenf5732c82019-08-01 00:01:542705 {// Fails in SetCanonicalCookie for trying to set a secure cookie
Aaron Tagliaboschi028009e2019-03-07 16:28:062706 // on an insecure host.
2707 "CookieNotSet=1;Secure",
2708 // Fail in FilteringTestLayeredNetworkDelegate::CanGetCookie.
2709 "CookieBlockedOnCanGetCookie=1",
2710 // Fails in SetCanonicalCookie for trying to overwrite a secure cookie
2711 // with an insecure cookie.
2712 "AlreadySetCookie=1",
2713 // Succeeds and added cookie to store. Delayed (which makes the callback
2714 // run asynchronously) in DelayedCookieMonster.
2715 "CookieSet=1"});
2716
2717 for (auto first_cookie_line : cookie_lines) {
2718 for (auto second_cookie_line : cookie_lines) {
2719 // Run with the delayed cookie monster.
2720 std::unique_ptr<URLRequest> request = async_context.CreateRequest(
2721 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2722 second_cookie_line),
2723 DEFAULT_PRIORITY, &async_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2724
2725 request->Start();
2726 async_delegate.RunUntilComplete();
2727 EXPECT_THAT(async_delegate.request_status(), IsOk());
2728
2729 // Run with the regular cookie monster.
2730 request = sync_context.CreateRequest(
2731 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2732 second_cookie_line),
2733 DEFAULT_PRIORITY, &sync_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2734
2735 request->Start();
2736 sync_delegate.RunUntilComplete();
2737 EXPECT_THAT(sync_delegate.request_status(), IsOk());
2738
2739 int expected_set_cookie_count = 0;
2740 int expected_blocked_cookie_count = 0;
2741
Lily Chenf5732c82019-08-01 00:01:542742 // 2 calls to the delegate's OnCanSetCookie method are expected, even if
2743 // the cookies don't end up getting set.
2744 expected_set_cookie_count += 2;
Aaron Tagliaboschi028009e2019-03-07 16:28:062745
2746 if (first_cookie_line == "CookieBlockedOnCanGetCookie=1")
2747 ++expected_blocked_cookie_count;
2748 if (second_cookie_line == "CookieBlockedOnCanGetCookie=1")
2749 ++expected_blocked_cookie_count;
2750
2751 EXPECT_EQ(expected_set_cookie_count,
2752 async_filter_network_delegate.set_cookie_called_count());
2753 EXPECT_EQ(expected_blocked_cookie_count,
2754 async_filter_network_delegate.blocked_set_cookie_count());
2755
2756 EXPECT_EQ(expected_set_cookie_count,
2757 sync_filter_network_delegate.set_cookie_called_count());
2758 EXPECT_EQ(expected_blocked_cookie_count,
2759 sync_filter_network_delegate.blocked_set_cookie_count());
2760
2761 async_filter_network_delegate.ResetSetCookieCalledCount();
2762 async_filter_network_delegate.ResetBlockedSetCookieCount();
2763
2764 sync_filter_network_delegate.ResetSetCookieCalledCount();
2765 sync_filter_network_delegate.ResetBlockedSetCookieCount();
2766 }
2767 }
2768}
2769
[email protected]f2f31b32013-01-16 23:24:092770TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392771 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442772 ASSERT_TRUE(test_server.Start());
2773
2774 // Set up a cookie.
2775 {
2776 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072777 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442778 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072779 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552780 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162781 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192782 req->Start();
Wez2a31b222018-06-07 22:07:152783 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442784 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2785 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2786 }
2787
2788 // Verify that the cookie is set.
2789 {
2790 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072791 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442792 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072793 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162794 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2795 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192796 req->Start();
Wez2a31b222018-06-07 22:07:152797 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442798
2799 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2800 != std::string::npos);
2801 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2802 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2803 }
2804
2805 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2806 {
2807 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072808 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442809 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072810 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162811 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2812 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192813 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2814 req->Start();
Wez2a31b222018-06-07 22:07:152815 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442816
2817 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2818 == std::string::npos);
2819
2820 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2821 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2822 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2823 }
2824}
2825
2826TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392827 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442828 ASSERT_TRUE(test_server.Start());
2829
2830 // Set up a cookie.
2831 {
2832 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072833 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442834 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072835 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552836 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162837 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192838 req->Start();
Wez2a31b222018-06-07 22:07:152839 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442840
2841 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2842 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2843 EXPECT_EQ(1, network_delegate.set_cookie_count());
2844 }
2845
2846 // Try to set-up another cookie and update the previous cookie.
2847 {
2848 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072849 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442850 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072851 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552852 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162853 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192854 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2855 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442856
Wez2a31b222018-06-07 22:07:152857 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442858
2859 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2860 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2861 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2862 EXPECT_EQ(0, network_delegate.set_cookie_count());
2863 }
2864
2865 // Verify the cookies weren't saved or updated.
2866 {
2867 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072868 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442869 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072870 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162871 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2872 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192873 req->Start();
Wez2a31b222018-06-07 22:07:152874 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442875
2876 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2877 == std::string::npos);
2878 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2879 != std::string::npos);
2880
2881 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2882 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2883 EXPECT_EQ(0, network_delegate.set_cookie_count());
2884 }
2885}
2886
2887TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392888 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442889 ASSERT_TRUE(test_server.Start());
2890
2891 // Set up a cookie.
2892 {
2893 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072894 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442895 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072896 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552897 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162898 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192899 req->Start();
Wez2a31b222018-06-07 22:07:152900 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442901
2902 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2903 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2904 }
2905
2906 // Verify that the cookie is set.
2907 {
2908 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072909 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442910 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072911 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162912 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2913 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192914 req->Start();
Wez2a31b222018-06-07 22:07:152915 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442916
2917 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2918 != std::string::npos);
2919
2920 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2921 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Eric Roman79cc7552019-07-19 02:17:542922 auto entries = net_log_.GetEntries();
Helen Li830d5708d62018-08-22 16:29:182923 for (const auto& entry : entries) {
2924 EXPECT_NE(entry.type,
2925 NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE);
2926 }
[email protected]316c1e5e2012-09-12 15:17:442927 }
2928
2929 // Verify that the cookie isn't sent.
2930 {
2931 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072932 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442933 TestDelegate d;
2934 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:072935 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162936 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2937 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192938 req->Start();
Wez2a31b222018-06-07 22:07:152939 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442940
2941 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2942 == std::string::npos);
2943
[email protected]22e045f2013-09-20 03:54:032944 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442945 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Eric Roman79cc7552019-07-19 02:17:542946 auto entries = net_log_.GetEntries();
Helen Li830d5708d62018-08-22 16:29:182947 ExpectLogContainsSomewhereAfter(
2948 entries, 0, NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE,
2949 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442950 }
2951}
2952
marqf14fff8d2015-12-02 15:52:292953// TODO(crbug.com/564656) This test is flaky on iOS.
2954#if defined(OS_IOS)
2955#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2956#else
2957#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2958#endif
[email protected]316c1e5e2012-09-12 15:17:442959TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392960 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442961 ASSERT_TRUE(test_server.Start());
2962
2963 // Set up a cookie.
2964 {
2965 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072966 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442967 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072968 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552969 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162970 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192971 req->Start();
Wez2a31b222018-06-07 22:07:152972 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442973
2974 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2975 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Eric Roman79cc7552019-07-19 02:17:542976 auto entries = net_log_.GetEntries();
Helen Li830d5708d62018-08-22 16:29:182977 for (const auto& entry : entries) {
2978 EXPECT_NE(entry.type,
2979 NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE);
2980 }
[email protected]316c1e5e2012-09-12 15:17:442981 }
2982
2983 // Try to set-up another cookie and update the previous cookie.
2984 {
2985 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072986 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442987 TestDelegate d;
2988 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:072989 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552990 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162991 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192992 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442993
Wez2a31b222018-06-07 22:07:152994 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442995
2996 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2997 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
Eric Roman79cc7552019-07-19 02:17:542998 auto entries = net_log_.GetEntries();
Helen Li830d5708d62018-08-22 16:29:182999 ExpectLogContainsSomewhereAfter(
3000 entries, 0, NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE,
3001 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:443002 }
3003
3004 // Verify the cookies weren't saved or updated.
3005 {
3006 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073007 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443008 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073009 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163010 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3011 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193012 req->Start();
Wez2a31b222018-06-07 22:07:153013 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443014
3015 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
3016 == std::string::npos);
3017 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
3018 != std::string::npos);
3019
3020 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3021 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3022 }
3023}
3024
3025TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:393026 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443027 ASSERT_TRUE(test_server.Start());
3028
3029 // Set up an empty cookie.
3030 {
3031 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073032 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443033 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073034 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163035 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
3036 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193037 req->Start();
Wez2a31b222018-06-07 22:07:153038 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443039
3040 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3041 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3042 EXPECT_EQ(0, network_delegate.set_cookie_count());
3043 }
3044}
3045
3046TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393047 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443048 ASSERT_TRUE(test_server.Start());
3049
3050 // Set up a cookie.
3051 {
3052 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073053 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443054 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073055 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553056 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163057 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193058 req->Start();
Wez2a31b222018-06-07 22:07:153059 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443060
3061 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3062 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3063 }
3064
3065 // Verify that the cookie is set.
3066 {
3067 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073068 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443069 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073070 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163071 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3072 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193073 req->Start();
Wez2a31b222018-06-07 22:07:153074 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443075
3076 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
3077 != std::string::npos);
3078
3079 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3080 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3081 }
3082
3083 // Verify that the cookie isn't sent.
3084 {
3085 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073086 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443087 TestDelegate d;
3088 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:073089 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163090 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3091 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193092 req->Start();
Wez2a31b222018-06-07 22:07:153093 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443094
3095 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
3096 == std::string::npos);
3097
[email protected]22e045f2013-09-20 03:54:033098 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:443099 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3100 }
3101}
3102
3103TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393104 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443105 ASSERT_TRUE(test_server.Start());
3106
3107 // Set up a cookie.
3108 {
3109 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073110 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443111 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073112 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553113 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163114 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193115 req->Start();
Wez2a31b222018-06-07 22:07:153116 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443117
3118 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3119 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3120 }
3121
3122 // Try to set-up another cookie and update the previous cookie.
3123 {
3124 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073125 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443126 TestDelegate d;
3127 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:073128 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553129 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:163130 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193131 req->Start();
[email protected]316c1e5e2012-09-12 15:17:443132
Wez2a31b222018-06-07 22:07:153133 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443134
3135 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3136 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
3137 }
3138
3139 // Verify the cookies weren't saved or updated.
3140 {
3141 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073142 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443143 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073144 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163145 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3146 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193147 req->Start();
Wez2a31b222018-06-07 22:07:153148 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443149
3150 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
3151 == std::string::npos);
3152 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
3153 != std::string::npos);
3154
3155 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3156 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3157 }
3158}
3159
mkwstc5fa7762016-03-28 09:28:233160TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:393161 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:263162 ASSERT_TRUE(test_server.Start());
3163
mkwst202534e32016-01-15 16:07:153164 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073165 default_context().set_network_delegate(&network_delegate);
mkwst202534e32016-01-15 16:07:153166
mkwstf71d0bd2016-03-21 14:15:243167 const std::string kHost = "example.test";
3168 const std::string kSubHost = "subdomain.example.test";
3169 const std::string kCrossHost = "cross-origin.test";
3170
3171 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:263172 {
mkwst3f3daac2015-02-26 20:15:263173 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073174 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
mkwstf71d0bd2016-03-21 14:15:243175 test_server.GetURL(kHost,
3176 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3177 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:163178 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Maks Orlovich8a3e4132019-04-23 16:59:243179 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3180 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263181 req->Start();
Wez2a31b222018-06-07 22:07:153182 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263183 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3184 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:243185 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:263186 }
3187
mkwstf71d0bd2016-03-21 14:15:243188 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:263189 {
mkwst3f3daac2015-02-26 20:15:263190 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073191 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163192 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3193 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463194 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463195 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263196 req->Start();
Wez2a31b222018-06-07 22:07:153197 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263198
mkwstf71d0bd2016-03-21 14:15:243199 EXPECT_NE(std::string::npos,
3200 d.data_received().find("StrictSameSiteCookie=1"));
3201 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263202 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3203 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3204 }
3205
clamyfd58ca072016-12-21 17:18:323206 // Verify that both cookies are sent when the request has no initiator (can
3207 // happen for main frame browser-initiated navigations).
3208 {
3209 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073210 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163211 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3212 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463213 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:323214 req->Start();
Wez2a31b222018-06-07 22:07:153215 d.RunUntilComplete();
clamyfd58ca072016-12-21 17:18:323216
3217 EXPECT_NE(std::string::npos,
3218 d.data_received().find("StrictSameSiteCookie=1"));
3219 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3220 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3221 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3222 }
3223
mkwstf71d0bd2016-03-21 14:15:243224 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263225 {
mkwst3f3daac2015-02-26 20:15:263226 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073227 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163228 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3229 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463230 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463231 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153232 req->Start();
Wez2a31b222018-06-07 22:07:153233 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153234
mkwstf71d0bd2016-03-21 14:15:243235 EXPECT_NE(std::string::npos,
3236 d.data_received().find("StrictSameSiteCookie=1"));
3237 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153238 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3239 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3240 }
3241
mkwstf71d0bd2016-03-21 14:15:243242 // Verify that neither cookie is not sent for cross-site requests.
3243 {
3244 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073245 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163246 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3247 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463248 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463249 req->set_initiator(
3250 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243251 req->Start();
Wez2a31b222018-06-07 22:07:153252 d.RunUntilComplete();
mkwstf71d0bd2016-03-21 14:15:243253
3254 EXPECT_EQ(std::string::npos,
3255 d.data_received().find("StrictSameSiteCookie=1"));
3256 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3257 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3258 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3259 }
3260
3261 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153262 // method is "safe".
3263 {
3264 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073265 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163266 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3267 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463268 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463269 req->set_initiator(
3270 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243271 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153272 req->Start();
Wez2a31b222018-06-07 22:07:153273 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153274
mkwstf71d0bd2016-03-21 14:15:243275 EXPECT_EQ(std::string::npos,
3276 d.data_received().find("StrictSameSiteCookie=1"));
3277 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153278 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3279 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3280 }
3281
mkwstf71d0bd2016-03-21 14:15:243282 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153283 // method is unsafe (e.g. POST).
3284 {
3285 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073286 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163287 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3288 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463289 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463290 req->set_initiator(
3291 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153292 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263293 req->Start();
Wez2a31b222018-06-07 22:07:153294 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263295
mkwstf71d0bd2016-03-21 14:15:243296 EXPECT_EQ(std::string::npos,
3297 d.data_received().find("StrictSameSiteCookie=1"));
3298 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263299 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3300 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3301 }
3302}
3303
Maks Orlovich8a3e4132019-04-23 16:59:243304TEST_F(URLRequestTest, SettingSameSiteCookies) {
3305 HttpTestServer test_server;
3306 ASSERT_TRUE(test_server.Start());
3307
3308 TestNetworkDelegate network_delegate;
3309 default_context().set_network_delegate(&network_delegate);
3310
3311 const std::string kHost = "example.test";
3312 const std::string kSubHost = "subdomain.example.test";
3313 const std::string kCrossHost = "cross-origin.test";
3314
3315 int expected_cookies = 0;
3316
3317 {
3318 TestDelegate d;
3319 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3320 test_server.GetURL(kHost,
Lily Chenf5732c82019-08-01 00:01:543321 "/set-cookie?Strict1=1;SameSite=Strict&"
3322 "Lax1=1;SameSite=Lax"),
Maks Orlovich8a3e4132019-04-23 16:59:243323 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3324 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3325 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
3326
3327 // 'SameSite' cookies are settable from strict same-site contexts
3328 // (same-origin site_for_cookies, same-origin initiator), so this request
Lily Chenf5732c82019-08-01 00:01:543329 // should result in two cookies being set.
Maks Orlovich8a3e4132019-04-23 16:59:243330 expected_cookies += 2;
3331
3332 req->Start();
3333 d.RunUntilComplete();
Lily Chenf5732c82019-08-01 00:01:543334 EXPECT_EQ(expected_cookies,
3335 static_cast<int>(GetAllCookies(&default_context()).size()));
Maks Orlovich8a3e4132019-04-23 16:59:243336 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3337 }
3338
3339 {
3340 TestDelegate d;
3341 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3342 test_server.GetURL(kHost,
Lily Chenf5732c82019-08-01 00:01:543343 "/set-cookie?Strict2=1;SameSite=Strict&"
3344 "Lax2=1;SameSite=Lax"),
Maks Orlovich8a3e4132019-04-23 16:59:243345 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3346 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3347 req->set_initiator(
3348 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3349
3350 // 'SameSite' cookies are settable from lax same-site contexts (same-origin
3351 // site_for_cookies, cross-site initiator), so this request should result in
Lily Chenf5732c82019-08-01 00:01:543352 // two cookies being set.
Maks Orlovich8a3e4132019-04-23 16:59:243353 expected_cookies += 2;
3354
3355 req->Start();
3356 d.RunUntilComplete();
Lily Chenf5732c82019-08-01 00:01:543357 EXPECT_EQ(expected_cookies,
3358 static_cast<int>(GetAllCookies(&default_context()).size()));
Maks Orlovich8a3e4132019-04-23 16:59:243359 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3360 }
3361
3362 {
3363 TestDelegate d;
3364 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3365 test_server.GetURL(kHost,
Lily Chenf5732c82019-08-01 00:01:543366 "/set-cookie?Strict3=1;SameSite=Strict&"
3367 "Lax3=1;SameSite=Lax"),
Maks Orlovich8a3e4132019-04-23 16:59:243368 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3369 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
3370 req->set_initiator(
3371 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3372
3373 // 'SameSite' cookies are settable from lax same-site contexts (same-site
3374 // site_for_cookies, cross-site initiator), so this request should result in
Lily Chenf5732c82019-08-01 00:01:543375 // two cookies being set.
Maks Orlovich8a3e4132019-04-23 16:59:243376 expected_cookies += 2;
3377
3378 req->Start();
3379 d.RunUntilComplete();
Lily Chenf5732c82019-08-01 00:01:543380 EXPECT_EQ(expected_cookies,
3381 static_cast<int>(GetAllCookies(&default_context()).size()));
Maks Orlovich8a3e4132019-04-23 16:59:243382 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3383 }
3384
3385 {
3386 TestDelegate d;
3387 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3388 test_server.GetURL(kHost,
Lily Chenf5732c82019-08-01 00:01:543389 "/set-cookie?Strict4=1;SameSite=Strict&"
3390 "Lax4=1;SameSite=Lax"),
Maks Orlovich8a3e4132019-04-23 16:59:243391 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3392 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
3393
3394 // 'SameSite' cookies are settable from strict same-site contexts (same-site
3395 // site_for_cookies, no initiator), so this request should result in two
Lily Chenf5732c82019-08-01 00:01:543396 // cookies being set.
Maks Orlovich8a3e4132019-04-23 16:59:243397 expected_cookies += 2;
3398
3399 req->Start();
3400 d.RunUntilComplete();
Lily Chenf5732c82019-08-01 00:01:543401 EXPECT_EQ(expected_cookies,
3402 static_cast<int>(GetAllCookies(&default_context()).size()));
Maks Orlovich8a3e4132019-04-23 16:59:243403 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3404 }
3405
3406 {
3407 TestDelegate d;
3408 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3409 test_server.GetURL(kHost,
Lily Chenf5732c82019-08-01 00:01:543410 "/set-cookie?Strict5=1;SameSite=Strict&"
3411 "Lax5=1;SameSite=Lax"),
Maks Orlovich8a3e4132019-04-23 16:59:243412 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3413 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
3414 req->set_initiator(
3415 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3416
3417 // 'SameSite' cookies are not settable from cross-site contexts, so this
Lily Chenf5732c82019-08-01 00:01:543418 // should not result in any new cookies being set.
Maks Orlovich8a3e4132019-04-23 16:59:243419 expected_cookies += 0;
3420
3421 req->Start();
3422 d.RunUntilComplete();
Lily Chenf5732c82019-08-01 00:01:543423 // This counts the number of cookies actually set.
3424 EXPECT_EQ(expected_cookies,
3425 static_cast<int>(GetAllCookies(&default_context()).size()));
3426 // This counts the number of successful calls to CanSetCookie() when
3427 // attempting to set a cookie. The two cookies above were created and
3428 // attempted to be set, and were not rejected by the NetworkDelegate, so the
3429 // count here is 2 more than the number of cookies actually set.
3430 EXPECT_EQ(expected_cookies + 2, network_delegate.set_cookie_count());
Maks Orlovich8a3e4132019-04-23 16:59:243431 }
3432}
3433
estark557a5eb82015-12-01 22:57:103434// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363435TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553436 EmbeddedTestServer http_server;
3437 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363438 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553439 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3440 https_server.AddDefaultHandlers(
3441 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3442 ASSERT_TRUE(http_server.Start());
3443 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363444
estarkb15166b2015-12-18 16:56:383445 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363446 TestURLRequestContext context(true);
3447 context.set_network_delegate(&network_delegate);
3448 context.Init();
3449
estarkb15166b2015-12-18 16:56:383450 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363451 {
3452 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363453 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103454 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163455 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363456 req->Start();
Wez2a31b222018-06-07 22:07:153457 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363458 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3459 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3460 }
3461
3462 // Verify that the cookie is not set.
3463 {
3464 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363465 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163466 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3467 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363468 req->Start();
Wez2a31b222018-06-07 22:07:153469 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363470
jww79aceda2015-12-07 01:56:343471 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3472 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363473 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3474 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3475 }
3476}
3477
estarkb15166b2015-12-18 16:56:383478TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553479 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3480 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363481 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553482 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363483
3484 TestNetworkDelegate network_delegate;
3485 TestURLRequestContext context(true);
3486 context.set_network_delegate(&network_delegate);
3487 context.Init();
3488
estarkb15166b2015-12-18 16:56:383489 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363490 {
3491 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163492 std::unique_ptr<URLRequest> req(context.CreateRequest(
3493 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3494 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363495 req->Start();
Wez2a31b222018-06-07 22:07:153496 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583497 EXPECT_EQ(0, network_delegate.set_cookie_count());
estarkcd39c11f2015-10-19 19:46:363498 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3499 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3500 }
3501
3502 // Verify that the cookie is not set.
3503 {
3504 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363505 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163506 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3507 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363508 req->Start();
Wez2a31b222018-06-07 22:07:153509 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363510
jww79aceda2015-12-07 01:56:343511 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363512 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3513 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3514 }
3515}
3516
estarkb15166b2015-12-18 16:56:383517TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553518 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3519 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363520 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553521 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363522
estarkb15166b2015-12-18 16:56:383523 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363524 TestURLRequestContext context(true);
3525 context.set_network_delegate(&network_delegate);
3526 context.Init();
3527
estarkb15166b2015-12-18 16:56:383528 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363529 {
3530 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363531 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103532 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163533 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363534 req->Start();
Wez2a31b222018-06-07 22:07:153535 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363536 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3537 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3538 }
3539
3540 // Verify that the cookie is set.
3541 {
3542 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363543 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163544 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3545 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363546 req->Start();
Wez2a31b222018-06-07 22:07:153547 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363548
jww79aceda2015-12-07 01:56:343549 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3550 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3551 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3552 }
3553}
3554
3555// Tests that secure cookies can't be set on non-secure origins if strict secure
3556// cookies are enabled.
3557TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3558 EmbeddedTestServer http_server;
3559 http_server.AddDefaultHandlers(
3560 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3561 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3562 https_server.AddDefaultHandlers(
3563 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3564 ASSERT_TRUE(http_server.Start());
3565 ASSERT_TRUE(https_server.Start());
3566
Matt Menkebe9b6eb2018-10-18 12:11:443567 TestNetworkDelegate network_delegate;
jww79aceda2015-12-07 01:56:343568 TestURLRequestContext context(true);
3569 context.set_network_delegate(&network_delegate);
3570 context.Init();
3571
3572 // Try to set a Secure cookie, with experimental features enabled.
3573 {
3574 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363575 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343576 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163577 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343578 req->Start();
Wez2a31b222018-06-07 22:07:153579 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343580 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3581 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3582 }
3583
3584 // Verify that the cookie is not set.
3585 {
3586 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363587 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163588 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3589 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343590 req->Start();
Wez2a31b222018-06-07 22:07:153591 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343592
3593 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3594 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3595 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3596 }
3597}
3598
Thiemo Nagel0793b9c532018-04-18 16:57:583599// The parameter is true for same-site and false for cross-site requests.
3600class URLRequestTestParameterizedSameSite
3601 : public URLRequestTest,
3602 public ::testing::WithParamInterface<bool> {
3603 protected:
3604 URLRequestTestParameterizedSameSite() {
3605 auto params = std::make_unique<HttpNetworkSession::Params>();
3606 params->ignore_certificate_errors = true;
3607 context_.set_http_network_session_params(std::move(params));
3608 context_.set_network_delegate(&network_delegate_);
3609 https_server_.AddDefaultHandlers(
3610 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3611 EXPECT_TRUE(https_server_.Start());
3612 }
3613
3614 // To be called after configuration of |context_| has been finalized.
3615 void InitContext() { context_.Init(); }
3616
3617 const std::string kHost_ = "example.test";
3618 const std::string kCrossHost_ = "cross-site.test";
3619 TestURLRequestContext context_{true};
3620 TestNetworkDelegate network_delegate_;
3621 base::HistogramTester histograms_;
3622 EmbeddedTestServer https_server_{EmbeddedTestServer::TYPE_HTTPS};
3623};
3624
Victor Costan8fb98f6f2019-02-01 17:08:293625INSTANTIATE_TEST_SUITE_P(URLRequestTest,
3626 URLRequestTestParameterizedSameSite,
3627 ::testing::Bool());
Thiemo Nagel0793b9c532018-04-18 16:57:583628
3629TEST_P(URLRequestTestParameterizedSameSite, CookieAgeMetrics) {
3630 const bool same_site = GetParam();
3631 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3632 InitContext();
3633
Mike West86149882017-07-28 10:41:493634 EmbeddedTestServer http_server;
3635 http_server.AddDefaultHandlers(
3636 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
Thiemo Nagel23e0b322018-04-18 12:46:543637 ASSERT_TRUE(http_server.Start());
3638
Thiemo Nagel0793b9c532018-04-18 16:57:583639 // Set two test cookies.
Thiemo Nagel23e0b322018-04-18 12:46:543640 {
3641 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583642 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3643 http_server.GetURL(kHost_, "/set-cookie?cookie=value&cookie2=value2"),
Thiemo Nagel23e0b322018-04-18 12:46:543644 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3645 req->Start();
Wez2a31b222018-06-07 22:07:153646 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583647 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3648 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3649 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3650 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3651 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 0);
3652 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3653 0);
3654 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3655 0);
3656 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3657 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 0);
Thiemo Nagel23e0b322018-04-18 12:46:543658 }
3659
Thiemo Nagel0793b9c532018-04-18 16:57:583660 // Make a secure request.
Thiemo Nagel23e0b322018-04-18 12:46:543661 {
3662 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583663 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3664 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3665 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3666 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103667 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583668 url::Origin::Create(https_server_.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103669 req->Start();
Wez2a31b222018-06-07 22:07:153670 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583671 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3672 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3673 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3674 !same_site);
3675 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3676 same_site);
3677 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3678 0);
3679 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3680 0);
3681 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3682 same_site ? 0 : 2);
3683 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3684 same_site ? 2 : 0);
3685 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3686 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
Mohsen Izadiad6f7592018-04-18 15:57:103687 }
3688
Thiemo Nagel0793b9c532018-04-18 16:57:583689 // Make a non-secure request.
Mohsen Izadiad6f7592018-04-18 15:57:103690 {
3691 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583692 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3693 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
Mohsen Izadiad6f7592018-04-18 15:57:103694 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel0793b9c532018-04-18 16:57:583695 req->set_site_for_cookies(http_server.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103696 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583697 url::Origin::Create(http_server.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103698 req->Start();
Wez2a31b222018-06-07 22:07:153699 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583700 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest",
3701 !same_site);
3702 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest",
3703 same_site);
3704 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3705 !same_site);
3706 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3707 same_site);
3708 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3709 same_site ? 0 : 2);
3710 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3711 same_site ? 2 : 0);
3712 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3713 same_site ? 0 : 2);
3714 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3715 same_site ? 2 : 0);
3716 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3717 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
3718 }
3719}
3720
3721// Cookies with secure attribute (no HSTS) --> k1pSecureAttribute
3722TEST_P(URLRequestTestParameterizedSameSite,
3723 CookieNetworkSecurityMetricSecureAttribute) {
3724 const bool same_site = GetParam();
3725 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3726 InitContext();
3727
3728 // Set cookies.
3729 {
3730 TestDelegate d;
3731 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3732 https_server_.GetURL(kHost_,
3733 "/set-cookie?session-cookie=value;Secure&"
3734 "longlived-cookie=value;Secure;domain=" +
3735 kHost_ + ";Max-Age=360000"),
3736 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3737 req->Start();
Wez2a31b222018-06-07 22:07:153738 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583739 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3740 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3741 }
3742
3743 // Verify that the cookies fall into the correct metrics bucket.
3744 {
3745 TestDelegate d;
3746 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3747 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3748 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3749 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3750 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3751 req->Start();
Wez2a31b222018-06-07 22:07:153752 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583753 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3754 // Static cast of boolean required for MSVC 1911.
3755 histograms_.ExpectBucketCount(
3756 "Cookie.NetworkSecurity",
3757 static_cast<int>(CookieNetworkSecurity::k1pSecureAttribute) |
3758 static_cast<int>(!same_site),
3759 2);
3760 }
3761}
3762
3763// Short-lived host cookie --> k1pHSTSHostCookie
3764TEST_P(URLRequestTestParameterizedSameSite,
3765 CookieNetworkSecurityMetricShortlivedHostCookie) {
3766 const bool same_site = GetParam();
3767 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3768
3769 TransportSecurityState transport_security_state;
3770 transport_security_state.AddHSTS(
3771 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3772 false /* include_subdomains */);
3773 context_.set_transport_security_state(&transport_security_state);
3774 InitContext();
3775
3776 // Set cookie.
3777 {
3778 TestDelegate d;
3779 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3780 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;Max-Age=3600"),
3781 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3782 req->Start();
Wez2a31b222018-06-07 22:07:153783 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583784 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3785 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3786 }
3787
3788 // Verify that the cookie falls into the correct metrics bucket.
3789 {
3790 TestDelegate d;
3791 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3792 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3793 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3794 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3795 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3796 req->Start();
Wez2a31b222018-06-07 22:07:153797 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583798 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3799 // Static cast of boolean required for MSVC 1911.
3800 histograms_.ExpectBucketCount(
3801 "Cookie.NetworkSecurity",
3802 static_cast<int>(CookieNetworkSecurity::k1pHSTSHostCookie) |
3803 static_cast<int>(!same_site),
3804 1);
3805 }
3806}
3807
3808// Long-lived (either due to expiry or due to being a session cookie) host
3809// cookies --> k1pExpiringHSTSHostCookie
3810TEST_P(URLRequestTestParameterizedSameSite,
3811 CookieNetworkSecurityMetricLonglivedHostCookie) {
3812 const bool same_site = GetParam();
3813 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3814
3815 TransportSecurityState transport_security_state;
3816 transport_security_state.AddHSTS(
3817 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3818 false /* include_subdomains */);
3819 context_.set_transport_security_state(&transport_security_state);
3820 InitContext();
3821
3822 // Set cookies.
3823 {
3824 TestDelegate d;
3825 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3826 https_server_.GetURL(kHost_,
3827 "/set-cookie?session-cookie=value&"
3828 "longlived-cookie=value;Max-Age=360000"),
3829 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3830 req->Start();
Wez2a31b222018-06-07 22:07:153831 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583832 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3833 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3834 }
3835
3836 // Verify that the cookies fall into the correct metrics bucket.
3837 {
3838 TestDelegate d;
3839 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3840 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3841 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3842 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3843 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3844 req->Start();
Wez2a31b222018-06-07 22:07:153845 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583846 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3847 // Static cast of boolean required for MSVC 1911.
3848 histograms_.ExpectBucketCount(
3849 "Cookie.NetworkSecurity",
3850 static_cast<int>(CookieNetworkSecurity::k1pExpiringHSTSHostCookie) |
3851 static_cast<int>(!same_site),
3852 2);
3853 }
3854}
3855
3856// Domain cookie with HSTS subdomains with cookie expiry before HSTS expiry -->
3857// k1pHSTSSubdomainsIncluded
3858TEST_P(URLRequestTestParameterizedSameSite,
3859 CookieNetworkSecurityMetricShortlivedDomainCookie) {
3860 const bool same_site = GetParam();
3861 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3862
3863 TransportSecurityState transport_security_state;
3864 transport_security_state.AddHSTS(
3865 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3866 true /* include_subdomains */);
3867 context_.set_transport_security_state(&transport_security_state);
3868 InitContext();
3869
3870 // Set cookie.
3871 {
3872 TestDelegate d;
3873 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3874 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3875 kHost_ + ";Max-Age=3600"),
3876 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3877 req->Start();
Wez2a31b222018-06-07 22:07:153878 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583879 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3880 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3881 }
3882
3883 // Verify that the cookie falls into the correct metrics bucket.
3884 {
3885 TestDelegate d;
3886 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3887 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3888 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3889 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3890 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3891 req->Start();
Wez2a31b222018-06-07 22:07:153892 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583893 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3894 // Static cast of boolean required for MSVC 1911.
3895 histograms_.ExpectBucketCount(
3896 "Cookie.NetworkSecurity",
3897 static_cast<int>(CookieNetworkSecurity::k1pHSTSSubdomainsIncluded) |
3898 static_cast<int>(!same_site),
3899 1);
3900 }
3901}
3902
3903// Long-lived (either due to expiry or due to being a session cookie) domain
3904// cookies with HSTS subdomains --> k1pExpiringHSTSSubdomainsIncluded
3905TEST_P(URLRequestTestParameterizedSameSite,
3906 CookieNetworkSecurityMetricLonglivedDomainCookie) {
3907 const bool same_site = GetParam();
3908 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3909
3910 TransportSecurityState transport_security_state;
3911 transport_security_state.AddHSTS(
3912 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3913 true /* include_subdomains */);
3914 context_.set_transport_security_state(&transport_security_state);
3915 InitContext();
3916
3917 // Set cookies.
3918 {
3919 TestDelegate d;
3920 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3921 https_server_.GetURL(
3922 kHost_, "/set-cookie?session-cookie=value;domain=" + kHost_ + "&" +
3923 "longlived-cookie=value;domain=" + kHost_ +
3924 ";Max-Age=360000"),
3925 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3926 req->Start();
Wez2a31b222018-06-07 22:07:153927 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583928 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3929 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3930 }
3931
3932 // Verify that the cookies fall into the correct metrics bucket.
3933 {
3934 TestDelegate d;
3935 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3936 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3937 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3938 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3939 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3940 req->Start();
Wez2a31b222018-06-07 22:07:153941 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583942 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3943 // Static cast of boolean required for MSVC 1911.
3944 histograms_.ExpectBucketCount(
3945 "Cookie.NetworkSecurity",
3946 static_cast<int>(
3947 CookieNetworkSecurity::k1pExpiringHSTSSubdomainsIncluded) |
3948 static_cast<int>(!same_site),
3949 2);
3950 }
3951}
3952
3953// Domain cookie with HSTS subdomains not included --> k1pHSTSSpoofable
3954TEST_P(URLRequestTestParameterizedSameSite,
3955 CookieNetworkSecurityMetricSpoofableDomainCookie) {
3956 const bool same_site = GetParam();
3957 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3958
3959 TransportSecurityState transport_security_state;
3960 transport_security_state.AddHSTS(
3961 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3962 false /* include_subdomains */);
3963 context_.set_transport_security_state(&transport_security_state);
3964 InitContext();
3965
3966 // Set cookie.
3967 {
3968 TestDelegate d;
3969 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3970 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3971 kHost_ + ";Max-Age=3600"),
3972 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3973 req->Start();
Wez2a31b222018-06-07 22:07:153974 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583975 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3976 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3977 }
3978
3979 // Verify that the cookie falls into the correct metrics bucket.
3980 {
3981 TestDelegate d;
3982 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3983 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3984 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3985 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3986 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3987 req->Start();
Wez2a31b222018-06-07 22:07:153988 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583989 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3990 // Static cast of boolean required for MSVC 1911.
3991 histograms_.ExpectBucketCount(
3992 "Cookie.NetworkSecurity",
3993 static_cast<int>(CookieNetworkSecurity::k1pHSTSSpoofable) |
3994 static_cast<int>(!same_site),
3995 1);
3996 }
3997}
3998
3999// Cookie without HSTS --> k1p(Non)SecureConnection
4000TEST_P(URLRequestTestParameterizedSameSite, CookieNetworkSecurityMetricNoHSTS) {
4001 const bool same_site = GetParam();
4002 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
4003 InitContext();
4004
4005 EmbeddedTestServer http_server;
4006 http_server.AddDefaultHandlers(
4007 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
4008 ASSERT_TRUE(http_server.Start());
4009
4010 // Set cookies.
4011 {
4012 TestDelegate d;
4013 std::unique_ptr<URLRequest> req(context_.CreateRequest(
4014 https_server_.GetURL(kHost_,
4015 "/set-cookie?cookie=value;domain=" + kHost_ +
4016 ";Max-Age=3600&host-cookie=value"),
4017 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4018 req->Start();
Wez2a31b222018-06-07 22:07:154019 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:584020 ASSERT_EQ(2, network_delegate_.set_cookie_count());
4021 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
4022 }
4023
4024 // Verify that the cookie falls into the correct metrics bucket.
4025 {
4026 TestDelegate d;
4027 std::unique_ptr<URLRequest> req(context_.CreateRequest(
4028 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
4029 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4030 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
4031 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
4032 req->Start();
Wez2a31b222018-06-07 22:07:154033 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:584034 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
4035 // Static cast of boolean required for MSVC 1911.
4036 histograms_.ExpectBucketCount(
4037 "Cookie.NetworkSecurity",
4038 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
4039 static_cast<int>(!same_site),
4040 2);
4041 }
4042
4043 // Verify that the cookie falls into the correct metrics bucket.
4044 {
4045 TestDelegate d;
4046 std::unique_ptr<URLRequest> req(context_.CreateRequest(
4047 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4048 TRAFFIC_ANNOTATION_FOR_TESTS));
4049 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
4050 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
4051 req->Start();
Wez2a31b222018-06-07 22:07:154052 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:584053 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 4);
4054 // Static cast of boolean required for MSVC 1911.
4055 histograms_.ExpectBucketCount(
4056 "Cookie.NetworkSecurity",
4057 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
4058 static_cast<int>(!same_site),
4059 2);
4060 // Static cast of boolean required for MSVC 1911.
4061 histograms_.ExpectBucketCount(
4062 "Cookie.NetworkSecurity",
4063 static_cast<int>(CookieNetworkSecurity::k1pNonsecureConnection) |
4064 static_cast<int>(!same_site),
4065 2);
Mike West86149882017-07-28 10:41:494066 }
4067}
4068
[email protected]5095cd72012-11-01 10:29:164069// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
4070// value for the |fixed_date| argument given to the constructor.
4071class FixedDateNetworkDelegate : public TestNetworkDelegate {
4072 public:
4073 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
4074 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:274075 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:164076
[email protected]cba24642014-08-15 20:49:594077 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:204078 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:594079 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:204080 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:594081 const HttpResponseHeaders* original_response_headers,
4082 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134083 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:164084
4085 private:
4086 std::string fixed_date_;
4087
4088 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
4089};
4090
4091int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:594092 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:204093 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:594094 const HttpResponseHeaders* original_response_headers,
4095 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:164096 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:594097 HttpResponseHeaders* new_response_headers =
4098 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:164099
4100 new_response_headers->RemoveHeader("Date");
4101 new_response_headers->AddHeader("Date: " + fixed_date_);
4102
4103 *override_response_headers = new_response_headers;
David Benjamind1f287bf2018-06-12 01:57:204104 return TestNetworkDelegate::OnHeadersReceived(
4105 request, std::move(callback), original_response_headers,
4106 override_response_headers, allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:164107}
4108
4109// Test that cookie expiration times are adjusted for server/client clock
4110// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
4111// headers by defaulting to GMT. (crbug.com/135131)
4112TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:394113 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:164114 ASSERT_TRUE(test_server.Start());
4115
4116 // Set up an expired cookie.
4117 {
4118 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074119 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164120 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074121 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194122 test_server.GetURL(
tommycli59a63432015-11-06 00:10:554123 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:164124 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194125 req->Start();
Wez2a31b222018-06-07 22:07:154126 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164127 }
4128 // Verify that the cookie is not set.
4129 {
4130 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074131 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164132 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074133 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164134 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4135 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194136 req->Start();
Wez2a31b222018-06-07 22:07:154137 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164138
4139 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
4140 }
4141 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
4142 {
4143 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
Ryan Sleevib8449e02018-07-15 04:31:074144 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164145 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074146 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194147 test_server.GetURL(
tommycli59a63432015-11-06 00:10:554148 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:164149 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194150 req->Start();
Wez2a31b222018-06-07 22:07:154151 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164152 }
4153 // Verify that the cookie is set.
4154 {
4155 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074156 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164157 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074158 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164159 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4160 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194161 req->Start();
Wez2a31b222018-06-07 22:07:154162 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164163
4164 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
4165 }
4166}
4167
4168
[email protected]316c1e5e2012-09-12 15:17:444169// Check that it is impossible to change the referrer in the extra headers of
4170// an URLRequest.
4171TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:394172 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:444173 ASSERT_TRUE(test_server.Start());
4174
4175 // If extra headers contain referer and the request contains a referer,
4176 // only the latter shall be respected.
4177 {
4178 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074179 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164180 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4181 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194182 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:444183
4184 HttpRequestHeaders headers;
4185 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194186 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:444187
[email protected]f7022f32014-08-21 16:32:194188 req->Start();
Wez2a31b222018-06-07 22:07:154189 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444190
4191 EXPECT_EQ("http://foo.com/", d.data_received());
4192 }
4193
4194 // If extra headers contain a referer but the request does not, no referer
4195 // shall be sent in the header.
4196 {
4197 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074198 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164199 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4200 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:444201
4202 HttpRequestHeaders headers;
4203 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194204 req->SetExtraRequestHeaders(headers);
4205 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:444206
[email protected]f7022f32014-08-21 16:32:194207 req->Start();
Wez2a31b222018-06-07 22:07:154208 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444209
4210 EXPECT_EQ("None", d.data_received());
4211 }
4212}
4213
[email protected]b89290212009-08-14 22:37:354214class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:114215 public:
mmenke9f2ec60c2015-06-01 20:59:474216 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:114217
[email protected]b89290212009-08-14 22:37:354218 protected:
[email protected]21184962011-10-26 00:50:304219 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
4220 // |request_method| is the method to use for the initial request.
4221 // |redirect_method| is the method that is expected to be used for the second
4222 // request, after redirection.
4223 // If |include_data| is true, data is uploaded with the request. The
4224 // response body is expected to match it exactly, if and only if
4225 // |request_method| == |redirect_method|.
4226 void HTTPRedirectMethodTest(const GURL& redirect_url,
4227 const std::string& request_method,
4228 const std::string& redirect_method,
4229 bool include_data) {
4230 static const char kData[] = "hello world";
4231 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074232 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164233 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194234 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:304235 if (include_data) {
mmenkecbc2b712014-10-09 20:29:074236 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:304237 HttpRequestHeaders headers;
4238 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244239 base::NumberToString(base::size(kData) - 1));
svaldez5b3a8972015-10-09 23:23:544240 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:194241 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:304242 }
[email protected]f7022f32014-08-21 16:32:194243 req->Start();
Wez2a31b222018-06-07 22:07:154244 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194245 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:504246 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:304247 if (include_data) {
4248 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:544249 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4250 HttpRequestHeaders::kContentLength));
4251 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4252 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304253 EXPECT_EQ(kData, d.data_received());
4254 } else {
svaldez5b3a8972015-10-09 23:23:544255 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4256 HttpRequestHeaders::kContentLength));
4257 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4258 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304259 EXPECT_NE(kData, d.data_received());
4260 }
4261 }
4262 if (HasFailure())
4263 LOG(WARNING) << "Request method was: " << request_method;
4264 }
4265
Alex Clarke1e08882b32017-10-06 14:22:404266 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
4267 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:514268 // |request_method| is the method to use for the initial request.
4269 // |redirect_method| is the method that is expected to be used for the second
4270 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:404271 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:514272 // redirection. If empty, expects that there will be no Origin header.
4273 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
4274 const std::string& request_method,
4275 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:404276 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:514277 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074278 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164279 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:514280 req->set_method(request_method);
4281 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
4282 redirect_url.GetOrigin().spec(), false);
4283 req->Start();
4284
Wez2a31b222018-06-07 22:07:154285 d.RunUntilComplete();
jww5fe460ff2015-03-28 00:22:514286
4287 EXPECT_EQ(redirect_method, req->method());
4288 // Note that there is no check for request success here because, for
4289 // purposes of testing, the request very well may fail. For example, if the
4290 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
4291 // origin, there is not an HTTPS server in this unit test framework, so the
4292 // request would fail. However, that's fine, as long as the request headers
4293 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:404294 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:514295 EXPECT_FALSE(
4296 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
4297 } else {
4298 std::string origin_header;
4299 EXPECT_TRUE(req->extra_request_headers().GetHeader(
4300 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:404301 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:514302 }
4303 }
4304
[email protected]762d2db2010-01-11 19:03:014305 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:014306 const int kMsgSize = 20000; // multiple of 10
4307 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:484308 char* uploadBytes = new char[kMsgSize+1];
4309 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:014310 char marker = 'a';
4311 for (int idx = 0; idx < kMsgSize/10; idx++) {
4312 memcpy(ptr, "----------", 10);
4313 ptr += 10;
4314 if (idx % 100 == 0) {
4315 ptr--;
4316 *ptr++ = marker;
4317 if (++marker > 'z')
4318 marker = 'a';
4319 }
4320 }
4321 uploadBytes[kMsgSize] = '\0';
4322
[email protected]762d2db2010-01-11 19:03:014323 for (int i = 0; i < kIterations; ++i) {
4324 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074325 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164326 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
4327 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194328 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:014329
mmenkecbc2b712014-10-09 20:29:074330 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:014331
[email protected]f7022f32014-08-21 16:32:194332 r->Start();
4333 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:014334
Wez2a31b222018-06-07 22:07:154335 d.RunUntilComplete();
[email protected]762d2db2010-01-11 19:03:014336
maksim.sisovb53724b52016-09-16 05:30:504337 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
4338 << d.request_status();
[email protected]762d2db2010-01-11 19:03:014339
4340 EXPECT_FALSE(d.received_data_before_response());
4341 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:014342 }
4343 delete[] uploadBytes;
4344 }
4345
[email protected]ede03212012-09-07 12:52:264346 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:344347 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074348 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:554349 test_server_.GetURL("/set-many-cookies?" +
Raul Tambre8c1981d2019-02-08 02:22:264350 base::NumberToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:164351 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:344352
[email protected]f7022f32014-08-21 16:32:194353 r->Start();
4354 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:344355
Wez2a31b222018-06-07 22:07:154356 d.RunUntilComplete();
[email protected]263163f2012-06-14 22:40:344357
maksim.sisovb53724b52016-09-16 05:30:504358 if (d.request_status() != OK) {
4359 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
4360 return false;
4361 }
[email protected]263163f2012-06-14 22:40:344362
maksim.sisovb53724b52016-09-16 05:30:504363 return true;
[email protected]263163f2012-06-14 22:40:344364 }
4365
David Benjamin42116f62017-11-20 21:45:394366 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:504367
tommycli59a63432015-11-06 00:10:554368 private:
David Benjamin42116f62017-11-20 21:45:394369 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:354370};
4371
tommycli59a63432015-11-06 00:10:554372namespace {
4373
danakj8522a25b2016-04-16 00:17:364374std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:554375 const test_server::HttpRequest& request) {
4376 if (request.headers.find("Host") == request.headers.end() ||
4377 request.headers.at("Host") != "www.redirect.com" ||
4378 request.method != test_server::METHOD_CONNECT) {
4379 return nullptr;
4380 }
4381
danakj8522a25b2016-04-16 00:17:364382 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554383 new test_server::BasicHttpResponse);
4384 http_response->set_code(HTTP_FOUND);
4385 http_response->AddCustomHeader("Location",
4386 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:484387 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554388}
4389
Nick Harper89bc7212018-07-31 19:07:574390} // namespace
4391
nharperb7441ef2016-01-25 23:54:144392// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114393// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:554394// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:114395// follow.
[email protected]f2f31b32013-01-16 23:24:094396TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:554397 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124398 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:554399 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114400
[email protected]ceefd7fd2012-11-29 00:36:244401 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044402 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554403 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504404
[email protected]d1ec59082009-02-11 02:48:154405 TestDelegate d;
4406 {
danakj8522a25b2016-04-16 00:17:364407 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164408 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4409 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194410 r->Start();
4411 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:154412
Wez2a31b222018-06-07 22:07:154413 d.RunUntilComplete();
[email protected]d1ec59082009-02-11 02:48:154414
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:224415 // The proxy server should be set before failure.
4416 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4417 http_test_server()->host_port_pair()),
4418 r->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:504419 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084420 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:154421 // We should not have followed the redirect.
4422 EXPECT_EQ(0, d.received_redirect_count());
4423 }
4424}
4425
[email protected]8202d0c2011-02-23 08:31:144426// This is the same as the previous test, but checks that the network delegate
4427// registers the error.
[email protected]c044616e2013-02-20 02:01:264428TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554429 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144430
[email protected]ceefd7fd2012-11-29 00:36:244431 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044432 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554433 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504434
[email protected]8202d0c2011-02-23 08:31:144435 TestDelegate d;
4436 {
danakj8522a25b2016-04-16 00:17:364437 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164438 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4439 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194440 r->Start();
4441 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144442
Wez2a31b222018-06-07 22:07:154443 d.RunUntilComplete();
[email protected]8202d0c2011-02-23 08:31:144444
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:224445 // The proxy server should be set before failure.
4446 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4447 http_test_server()->host_port_pair()),
4448 r->proxy_server());
[email protected]8202d0c2011-02-23 08:31:144449 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504450 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144451 // We should not have followed the redirect.
4452 EXPECT_EQ(0, d.received_redirect_count());
4453
4454 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014455 EXPECT_THAT(network_delegate.last_error(),
4456 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144457 }
4458}
4459
[email protected]dc5a5cf2012-09-26 02:49:304460// Tests that we can block and asynchronously return OK in various stages.
4461TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4462 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4463 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4464 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4465 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4466 };
Avi Drissman4365a4782018-12-28 19:26:244467 static const size_t blocking_stages_length = base::size(blocking_stages);
[email protected]dc5a5cf2012-09-26 02:49:304468
tommycli59a63432015-11-06 00:10:554469 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304470
4471 TestDelegate d;
4472 BlockingNetworkDelegate network_delegate(
4473 BlockingNetworkDelegate::USER_CALLBACK);
4474 network_delegate.set_block_on(
4475 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4476 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4477 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4478
4479 TestURLRequestContext context(true);
4480 context.set_network_delegate(&network_delegate);
4481 context.Init();
4482
4483 {
danakj8522a25b2016-04-16 00:17:364484 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164485 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4486 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304487
[email protected]f7022f32014-08-21 16:32:194488 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304489 for (size_t i = 0; i < blocking_stages_length; ++i) {
Wez2a31b222018-06-07 22:07:154490 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304491 EXPECT_EQ(blocking_stages[i],
4492 network_delegate.stage_blocked_for_callback());
4493 network_delegate.DoCallback(OK);
4494 }
Wez2a31b222018-06-07 22:07:154495 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194496 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504497 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304498 EXPECT_EQ(1, network_delegate.created_requests());
4499 EXPECT_EQ(0, network_delegate.destroyed_requests());
4500 }
4501 EXPECT_EQ(1, network_delegate.destroyed_requests());
4502}
4503
[email protected]4c76d7c2011-04-15 19:14:124504// Tests that the network delegate can block and cancel a request.
4505TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554506 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124507
4508 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304509 BlockingNetworkDelegate network_delegate(
4510 BlockingNetworkDelegate::AUTO_CALLBACK);
4511 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4512 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124513
[email protected]d5a4dd62012-05-23 01:41:044514 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554515 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504516
[email protected]4c76d7c2011-04-15 19:14:124517 {
rhalavatib7bd7c792017-04-27 05:25:164518 std::unique_ptr<URLRequest> r(
4519 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4520 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124521
[email protected]f7022f32014-08-21 16:32:194522 r->Start();
Wez2a31b222018-06-07 22:07:154523 d.RunUntilComplete();
[email protected]4c76d7c2011-04-15 19:14:124524
[email protected]d8fc4722014-06-13 13:17:154525 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474526 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504527 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124528 EXPECT_EQ(1, network_delegate.created_requests());
4529 EXPECT_EQ(0, network_delegate.destroyed_requests());
4530 }
4531 EXPECT_EQ(1, network_delegate.destroyed_requests());
4532}
4533
[email protected]b4438d32012-09-27 06:15:304534// Helper function for NetworkDelegateCancelRequestAsynchronously and
4535// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4536// delegate operating in |block_mode| and a request for |url|. It blocks the
4537// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4538void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4539 BlockingNetworkDelegate::Stage stage,
4540 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364541 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304542 BlockingNetworkDelegate network_delegate(block_mode);
4543 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4544 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364545
[email protected]b4438d32012-09-27 06:15:304546 TestURLRequestContext context(true);
4547 context.set_network_delegate(&network_delegate);
4548 context.Init();
[email protected]3cd384c602011-08-31 16:12:364549
4550 {
rhalavatib7bd7c792017-04-27 05:25:164551 std::unique_ptr<URLRequest> r(context.CreateRequest(
4552 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364553
[email protected]f7022f32014-08-21 16:32:194554 r->Start();
Wez2a31b222018-06-07 22:07:154555 d.RunUntilComplete();
[email protected]3cd384c602011-08-31 16:12:364556
[email protected]d8fc4722014-06-13 13:17:154557 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474558 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4559 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4560 EXPECT_FALSE(r->proxy_server().is_valid());
4561 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4562 EXPECT_TRUE(r->proxy_server().is_direct());
4563 } else {
4564 NOTREACHED();
4565 }
maksim.sisovb53724b52016-09-16 05:30:504566 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364567 EXPECT_EQ(1, network_delegate.created_requests());
4568 EXPECT_EQ(0, network_delegate.destroyed_requests());
4569 }
4570 EXPECT_EQ(1, network_delegate.destroyed_requests());
4571}
4572
[email protected]b4438d32012-09-27 06:15:304573// The following 3 tests check that the network delegate can cancel a request
4574// synchronously in various stages of the request.
4575TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554576 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304577 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4578 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554579 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304580}
4581
4582TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554583 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304584 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4585 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554586 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304587}
4588
4589TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554590 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304591 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4592 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554593 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304594}
4595
4596// The following 3 tests check that the network delegate can cancel a request
4597// asynchronously in various stages of the request.
4598TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554599 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304600 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4601 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554602 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304603}
4604
4605TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554606 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304607 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4608 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554609 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304610}
4611
4612TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554613 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304614 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4615 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554616 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304617}
4618
[email protected]4c76d7c2011-04-15 19:14:124619// Tests that the network delegate can block and redirect a request to a new
4620// URL.
4621TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554622 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124623
4624 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304625 BlockingNetworkDelegate network_delegate(
4626 BlockingNetworkDelegate::AUTO_CALLBACK);
4627 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
Eric Romanda790f92018-11-07 19:17:154628 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]4c76d7c2011-04-15 19:14:124629 network_delegate.set_redirect_url(redirect_url);
4630
[email protected]d5a4dd62012-05-23 01:41:044631 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554632 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504633
[email protected]4c76d7c2011-04-15 19:14:124634 {
Eric Romanda790f92018-11-07 19:17:154635 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164636 std::unique_ptr<URLRequest> r(context.CreateRequest(
4637 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124638
[email protected]6be6fa92014-08-06 23:44:564639 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194640 r->Start();
Wez0e717112018-06-18 23:09:224641 d.RunUntilRedirect();
[email protected]4c76d7c2011-04-15 19:14:124642
[email protected]6be6fa92014-08-06 23:44:564643 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194644 EXPECT_EQ(307, r->GetResponseCode());
4645 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564646 std::string location;
Raul Tambre94493c652019-03-11 17:18:354647 ASSERT_TRUE(
4648 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564649 EXPECT_EQ(redirect_url, GURL(location));
4650
4651 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354652 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4653 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154654 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:504655 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474656 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4657 http_test_server()->host_port_pair()),
4658 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094659 // before_send_headers_with_proxy_count only increments for headers sent
4660 // through an untunneled proxy.
4661 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554662 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4663 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274664
maksim.sisovb53724b52016-09-16 05:30:504665 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194666 EXPECT_EQ(redirect_url, r->url());
4667 EXPECT_EQ(original_url, r->original_url());
4668 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124669 EXPECT_EQ(1, network_delegate.created_requests());
4670 EXPECT_EQ(0, network_delegate.destroyed_requests());
4671 }
4672 EXPECT_EQ(1, network_delegate.destroyed_requests());
4673}
4674
[email protected]b813ed72012-04-05 08:21:364675// Tests that the network delegate can block and redirect a request to a new
4676// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4677TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554678 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364679
4680 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304681 BlockingNetworkDelegate network_delegate(
4682 BlockingNetworkDelegate::SYNCHRONOUS);
Eric Romanda790f92018-11-07 19:17:154683 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]b813ed72012-04-05 08:21:364684 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364685
[email protected]d5a4dd62012-05-23 01:41:044686 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554687 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364688
4689 {
Eric Romanda790f92018-11-07 19:17:154690 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164691 std::unique_ptr<URLRequest> r(context.CreateRequest(
4692 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364693
[email protected]6be6fa92014-08-06 23:44:564694 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194695 r->Start();
Wez0e717112018-06-18 23:09:224696 d.RunUntilRedirect();
[email protected]b813ed72012-04-05 08:21:364697
[email protected]6be6fa92014-08-06 23:44:564698 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194699 EXPECT_EQ(307, r->GetResponseCode());
4700 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564701 std::string location;
Raul Tambre94493c652019-03-11 17:18:354702 ASSERT_TRUE(
4703 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564704 EXPECT_EQ(redirect_url, GURL(location));
4705
4706 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354707 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4708 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154709 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564710
maksim.sisovb53724b52016-09-16 05:30:504711 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474712 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4713 http_test_server()->host_port_pair()),
4714 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094715 // before_send_headers_with_proxy_count only increments for headers sent
4716 // through an untunneled proxy.
4717 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554718 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4719 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504720 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194721 EXPECT_EQ(redirect_url, r->url());
4722 EXPECT_EQ(original_url, r->original_url());
4723 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364724 EXPECT_EQ(1, network_delegate.created_requests());
4725 EXPECT_EQ(0, network_delegate.destroyed_requests());
4726 }
4727 EXPECT_EQ(1, network_delegate.destroyed_requests());
4728}
4729
[email protected]3c5ca8c2011-09-29 01:14:514730// Tests that redirects caused by the network delegate preserve POST data.
4731TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554732 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514733
4734 const char kData[] = "hello world";
4735
4736 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304737 BlockingNetworkDelegate network_delegate(
4738 BlockingNetworkDelegate::AUTO_CALLBACK);
4739 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554740 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514741 network_delegate.set_redirect_url(redirect_url);
4742
[email protected]ef2bf422012-05-11 03:27:094743 TestURLRequestContext context(true);
4744 context.set_network_delegate(&network_delegate);
4745 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514746
4747 {
tommycli59a63432015-11-06 00:10:554748 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164749 std::unique_ptr<URLRequest> r(context.CreateRequest(
4750 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194751 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074752 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514753 HttpRequestHeaders headers;
4754 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244755 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194756 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564757
4758 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194759 r->Start();
Wez0e717112018-06-18 23:09:224760 d.RunUntilRedirect();
[email protected]3c5ca8c2011-09-29 01:14:514761
[email protected]6be6fa92014-08-06 23:44:564762 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194763 EXPECT_EQ(307, r->GetResponseCode());
4764 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564765 std::string location;
Raul Tambre94493c652019-03-11 17:18:354766 ASSERT_TRUE(
4767 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564768 EXPECT_EQ(redirect_url, GURL(location));
4769
4770 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354771 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4772 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154773 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564774
maksim.sisovb53724b52016-09-16 05:30:504775 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194776 EXPECT_EQ(redirect_url, r->url());
4777 EXPECT_EQ(original_url, r->original_url());
4778 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514779 EXPECT_EQ(1, network_delegate.created_requests());
4780 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194781 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514782 EXPECT_EQ(kData, d.data_received());
4783 }
4784 EXPECT_EQ(1, network_delegate.destroyed_requests());
4785}
4786
[email protected]5f714132014-03-26 10:41:164787// Tests that the network delegate can block and redirect a request to a new
4788// URL during OnHeadersReceived.
4789TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554790 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164791
4792 TestDelegate d;
4793 BlockingNetworkDelegate network_delegate(
4794 BlockingNetworkDelegate::AUTO_CALLBACK);
4795 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
Eric Romanda790f92018-11-07 19:17:154796 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]5f714132014-03-26 10:41:164797 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4798
4799 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554800 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164801
4802 {
Eric Romanda790f92018-11-07 19:17:154803 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164804 std::unique_ptr<URLRequest> r(context.CreateRequest(
4805 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164806
[email protected]f7022f32014-08-21 16:32:194807 r->Start();
Wez2a31b222018-06-07 22:07:154808 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:164809
maksim.sisovb53724b52016-09-16 05:30:504810 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474811 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4812 http_test_server()->host_port_pair()),
4813 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094814 // before_send_headers_with_proxy_count only increments for headers sent
4815 // through an untunneled proxy.
4816 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554817 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4818 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194819
maksim.sisovb53724b52016-09-16 05:30:504820 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194821 EXPECT_EQ(redirect_url, r->url());
4822 EXPECT_EQ(original_url, r->original_url());
4823 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164824 EXPECT_EQ(2, network_delegate.created_requests());
4825 EXPECT_EQ(0, network_delegate.destroyed_requests());
4826 }
4827 EXPECT_EQ(1, network_delegate.destroyed_requests());
4828}
4829
[email protected]c2911d72011-10-03 22:16:364830// Tests that the network delegate can synchronously complete OnAuthRequired
4831// by taking no action. This indicates that the NetworkDelegate does not want to
4832// handle the challenge, and is passing the buck along to the
4833// URLRequest::Delegate.
4834TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554835 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364836
4837 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304838 BlockingNetworkDelegate network_delegate(
4839 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364840
[email protected]ef2bf422012-05-11 03:27:094841 TestURLRequestContext context(true);
4842 context.set_network_delegate(&network_delegate);
4843 context.Init();
[email protected]c2911d72011-10-03 22:16:364844
[email protected]f3cf9802011-10-28 18:44:584845 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364846
4847 {
tommycli59a63432015-11-06 00:10:554848 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164849 std::unique_ptr<URLRequest> r(context.CreateRequest(
4850 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194851 r->Start();
[email protected]79e1fd62013-06-20 06:50:044852
Wez2a31b222018-06-07 22:07:154853 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044854
maksim.sisovb53724b52016-09-16 05:30:504855 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194856 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044857 EXPECT_TRUE(d.auth_required_called());
4858 EXPECT_EQ(1, network_delegate.created_requests());
4859 EXPECT_EQ(0, network_delegate.destroyed_requests());
4860 }
4861 EXPECT_EQ(1, network_delegate.destroyed_requests());
4862}
4863
4864TEST_F(URLRequestTestHTTP,
4865 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554866 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044867
4868 TestDelegate d;
4869 BlockingNetworkDelegate network_delegate(
4870 BlockingNetworkDelegate::SYNCHRONOUS);
4871
4872 TestURLRequestContext context(true);
4873 context.set_network_delegate(&network_delegate);
4874 context.Init();
4875
4876 d.set_credentials(AuthCredentials(kUser, kSecret));
4877
4878 {
tommycli59a63432015-11-06 00:10:554879 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164880 std::unique_ptr<URLRequest> r(context.CreateRequest(
4881 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194882 r->Start();
[email protected]79e1fd62013-06-20 06:50:044883
Wez2a31b222018-06-07 22:07:154884 d.RunUntilComplete();
shivanisha8061c4202017-06-13 23:35:524885
[email protected]79e1fd62013-06-20 06:50:044886 {
4887 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194888 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524889 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044890 }
4891
maksim.sisovb53724b52016-09-16 05:30:504892 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194893 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364894 EXPECT_TRUE(d.auth_required_called());
4895 EXPECT_EQ(1, network_delegate.created_requests());
4896 EXPECT_EQ(0, network_delegate.destroyed_requests());
4897 }
4898 EXPECT_EQ(1, network_delegate.destroyed_requests());
4899}
4900
4901// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404902// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364903TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554904 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364905
4906 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304907 BlockingNetworkDelegate network_delegate(
4908 BlockingNetworkDelegate::SYNCHRONOUS);
4909 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364910 network_delegate.set_auth_retval(
4911 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4912
[email protected]f3cf9802011-10-28 18:44:584913 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364914
[email protected]ef2bf422012-05-11 03:27:094915 TestURLRequestContext context(true);
4916 context.set_network_delegate(&network_delegate);
4917 context.Init();
[email protected]c2911d72011-10-03 22:16:364918
4919 {
tommycli59a63432015-11-06 00:10:554920 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164921 std::unique_ptr<URLRequest> r(context.CreateRequest(
4922 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194923 r->Start();
Wez2a31b222018-06-07 22:07:154924 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364925
maksim.sisovb53724b52016-09-16 05:30:504926 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194927 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364928 EXPECT_FALSE(d.auth_required_called());
4929 EXPECT_EQ(1, network_delegate.created_requests());
4930 EXPECT_EQ(0, network_delegate.destroyed_requests());
4931 }
4932 EXPECT_EQ(1, network_delegate.destroyed_requests());
4933}
4934
[email protected]79e1fd62013-06-20 06:50:044935// Same as above, but also tests that GetFullRequestHeaders returns the proper
4936// headers (for the first or second request) when called at the proper times.
4937TEST_F(URLRequestTestHTTP,
4938 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554939 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044940
4941 TestDelegate d;
4942 BlockingNetworkDelegate network_delegate(
4943 BlockingNetworkDelegate::SYNCHRONOUS);
4944 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4945 network_delegate.set_auth_retval(
4946 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4947
4948 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4949
4950 TestURLRequestContext context(true);
4951 context.set_network_delegate(&network_delegate);
4952 context.Init();
4953
4954 {
tommycli59a63432015-11-06 00:10:554955 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164956 std::unique_ptr<URLRequest> r(context.CreateRequest(
4957 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194958 r->Start();
Wez2a31b222018-06-07 22:07:154959 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044960
maksim.sisovb53724b52016-09-16 05:30:504961 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194962 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044963 EXPECT_FALSE(d.auth_required_called());
4964 EXPECT_EQ(1, network_delegate.created_requests());
4965 EXPECT_EQ(0, network_delegate.destroyed_requests());
4966
4967 {
4968 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194969 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044970 EXPECT_TRUE(headers.HasHeader("Authorization"));
4971 }
4972 }
4973 EXPECT_EQ(1, network_delegate.destroyed_requests());
4974}
4975
[email protected]c2911d72011-10-03 22:16:364976// Tests that the network delegate can synchronously complete OnAuthRequired
4977// by cancelling authentication.
4978TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554979 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364980
4981 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304982 BlockingNetworkDelegate network_delegate(
4983 BlockingNetworkDelegate::SYNCHRONOUS);
4984 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364985 network_delegate.set_auth_retval(
4986 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4987
[email protected]ef2bf422012-05-11 03:27:094988 TestURLRequestContext context(true);
4989 context.set_network_delegate(&network_delegate);
4990 context.Init();
[email protected]c2911d72011-10-03 22:16:364991
4992 {
tommycli59a63432015-11-06 00:10:554993 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164994 std::unique_ptr<URLRequest> r(context.CreateRequest(
4995 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194996 r->Start();
Wez2a31b222018-06-07 22:07:154997 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364998
maksim.sisovb53724b52016-09-16 05:30:504999 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195000 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365001 EXPECT_FALSE(d.auth_required_called());
5002 EXPECT_EQ(1, network_delegate.created_requests());
5003 EXPECT_EQ(0, network_delegate.destroyed_requests());
5004 }
5005 EXPECT_EQ(1, network_delegate.destroyed_requests());
5006}
5007
5008// Tests that the network delegate can asynchronously complete OnAuthRequired
5009// by taking no action. This indicates that the NetworkDelegate does not want
5010// to handle the challenge, and is passing the buck along to the
5011// URLRequest::Delegate.
5012TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:555013 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365014
5015 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305016 BlockingNetworkDelegate network_delegate(
5017 BlockingNetworkDelegate::AUTO_CALLBACK);
5018 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365019
[email protected]ef2bf422012-05-11 03:27:095020 TestURLRequestContext context(true);
5021 context.set_network_delegate(&network_delegate);
5022 context.Init();
[email protected]c2911d72011-10-03 22:16:365023
[email protected]f3cf9802011-10-28 18:44:585024 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:365025
5026 {
tommycli59a63432015-11-06 00:10:555027 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165028 std::unique_ptr<URLRequest> r(context.CreateRequest(
5029 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195030 r->Start();
Wez2a31b222018-06-07 22:07:155031 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365032
maksim.sisovb53724b52016-09-16 05:30:505033 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195034 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365035 EXPECT_TRUE(d.auth_required_called());
5036 EXPECT_EQ(1, network_delegate.created_requests());
5037 EXPECT_EQ(0, network_delegate.destroyed_requests());
5038 }
5039 EXPECT_EQ(1, network_delegate.destroyed_requests());
5040}
5041
5042// Tests that the network delegate can asynchronously complete OnAuthRequired
5043// by setting credentials.
5044TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:555045 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365046
5047 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305048 BlockingNetworkDelegate network_delegate(
5049 BlockingNetworkDelegate::AUTO_CALLBACK);
5050 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365051 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365052 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5053
[email protected]f3cf9802011-10-28 18:44:585054 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:365055 network_delegate.set_auth_credentials(auth_credentials);
5056
[email protected]ef2bf422012-05-11 03:27:095057 TestURLRequestContext context(true);
5058 context.set_network_delegate(&network_delegate);
5059 context.Init();
[email protected]c2911d72011-10-03 22:16:365060
5061 {
tommycli59a63432015-11-06 00:10:555062 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165063 std::unique_ptr<URLRequest> r(context.CreateRequest(
5064 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195065 r->Start();
Wez2a31b222018-06-07 22:07:155066 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365067
maksim.sisovb53724b52016-09-16 05:30:505068 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195069 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365070 EXPECT_FALSE(d.auth_required_called());
5071 EXPECT_EQ(1, network_delegate.created_requests());
5072 EXPECT_EQ(0, network_delegate.destroyed_requests());
5073 }
5074 EXPECT_EQ(1, network_delegate.destroyed_requests());
5075}
5076
5077// Tests that the network delegate can asynchronously complete OnAuthRequired
5078// by cancelling authentication.
5079TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:555080 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365081
5082 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305083 BlockingNetworkDelegate network_delegate(
5084 BlockingNetworkDelegate::AUTO_CALLBACK);
5085 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365086 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365087 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
5088
[email protected]ef2bf422012-05-11 03:27:095089 TestURLRequestContext context(true);
5090 context.set_network_delegate(&network_delegate);
5091 context.Init();
[email protected]c2911d72011-10-03 22:16:365092
5093 {
tommycli59a63432015-11-06 00:10:555094 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165095 std::unique_ptr<URLRequest> r(context.CreateRequest(
5096 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195097 r->Start();
Wez2a31b222018-06-07 22:07:155098 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365099
maksim.sisovb53724b52016-09-16 05:30:505100 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195101 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365102 EXPECT_FALSE(d.auth_required_called());
5103 EXPECT_EQ(1, network_delegate.created_requests());
5104 EXPECT_EQ(0, network_delegate.destroyed_requests());
5105 }
5106 EXPECT_EQ(1, network_delegate.destroyed_requests());
5107}
5108
David Benjamin0bda12f2018-02-07 19:58:455109// Tests that NetworkDelegate header overrides from the 401 response do not
5110// affect the 200 response. This is a regression test for
5111// https://crbug.com/801237.
5112TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
5113 ASSERT_TRUE(http_test_server()->Start());
5114
5115 TestDelegate d;
5116 d.set_credentials(AuthCredentials(kUser, kSecret));
5117 default_network_delegate_.set_add_header_to_first_response(true);
5118
5119 {
5120 GURL url(http_test_server()->GetURL("/auth-basic"));
Ryan Sleevib8449e02018-07-15 04:31:075121 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455122 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5123 r->Start();
5124
Wez2a31b222018-06-07 22:07:155125 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455126
5127 EXPECT_EQ(OK, d.request_status());
5128 EXPECT_EQ(200, r->GetResponseCode());
5129 EXPECT_TRUE(d.auth_required_called());
5130 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
5131 }
5132
5133 {
5134 GURL url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075135 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455136 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5137 r->Start();
5138
Wez2a31b222018-06-07 22:07:155139 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455140
5141 // Check that set_add_header_to_first_response normally adds a header.
5142 EXPECT_EQ(OK, d.request_status());
5143 EXPECT_EQ(200, r->GetResponseCode());
5144 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
5145 }
5146}
5147
[email protected]9045b8822012-01-13 20:35:355148// Tests that we can handle when a network request was canceled while we were
5149// waiting for the network delegate.
5150// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
5151TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:555152 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355153
5154 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305155 BlockingNetworkDelegate network_delegate(
5156 BlockingNetworkDelegate::USER_CALLBACK);
5157 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:355158
[email protected]ef2bf422012-05-11 03:27:095159 TestURLRequestContext context(true);
5160 context.set_network_delegate(&network_delegate);
5161 context.Init();
[email protected]9045b8822012-01-13 20:35:355162
5163 {
rhalavatib7bd7c792017-04-27 05:25:165164 std::unique_ptr<URLRequest> r(
5165 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5166 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355167
[email protected]f7022f32014-08-21 16:32:195168 r->Start();
Wez2a31b222018-06-07 22:07:155169 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305170 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
5171 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355172 EXPECT_EQ(0, network_delegate.completed_requests());
5173 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195174 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355175 // Ensure that network delegate is notified.
5176 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505177 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355178 EXPECT_EQ(1, network_delegate.created_requests());
5179 EXPECT_EQ(0, network_delegate.destroyed_requests());
5180 }
5181 EXPECT_EQ(1, network_delegate.destroyed_requests());
5182}
5183
5184// Tests that we can handle when a network request was canceled while we were
5185// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:005186// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
5187// callback.
[email protected]9045b8822012-01-13 20:35:355188TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:555189 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355190
5191 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305192 BlockingNetworkDelegate network_delegate(
5193 BlockingNetworkDelegate::USER_CALLBACK);
5194 network_delegate.set_block_on(
5195 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:355196
[email protected]ef2bf422012-05-11 03:27:095197 TestURLRequestContext context(true);
5198 context.set_network_delegate(&network_delegate);
5199 context.Init();
[email protected]9045b8822012-01-13 20:35:355200
5201 {
rhalavatib7bd7c792017-04-27 05:25:165202 std::unique_ptr<URLRequest> r(
5203 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5204 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355205
[email protected]f7022f32014-08-21 16:32:195206 r->Start();
Wez2a31b222018-06-07 22:07:155207 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305208 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
5209 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355210 EXPECT_EQ(0, network_delegate.completed_requests());
5211 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195212 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355213 // Ensure that network delegate is notified.
5214 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505215 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355216 EXPECT_EQ(1, network_delegate.created_requests());
5217 EXPECT_EQ(0, network_delegate.destroyed_requests());
5218 }
5219 EXPECT_EQ(1, network_delegate.destroyed_requests());
5220}
5221
5222// Tests that we can handle when a network request was canceled while we were
5223// waiting for the network delegate.
5224// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
5225TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:555226 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355227
5228 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305229 BlockingNetworkDelegate network_delegate(
5230 BlockingNetworkDelegate::USER_CALLBACK);
5231 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:355232
[email protected]ef2bf422012-05-11 03:27:095233 TestURLRequestContext context(true);
5234 context.set_network_delegate(&network_delegate);
5235 context.Init();
[email protected]9045b8822012-01-13 20:35:355236
5237 {
rhalavatib7bd7c792017-04-27 05:25:165238 std::unique_ptr<URLRequest> r(
5239 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5240 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355241
[email protected]f7022f32014-08-21 16:32:195242 r->Start();
Wez2a31b222018-06-07 22:07:155243 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305244 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
5245 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355246 EXPECT_EQ(0, network_delegate.completed_requests());
5247 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195248 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355249 // Ensure that network delegate is notified.
5250 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505251 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355252 EXPECT_EQ(1, network_delegate.created_requests());
5253 EXPECT_EQ(0, network_delegate.destroyed_requests());
5254 }
5255 EXPECT_EQ(1, network_delegate.destroyed_requests());
5256}
5257
5258// Tests that we can handle when a network request was canceled while we were
5259// waiting for the network delegate.
5260// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:025261TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:555262 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355263
5264 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305265 BlockingNetworkDelegate network_delegate(
5266 BlockingNetworkDelegate::USER_CALLBACK);
5267 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:355268
[email protected]ef2bf422012-05-11 03:27:095269 TestURLRequestContext context(true);
5270 context.set_network_delegate(&network_delegate);
5271 context.Init();
[email protected]9045b8822012-01-13 20:35:355272
5273 {
danakj8522a25b2016-04-16 00:17:365274 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165275 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
5276 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355277
[email protected]f7022f32014-08-21 16:32:195278 r->Start();
Wez2a31b222018-06-07 22:07:155279 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305280 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
5281 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355282 EXPECT_EQ(0, network_delegate.completed_requests());
5283 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195284 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355285 // Ensure that network delegate is notified.
5286 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505287 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355288 EXPECT_EQ(1, network_delegate.created_requests());
5289 EXPECT_EQ(0, network_delegate.destroyed_requests());
5290 }
5291 EXPECT_EQ(1, network_delegate.destroyed_requests());
5292}
5293
tommycli59a63432015-11-06 00:10:555294namespace {
5295
danakj8522a25b2016-04-16 00:17:365296std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:555297 const test_server::HttpRequest& request) {
5298 if (request.headers.find("Host") == request.headers.end() ||
5299 request.headers.at("Host") != "www.server-auth.com" ||
5300 request.method != test_server::METHOD_CONNECT) {
5301 return nullptr;
5302 }
5303
danakj8522a25b2016-04-16 00:17:365304 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:555305 new test_server::BasicHttpResponse);
5306 http_response->set_code(HTTP_UNAUTHORIZED);
5307 http_response->AddCustomHeader("WWW-Authenticate",
5308 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:485309 return std::move(http_response);
tommycli59a63432015-11-06 00:10:555310}
5311
5312} // namespace
5313
5314// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:115315// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:555316// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:355317TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:555318 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:125319 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:555320 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115321
[email protected]ceefd7fd2012-11-29 00:36:245322 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:045323 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:555324 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:505325
[email protected]dc651782009-02-14 01:45:085326 TestDelegate d;
5327 {
danakj8522a25b2016-04-16 00:17:365328 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165329 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
5330 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:085331
[email protected]f7022f32014-08-21 16:32:195332 r->Start();
5333 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:085334
Wez2a31b222018-06-07 22:07:155335 d.RunUntilComplete();
[email protected]dc651782009-02-14 01:45:085336
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:225337 // The proxy server should be set before failure.
5338 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
5339 http_test_server()->host_port_pair()),
5340 r->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:505341 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:085342 }
5343}
5344
[email protected]b89290212009-08-14 22:37:355345TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:555346 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115347
initial.commit586acc5fe2008-07-26 22:42:525348 TestDelegate d;
5349 {
Ryan Sleevib8449e02018-07-15 04:31:075350 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165351 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5352 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525353
[email protected]f7022f32014-08-21 16:32:195354 r->Start();
5355 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525356
Wez2a31b222018-06-07 22:07:155357 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525358
5359 EXPECT_EQ(1, d.response_started_count());
5360 EXPECT_FALSE(d.received_data_before_response());
5361 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555362 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375363 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555364 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375365 r->GetResponseRemoteEndpoint().port());
[email protected]c31a54592009-09-04 02:36:165366
[email protected]9e743cd2010-03-16 07:03:535367 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:525368 }
initial.commit586acc5fe2008-07-26 22:42:525369}
5370
[email protected]263163f2012-06-14 22:40:345371// This test has the server send a large number of cookies to the client.
5372// To ensure that no number of cookies causes a crash, a galloping binary
5373// search is used to estimate that maximum number of cookies that are accepted
5374// by the browser. Beyond the maximum number, the request will fail with
5375// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:315376#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:305377// http://crbug.com/177916
5378#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
5379#else
5380#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
5381#endif // defined(OS_WIN)
5382TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:555383 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:345384
5385 int lower_bound = 0;
5386 int upper_bound = 1;
5387
5388 // Double the number of cookies until the response header limits are
5389 // exceeded.
5390 while (DoManyCookiesRequest(upper_bound)) {
5391 lower_bound = upper_bound;
5392 upper_bound *= 2;
5393 ASSERT_LT(upper_bound, 1000000);
5394 }
5395
pkasting6b68a162014-12-01 22:10:295396 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:345397 if (tolerance < 2)
5398 tolerance = 2;
5399
5400 // Perform a binary search to find the highest possible number of cookies,
5401 // within the desired tolerance.
5402 while (upper_bound - lower_bound >= tolerance) {
5403 int num_cookies = (lower_bound + upper_bound) / 2;
5404
5405 if (DoManyCookiesRequest(num_cookies))
5406 lower_bound = num_cookies;
5407 else
5408 upper_bound = num_cookies;
5409 }
5410 // Success: the test did not crash.
5411}
5412
[email protected]b89290212009-08-14 22:37:355413TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:555414 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115415
initial.commit586acc5fe2008-07-26 22:42:525416 TestDelegate d;
5417 {
Ryan Sleevib8449e02018-07-15 04:31:075418 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165419 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5420 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525421
[email protected]f7022f32014-08-21 16:32:195422 r->Start();
5423 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525424
Wez2a31b222018-06-07 22:07:155425 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525426
5427 EXPECT_EQ(1, d.response_started_count());
5428 EXPECT_FALSE(d.received_data_before_response());
5429 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555430 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375431 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555432 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375433 r->GetResponseRemoteEndpoint().port());
initial.commit586acc5fe2008-07-26 22:42:525434 }
[email protected]5d7b373e2009-09-02 07:19:035435}
5436
[email protected]79e1fd62013-06-20 06:50:045437TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555438 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045439
5440 TestDelegate d;
5441 {
tommycli59a63432015-11-06 00:10:555442 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075443 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165444 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045445
5446 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195447 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045448
[email protected]f7022f32014-08-21 16:32:195449 r->Start();
5450 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045451
Wez2a31b222018-06-07 22:07:155452 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:045453
5454 EXPECT_EQ(1, d.response_started_count());
5455 EXPECT_FALSE(d.received_data_before_response());
5456 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555457 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375458 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555459 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375460 r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:045461
5462 EXPECT_TRUE(d.have_full_request_headers());
5463 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5464 }
5465}
5466
[email protected]58e32bb2013-01-21 18:23:255467TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555468 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255469
5470 TestDelegate d;
5471 {
Ryan Sleevib8449e02018-07-15 04:31:075472 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165473 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5474 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255475
[email protected]f7022f32014-08-21 16:32:195476 r->Start();
5477 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255478
Wez2a31b222018-06-07 22:07:155479 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255480
5481 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195482 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255483 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5484
5485 EXPECT_EQ(1, d.response_started_count());
5486 EXPECT_FALSE(d.received_data_before_response());
5487 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555488 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375489 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555490 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375491 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:255492 }
5493}
5494
tommycli59a63432015-11-06 00:10:555495// TODO(svaldez): Update tests to use EmbeddedTestServer.
5496#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395497TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555498 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555499 base::FilePath(kTestFilePath));
5500
5501 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395502
5503 // Parameter that specifies the Content-Length field in the response:
5504 // C - Compressed length.
5505 // U - Uncompressed length.
5506 // L - Large length (larger than both C & U).
5507 // M - Medium length (between C & U).
5508 // S - Small length (smaller than both C & U).
5509 const char test_parameters[] = "CULMS";
Avi Drissman4365a4782018-12-28 19:26:245510 const int num_tests = base::size(test_parameters) - 1; // Skip NULL.
[email protected]aad63572011-05-24 20:14:395511 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445512 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395513 // S has too little data, but we seem to accept it.
5514 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375515 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395516
xunjielifb4da222016-07-14 18:38:595517 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:195518 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
xunjielifb4da222016-07-14 18:38:595519 file_path = file_path.Append(kTestFilePath);
5520 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5521 std::string expected_content;
5522 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5523
5524 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395525 TestDelegate d;
5526 {
tommycli59a63432015-11-06 00:10:555527 std::string test_file = base::StringPrintf(
5528 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395529
[email protected]ceefd7fd2012-11-29 00:36:245530 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095531 TestURLRequestContext context(true);
5532 context.set_network_delegate(&network_delegate);
5533 context.Init();
[email protected]87a09a92011-07-14 15:50:505534
rhalavatib7bd7c792017-04-27 05:25:165535 std::unique_ptr<URLRequest> r(
5536 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5537 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195538 r->Start();
5539 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395540
Wez2a31b222018-06-07 22:07:155541 d.RunUntilComplete();
[email protected]aad63572011-05-24 20:14:395542
5543 EXPECT_EQ(1, d.response_started_count());
5544 EXPECT_FALSE(d.received_data_before_response());
5545 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505546 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395547 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505548 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5549 << "\"";
xunjielifb4da222016-07-14 18:38:595550 if (test_parameters[i] == 'S') {
5551 // When content length is smaller than both compressed length and
5552 // uncompressed length, HttpStreamParser might not read the full
5553 // response body.
5554 continue;
5555 }
5556 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395557 } else {
maksim.sisovb53724b52016-09-16 05:30:505558 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395559 << " Parameter = \"" << test_file << "\"";
5560 }
5561 }
5562 }
5563}
tommycli59a63432015-11-06 00:10:555564#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395565
[email protected]58e32bb2013-01-21 18:23:255566TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555567 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255568
tommycli59a63432015-11-06 00:10:555569 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455570 GURL original_url =
tommycli59a63432015-11-06 00:10:555571 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255572 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075573 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165574 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195575 req->Start();
Wez2a31b222018-06-07 22:07:155576 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255577
5578 EXPECT_EQ(1, d.response_started_count());
5579 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195580 EXPECT_EQ(destination_url, req->url());
5581 EXPECT_EQ(original_url, req->original_url());
5582 ASSERT_EQ(2U, req->url_chain().size());
5583 EXPECT_EQ(original_url, req->url_chain()[0]);
5584 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255585
5586 LoadTimingInfo load_timing_info_before_redirect;
5587 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5588 &load_timing_info_before_redirect));
5589 TestLoadTimingNotReused(load_timing_info_before_redirect,
5590 CONNECT_TIMING_HAS_DNS_TIMES);
5591
5592 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195593 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255594 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5595
5596 // Check that a new socket was used on redirect, since the server does not
5597 // supposed keep-alive sockets, and that the times before the redirect are
5598 // before the ones recorded for the second request.
5599 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5600 load_timing_info.socket_log_id);
5601 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5602 load_timing_info.connect_timing.connect_start);
5603}
5604
[email protected]8f1ac082011-04-19 21:14:135605TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555606 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135607
tommycli59a63432015-11-06 00:10:555608 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455609 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555610 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5611 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5612 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135613 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075614 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165615 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195616 req->Start();
Wez2a31b222018-06-07 22:07:155617 d.RunUntilComplete();
[email protected]8f1ac082011-04-19 21:14:135618
5619 EXPECT_EQ(1, d.response_started_count());
5620 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195621 EXPECT_EQ(destination_url, req->url());
5622 EXPECT_EQ(original_url, req->original_url());
5623 ASSERT_EQ(3U, req->url_chain().size());
5624 EXPECT_EQ(original_url, req->url_chain()[0]);
5625 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5626 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135627}
5628
David Benjamina7fde612019-03-15 14:20:585629// This is a regression test for https://crbug.com/942073.
5630TEST_F(URLRequestTestHTTP, RedirectEscaping) {
5631 ASSERT_TRUE(http_test_server()->Start());
5632
5633 // Assemble the destination URL as a string so it is not escaped by GURL.
5634 GURL destination_base = http_test_server()->GetURL("/defaultresponse");
5635 // Add a URL fragment of U+2603 unescaped, U+2603 escaped, and then a UTF-8
5636 // encoding error.
5637 std::string destination_url =
5638 destination_base.spec() + "#\xE2\x98\x83_%E2%98%83_\xE0\xE0";
5639 // Redirect resolution should percent-escape bytes and preserve the UTF-8
5640 // error at the end.
5641 std::string destination_escaped =
5642 destination_base.spec() + "#%E2%98%83_%E2%98%83_%E0%E0";
5643 GURL original_url = http_test_server()->GetURL(
5644 "/server-redirect?" + EscapeQueryParamValue(destination_url, false));
5645 TestDelegate d;
5646 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
5647 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5648 req->Start();
5649 d.RunUntilComplete();
5650
5651 EXPECT_EQ(1, d.response_started_count());
5652 EXPECT_EQ(1, d.received_redirect_count());
5653 EXPECT_EQ(destination_escaped, req->url().spec());
5654 EXPECT_EQ(original_url, req->original_url());
5655 ASSERT_EQ(2U, req->url_chain().size());
5656 EXPECT_EQ(original_url, req->url_chain()[0]);
5657 EXPECT_EQ(destination_escaped, req->url_chain()[1].spec());
5658}
5659
[email protected]abe1c4a2013-10-25 19:28:515660// First and second pieces of information logged by delegates to URLRequests.
5661const char kFirstDelegateInfo[] = "Wonderful delegate";
5662const char kSecondDelegateInfo[] = "Exciting delegate";
5663
5664// Logs delegate information to a URLRequest. The first string is logged
5665// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5666// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5667// another asynchronous call is used to clear the delegate information
5668// before calling a callback. The object then deletes itself.
5669class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5670 public:
David Benjamind1f287bf2018-06-12 01:57:205671 using Callback = base::OnceCallback<void()>;
[email protected]abe1c4a2013-10-25 19:28:515672
5673 // Each time delegate information is added to the URLRequest, the resulting
5674 // load state is checked. The expected load state after each request is
5675 // passed in as an argument.
5676 static void Run(URLRequest* url_request,
5677 LoadState expected_first_load_state,
5678 LoadState expected_second_load_state,
5679 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205680 Callback callback) {
tzik38f920a2018-08-01 04:41:205681 // base::MakeRefCounted<AsyncDelegateLogger> is unavailable here, since the
5682 // constructor of AsyncDelegateLogger is private.
5683 auto logger = base::WrapRefCounted(new AsyncDelegateLogger(
David Benjamind1f287bf2018-06-12 01:57:205684 url_request, expected_first_load_state, expected_second_load_state,
tzik38f920a2018-08-01 04:41:205685 expected_third_load_state, std::move(callback)));
[email protected]abe1c4a2013-10-25 19:28:515686 logger->Start();
5687 }
5688
5689 // Checks that the log entries, starting with log_position, contain the
5690 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5691 // recorded. Returns the index of entry after the expected number of
5692 // events this logged, or entries.size() if there aren't enough entries.
Eric Roman79cc7552019-07-19 02:17:545693 static size_t CheckDelegateInfo(const std::vector<NetLogEntry>& entries,
vishal.b62985ca92015-04-17 08:45:515694 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515695 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5696 if (log_position + 3 >= entries.size()) {
5697 ADD_FAILURE() << "Not enough log entries";
5698 return entries.size();
5699 }
5700 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005701 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5702 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
Eric Roman79cc7552019-07-19 02:17:545703 EXPECT_EQ(
5704 kFirstDelegateInfo,
5705 GetStringValueFromParams(entries[log_position], "delegate_blocked_by"));
[email protected]abe1c4a2013-10-25 19:28:515706
5707 ++log_position;
mikecirone8b85c432016-09-08 19:11:005708 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5709 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515710
5711 ++log_position;
mikecirone8b85c432016-09-08 19:11:005712 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5713 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
Eric Roman79cc7552019-07-19 02:17:545714 EXPECT_EQ(
5715 kSecondDelegateInfo,
5716 GetStringValueFromParams(entries[log_position], "delegate_blocked_by"));
[email protected]abe1c4a2013-10-25 19:28:515717
5718 ++log_position;
mikecirone8b85c432016-09-08 19:11:005719 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5720 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515721
5722 return log_position + 1;
5723 }
5724
5725 private:
5726 friend class base::RefCounted<AsyncDelegateLogger>;
5727
5728 AsyncDelegateLogger(URLRequest* url_request,
5729 LoadState expected_first_load_state,
5730 LoadState expected_second_load_state,
5731 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205732 Callback callback)
[email protected]abe1c4a2013-10-25 19:28:515733 : url_request_(url_request),
5734 expected_first_load_state_(expected_first_load_state),
5735 expected_second_load_state_(expected_second_load_state),
5736 expected_third_load_state_(expected_third_load_state),
David Benjamind1f287bf2018-06-12 01:57:205737 callback_(std::move(callback)) {}
[email protected]abe1c4a2013-10-25 19:28:515738
Chris Watkins7a41d3552017-12-01 02:13:275739 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515740
5741 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535742 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515743 LoadStateWithParam load_state = url_request_->GetLoadState();
5744 EXPECT_EQ(expected_first_load_state_, load_state.state);
5745 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455746 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155747 FROM_HERE,
5748 base::BindOnce(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515749 }
5750
5751 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535752 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515753 LoadStateWithParam load_state = url_request_->GetLoadState();
5754 EXPECT_EQ(expected_second_load_state_, load_state.state);
5755 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5756 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5757 } else {
5758 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5759 }
skyostil4891b25b2015-06-11 11:43:455760 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155761 FROM_HERE, base::BindOnce(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515762 }
5763
5764 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535765 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515766 LoadStateWithParam load_state = url_request_->GetLoadState();
5767 EXPECT_EQ(expected_third_load_state_, load_state.state);
5768 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085769 EXPECT_EQ(base::string16(), load_state.param);
David Benjamind1f287bf2018-06-12 01:57:205770 std::move(callback_).Run();
[email protected]abe1c4a2013-10-25 19:28:515771 }
5772
5773 URLRequest* url_request_;
5774 const int expected_first_load_state_;
5775 const int expected_second_load_state_;
5776 const int expected_third_load_state_;
David Benjamind1f287bf2018-06-12 01:57:205777 Callback callback_;
[email protected]abe1c4a2013-10-25 19:28:515778
5779 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5780};
5781
5782// NetworkDelegate that logs delegate information before a request is started,
5783// before headers are sent, when headers are read, and when auth information
5784// is requested. Uses AsyncDelegateLogger.
5785class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5786 public:
Chris Watkins7a41d3552017-12-01 02:13:275787 AsyncLoggingNetworkDelegate() = default;
5788 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515789
5790 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205791 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205792 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:205793 GURL* new_url) override {
David Benjamind1f287bf2018-06-12 01:57:205794 // TestNetworkDelegate always completes synchronously.
5795 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
5796 request, base::NullCallback(), new_url));
5797 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515798 }
5799
ryansturm2343cb62016-06-15 01:09:005800 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205801 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:005802 HttpRequestHeaders* headers) override {
David Benjamind1f287bf2018-06-12 01:57:205803 // TestNetworkDelegate always completes synchronously.
5804 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
5805 request, base::NullCallback(), headers));
5806 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515807 }
5808
dchengb03027d2014-10-21 12:00:205809 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515810 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205811 CompletionOnceCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515812 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165813 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135814 GURL* allowed_unsafe_redirect_url) override {
David Benjamind1f287bf2018-06-12 01:57:205815 // TestNetworkDelegate always completes synchronously.
5816 CHECK_NE(ERR_IO_PENDING,
5817 TestNetworkDelegate::OnHeadersReceived(
5818 request, base::NullCallback(), original_response_headers,
5819 override_response_headers, allowed_unsafe_redirect_url));
5820 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515821 }
5822
dchengb03027d2014-10-21 12:00:205823 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515824 URLRequest* request,
5825 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:205826 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:135827 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515828 AsyncDelegateLogger::Run(
David Benjamind1f287bf2018-06-12 01:57:205829 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5830 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5831 base::BindOnce(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5832 std::move(callback), credentials));
[email protected]abe1c4a2013-10-25 19:28:515833 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5834 }
5835
5836 private:
David Benjamind1f287bf2018-06-12 01:57:205837 static int RunCallbackAsynchronously(URLRequest* request,
5838 CompletionOnceCallback callback) {
5839 AsyncDelegateLogger::Run(request, LOAD_STATE_WAITING_FOR_DELEGATE,
5840 LOAD_STATE_WAITING_FOR_DELEGATE,
5841 LOAD_STATE_WAITING_FOR_DELEGATE,
5842 base::BindOnce(std::move(callback), OK));
[email protected]abe1c4a2013-10-25 19:28:515843 return ERR_IO_PENDING;
5844 }
5845
David Benjamind1f287bf2018-06-12 01:57:205846 static void SetAuthAndResume(AuthCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515847 AuthCredentials* credentials) {
5848 *credentials = AuthCredentials(kUser, kSecret);
David Benjamind1f287bf2018-06-12 01:57:205849 std::move(callback).Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
[email protected]abe1c4a2013-10-25 19:28:515850 }
5851
5852 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5853};
5854
5855// URLRequest::Delegate that logs delegate information when the headers
5856// are received, when each read completes, and during redirects. Uses
5857// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5858//
5859// Inherits from TestDelegate to reuse the TestDelegate code to handle
5860// advancing to the next step in most cases, as well as cancellation.
5861class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5862 public:
5863 enum CancelStage {
5864 NO_CANCEL = 0,
5865 CANCEL_ON_RECEIVED_REDIRECT,
5866 CANCEL_ON_RESPONSE_STARTED,
5867 CANCEL_ON_READ_COMPLETED
5868 };
5869
5870 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5871 : cancel_stage_(cancel_stage) {
5872 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5873 set_cancel_in_received_redirect(true);
5874 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5875 set_cancel_in_response_started(true);
5876 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5877 set_cancel_in_received_data(true);
5878 }
Chris Watkins7a41d3552017-12-01 02:13:275879 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515880
5881 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205882 void OnReceivedRedirect(URLRequest* request,
5883 const RedirectInfo& redirect_info,
5884 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515885 *defer_redirect = true;
5886 AsyncDelegateLogger::Run(
5887 request,
5888 LOAD_STATE_WAITING_FOR_DELEGATE,
5889 LOAD_STATE_WAITING_FOR_DELEGATE,
5890 LOAD_STATE_WAITING_FOR_DELEGATE,
5891 base::Bind(
5892 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595893 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515894 }
5895
maksim.sisov0f4aa142016-09-05 05:55:285896 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515897 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285898 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5899 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5900 base::Bind(
5901 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5902 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515903 }
5904
dchengb03027d2014-10-21 12:00:205905 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515906 AsyncDelegateLogger::Run(
5907 request,
5908 LOAD_STATE_IDLE,
5909 LOAD_STATE_IDLE,
5910 LOAD_STATE_IDLE,
5911 base::Bind(
5912 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5913 base::Unretained(this), request, bytes_read));
5914 }
5915
5916 private:
5917 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595918 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515919 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595920 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515921 // FollowDeferredRedirect should not be called after cancellation.
5922 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5923 return;
Arthur Sonzognib8465ff72019-01-04 18:44:355924 if (!defer_redirect) {
5925 request->FollowDeferredRedirect(base::nullopt /* removed_headers */,
5926 base::nullopt /* modified_headers */);
5927 }
[email protected]abe1c4a2013-10-25 19:28:515928 }
5929
maksim.sisov0f4aa142016-09-05 05:55:285930 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515931 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285932 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515933 }
5934
5935 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5936 // The parent class continues the request.
5937 TestDelegate::OnReadCompleted(request, bytes_read);
5938 }
5939
5940 const CancelStage cancel_stage_;
5941
5942 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5943};
5944
5945// Tests handling of delegate info before a request starts.
5946TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555947 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515948
5949 TestDelegate request_delegate;
5950 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:355951 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:515952 context.set_net_log(&net_log_);
5953 context.Init();
5954
5955 {
rhalavatib7bd7c792017-04-27 05:25:165956 std::unique_ptr<URLRequest> r(context.CreateRequest(
5957 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5958 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195959 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515960 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085961 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515962
5963 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195964 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515965 LOAD_STATE_WAITING_FOR_DELEGATE,
5966 LOAD_STATE_WAITING_FOR_DELEGATE,
5967 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195968 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515969
Wez2a31b222018-06-07 22:07:155970 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515971
[email protected]f7022f32014-08-21 16:32:195972 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505973 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515974 }
5975
Eric Roman79cc7552019-07-19 02:17:545976 auto entries = net_log_.GetEntries();
[email protected]abe1c4a2013-10-25 19:28:515977 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005978 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515979
5980 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5981
5982 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005983 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5984 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515985}
5986
5987// Tests handling of delegate info from a network delegate.
5988TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555989 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515990
5991 TestDelegate request_delegate;
5992 AsyncLoggingNetworkDelegate network_delegate;
5993 TestURLRequestContext context(true);
5994 context.set_network_delegate(&network_delegate);
5995 context.set_net_log(&net_log_);
5996 context.Init();
5997
5998 {
rhalavatib7bd7c792017-04-27 05:25:165999 std::unique_ptr<URLRequest> r(context.CreateRequest(
6000 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
6001 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196002 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516003 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086004 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516005
[email protected]f7022f32014-08-21 16:32:196006 r->Start();
Wez2a31b222018-06-07 22:07:156007 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516008
[email protected]f7022f32014-08-21 16:32:196009 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506010 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516011 EXPECT_EQ(1, network_delegate.created_requests());
6012 EXPECT_EQ(0, network_delegate.destroyed_requests());
6013 }
6014 EXPECT_EQ(1, network_delegate.destroyed_requests());
6015
6016 size_t log_position = 0;
Eric Roman79cc7552019-07-19 02:17:546017 auto entries = net_log_.GetEntries();
David Benjamin9776ca22018-06-13 00:00:156018 static const NetLogEventType kExpectedEvents[] = {
6019 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6020 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6021 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6022 };
6023 for (NetLogEventType event : kExpectedEvents) {
6024 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516025 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156026 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516027
6028 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6029 log_position + 1);
6030
6031 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156032 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006033 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516034 }
6035
mikecirone8b85c432016-09-08 19:11:006036 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6037 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516038}
6039
6040// Tests handling of delegate info from a network delegate in the case of an
6041// HTTP redirect.
6042TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:556043 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516044
6045 TestDelegate request_delegate;
6046 AsyncLoggingNetworkDelegate network_delegate;
6047 TestURLRequestContext context(true);
6048 context.set_network_delegate(&network_delegate);
6049 context.set_net_log(&net_log_);
6050 context.Init();
6051
6052 {
danakj8522a25b2016-04-16 00:17:366053 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556054 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166055 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196056 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516057 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086058 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516059
[email protected]f7022f32014-08-21 16:32:196060 r->Start();
Wez2a31b222018-06-07 22:07:156061 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516062
[email protected]f7022f32014-08-21 16:32:196063 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506064 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516065 EXPECT_EQ(2, network_delegate.created_requests());
6066 EXPECT_EQ(0, network_delegate.destroyed_requests());
6067 }
6068 EXPECT_EQ(1, network_delegate.destroyed_requests());
6069
6070 size_t log_position = 0;
Eric Roman79cc7552019-07-19 02:17:546071 auto entries = net_log_.GetEntries();
David Benjamin9776ca22018-06-13 00:00:156072 static const NetLogEventType kExpectedEvents[] = {
6073 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6074 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6075 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6076 };
6077 for (NetLogEventType event : kExpectedEvents) {
6078 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516079 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156080 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516081
David Benjamin9776ca22018-06-13 00:00:156082 log_position =
6083 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516084
6085 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156086 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006087 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516088 }
6089
6090 // The URLRequest::Delegate then gets informed about the redirect.
6091 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156092 entries, log_position + 1,
6093 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
mikecirone8b85c432016-09-08 19:11:006094 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516095
6096 // The NetworkDelegate logged information in the same three events as before.
David Benjamin9776ca22018-06-13 00:00:156097 for (NetLogEventType event : kExpectedEvents) {
6098 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516099 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156100 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516101
6102 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6103 log_position + 1);
6104
6105 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156106 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006107 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516108 }
6109
mikecirone8b85c432016-09-08 19:11:006110 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6111 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516112}
6113
6114// Tests handling of delegate info from a network delegate in the case of HTTP
6115// AUTH.
6116TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:556117 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516118
6119 TestDelegate request_delegate;
6120 AsyncLoggingNetworkDelegate network_delegate;
6121 TestURLRequestContext context(true);
6122 context.set_network_delegate(&network_delegate);
6123 context.set_net_log(&net_log_);
6124 context.Init();
6125
6126 {
rhalavatib7bd7c792017-04-27 05:25:166127 std::unique_ptr<URLRequest> r(context.CreateRequest(
6128 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
6129 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196130 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516131 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086132 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516133
[email protected]f7022f32014-08-21 16:32:196134 r->Start();
Wez2a31b222018-06-07 22:07:156135 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516136
[email protected]f7022f32014-08-21 16:32:196137 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506138 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516139 EXPECT_EQ(1, network_delegate.created_requests());
6140 EXPECT_EQ(0, network_delegate.destroyed_requests());
6141 }
6142 EXPECT_EQ(1, network_delegate.destroyed_requests());
6143
6144 size_t log_position = 0;
Eric Roman79cc7552019-07-19 02:17:546145 auto entries = net_log_.GetEntries();
David Benjamin9776ca22018-06-13 00:00:156146 static const NetLogEventType kExpectedEvents[] = {
6147 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6148 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6149 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6150 NetLogEventType::NETWORK_DELEGATE_AUTH_REQUIRED,
6151 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6152 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6153 };
6154 for (NetLogEventType event : kExpectedEvents) {
6155 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516156 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156157 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516158
David Benjamin9776ca22018-06-13 00:00:156159 log_position =
6160 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516161
6162 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156163 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006164 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516165 }
6166
mikecirone8b85c432016-09-08 19:11:006167 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6168 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516169}
6170
tommycli59a63432015-11-06 00:10:556171// TODO(svaldez): Update tests to use EmbeddedTestServer.
6172#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516173// Tests handling of delegate info from a URLRequest::Delegate.
6174TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:556175 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:556176 base::FilePath(kTestFilePath));
6177
6178 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:516179
6180 AsyncLoggingUrlRequestDelegate request_delegate(
6181 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6182 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356183 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516184 context.set_net_log(&net_log_);
6185 context.Init();
6186
6187 {
6188 // A chunked response with delays between chunks is used to make sure that
6189 // attempts by the URLRequest delegate to log information while reading the
6190 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:486191 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:516192 // that it occurs.
danakj8522a25b2016-04-16 00:17:366193 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556194 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166195 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196196 LoadStateWithParam load_state = r->GetLoadState();
6197 r->Start();
Wez2a31b222018-06-07 22:07:156198 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516199
[email protected]f7022f32014-08-21 16:32:196200 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506201 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516202 }
6203
Eric Roman79cc7552019-07-19 02:17:546204 auto entries = net_log_.GetEntries();
[email protected]abe1c4a2013-10-25 19:28:516205
[email protected]1826a402014-01-08 15:40:486206 size_t log_position = 0;
6207
[email protected]abe1c4a2013-10-25 19:28:516208 // The delegate info should only have been logged on header complete. Other
6209 // times it should silently be ignored.
David Benjamin9776ca22018-06-13 00:00:156210 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
6211 entries, 0, NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST));
mikecirone8b85c432016-09-08 19:11:006212 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156213 entries, log_position + 1,
6214 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
mikecirone8b85c432016-09-08 19:11:006215 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516216
David Benjamin9776ca22018-06-13 00:00:156217 log_position =
6218 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516219
6220 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156221 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6222 entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006223 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516224
mikecirone8b85c432016-09-08 19:11:006225 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6226 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516227 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
David Benjamin9776ca22018-06-13 00:00:156228 entries, log_position + 1,
6229 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED));
[email protected]abe1c4a2013-10-25 19:28:516230}
tommycli59a63432015-11-06 00:10:556231#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516232
6233// Tests handling of delegate info from a URLRequest::Delegate in the case of
6234// an HTTP redirect.
6235TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:556236 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516237
6238 AsyncLoggingUrlRequestDelegate request_delegate(
6239 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6240 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356241 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516242 context.set_net_log(&net_log_);
6243 context.Init();
6244
6245 {
danakj8522a25b2016-04-16 00:17:366246 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556247 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166248 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196249 LoadStateWithParam load_state = r->GetLoadState();
6250 r->Start();
Wez2a31b222018-06-07 22:07:156251 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516252
[email protected]f7022f32014-08-21 16:32:196253 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506254 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516255 }
6256
Eric Roman79cc7552019-07-19 02:17:546257 auto entries = net_log_.GetEntries();
[email protected]abe1c4a2013-10-25 19:28:516258
6259 // Delegate info should only have been logged in OnReceivedRedirect and
6260 // OnResponseStarted.
6261 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156262 static const NetLogEventType kExpectedEvents[] = {
6263 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6264 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6265 };
6266 for (NetLogEventType event : kExpectedEvents) {
6267 SCOPED_TRACE(NetLog::EventTypeToString(event));
6268 log_position = ExpectLogContainsSomewhereAfter(entries, log_position, event,
6269 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516270
David Benjamin9776ca22018-06-13 00:00:156271 log_position =
6272 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516273
6274 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156275 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006276 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516277 }
6278
mikecirone8b85c432016-09-08 19:11:006279 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6280 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516281}
6282
6283// Tests handling of delegate info from a URLRequest::Delegate in the case of
6284// an HTTP redirect, with cancellation at various points.
6285TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:556286 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516287
6288 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
6289 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
6290 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
6291 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
6292 };
6293
David Benjamin9776ca22018-06-13 00:00:156294 for (auto cancel_stage : kCancelStages) {
6295 AsyncLoggingUrlRequestDelegate request_delegate(cancel_stage);
vishal.b62985ca92015-04-17 08:45:516296 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046297 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356298 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516299 context.set_net_log(&net_log);
6300 context.Init();
6301
6302 {
danakj8522a25b2016-04-16 00:17:366303 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556304 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166305 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196306 LoadStateWithParam load_state = r->GetLoadState();
6307 r->Start();
Wez2a31b222018-06-07 22:07:156308 request_delegate.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506309 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
Wez2a31b222018-06-07 22:07:156310
6311 // Spin the message loop to run AsyncDelegateLogger task(s) posted after
6312 // the |request_delegate| completion task.
6313 base::RunLoop().RunUntilIdle();
[email protected]abe1c4a2013-10-25 19:28:516314 }
6315
Eric Roman79cc7552019-07-19 02:17:546316 auto entries = net_log.GetEntries();
[email protected]abe1c4a2013-10-25 19:28:516317
6318 // Delegate info is always logged in both OnReceivedRedirect and
6319 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6320 // OnResponseStarted delegate call is after cancellation, but logging is
6321 // still currently supported in that call.
6322 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156323 static const NetLogEventType kExpectedEvents[] = {
6324 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6325 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6326 };
6327 for (NetLogEventType event : kExpectedEvents) {
6328 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516329 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156330 entries, log_position, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516331
David Benjamin9776ca22018-06-13 00:00:156332 log_position =
6333 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516334
6335 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156336 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006337 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516338 }
6339
mikecirone8b85c432016-09-08 19:11:006340 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6341 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516342 }
6343}
6344
[email protected]847c0fa92012-11-06 16:37:426345namespace {
6346
6347const char kExtraHeader[] = "Allow-Snafu";
6348const char kExtraValue[] = "fubar";
6349
6350class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206351 void OnReceivedRedirect(URLRequest* request,
6352 const RedirectInfo& redirect_info,
6353 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596354 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426355 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6356 }
6357};
6358
6359} // namespace
6360
6361TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556362 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426363
tommycli59a63432015-11-06 00:10:556364 GURL destination_url =
6365 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6366 GURL original_url =
6367 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426368 RedirectWithAdditionalHeadersDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076369 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166370 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196371 req->Start();
Wez2a31b222018-06-07 22:07:156372 d.RunUntilComplete();
[email protected]847c0fa92012-11-06 16:37:426373
6374 std::string value;
[email protected]f7022f32014-08-21 16:32:196375 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426376 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6377 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196378 EXPECT_FALSE(req->is_pending());
6379 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426380 EXPECT_EQ(kExtraValue, d.data_received());
6381}
6382
[email protected]251a1b92012-11-13 11:01:096383namespace {
6384
6385const char kExtraHeaderToRemove[] = "To-Be-Removed";
6386
6387class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206388 void OnReceivedRedirect(URLRequest* request,
6389 const RedirectInfo& redirect_info,
6390 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596391 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096392 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6393 }
6394};
6395
6396} // namespace
6397
6398TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556399 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096400
tommycli59a63432015-11-06 00:10:556401 GURL destination_url = http_test_server()->GetURL(
6402 "/echoheader?" + std::string(kExtraHeaderToRemove));
6403 GURL original_url =
6404 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096405 RedirectWithHeaderRemovalDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076406 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166407 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196408 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6409 req->Start();
Wez2a31b222018-06-07 22:07:156410 d.RunUntilComplete();
[email protected]251a1b92012-11-13 11:01:096411
6412 std::string value;
[email protected]f7022f32014-08-21 16:32:196413 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096414 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196415 EXPECT_FALSE(req->is_pending());
6416 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096417 EXPECT_EQ("None", d.data_received());
6418}
6419
mmenke94f1bd92016-12-07 21:13:056420TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446421 TestDelegate d;
6422 {
Ryan Sleevib8449e02018-07-15 04:31:076423 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166424 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6425 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446426
[email protected]f7022f32014-08-21 16:32:196427 r->Start();
6428 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446429
[email protected]f7022f32014-08-21 16:32:196430 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446431
Wez2a31b222018-06-07 22:07:156432 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446433
6434 // We expect to receive OnResponseStarted even though the request has been
6435 // cancelled.
6436 EXPECT_EQ(1, d.response_started_count());
6437 EXPECT_EQ(0, d.bytes_received());
6438 EXPECT_FALSE(d.received_data_before_response());
6439 }
6440}
6441
mmenke94f1bd92016-12-07 21:13:056442TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556443 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446444
6445 TestDelegate d;
6446 {
Ryan Sleevib8449e02018-07-15 04:31:076447 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166448 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6449 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446450
6451 d.set_cancel_in_response_started(true);
6452
[email protected]f7022f32014-08-21 16:32:196453 r->Start();
6454 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446455
Wez2a31b222018-06-07 22:07:156456 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446457
6458 EXPECT_EQ(1, d.response_started_count());
6459 EXPECT_EQ(0, d.bytes_received());
6460 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506461 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446462 }
6463}
6464
mmenke94f1bd92016-12-07 21:13:056465TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556466 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446467
6468 TestDelegate d;
6469 {
Ryan Sleevib8449e02018-07-15 04:31:076470 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166471 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6472 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056473
6474 d.set_cancel_in_received_data(true);
6475
6476 r->Start();
6477 EXPECT_TRUE(r->is_pending());
6478
Wez2a31b222018-06-07 22:07:156479 d.RunUntilComplete();
mmenke94f1bd92016-12-07 21:13:056480
6481 EXPECT_EQ(1, d.response_started_count());
6482 EXPECT_NE(0, d.received_bytes_count());
6483 EXPECT_FALSE(d.received_data_before_response());
6484 EXPECT_EQ(ERR_ABORTED, d.request_status());
6485 }
6486}
6487
6488TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6489 ASSERT_TRUE(http_test_server()->Start());
6490
6491 TestDelegate d;
6492 {
6493 // This returns an empty response (With headers).
Ryan Sleevib8449e02018-07-15 04:31:076494 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166495 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6496 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446497
6498 d.set_cancel_in_received_data(true);
6499
[email protected]f7022f32014-08-21 16:32:196500 r->Start();
6501 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446502
Wez2a31b222018-06-07 22:07:156503 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446504
6505 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056506 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446507 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506508 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446509 }
6510}
6511
mmenke94f1bd92016-12-07 21:13:056512TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556513 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446514
6515 TestDelegate d;
6516 {
Ryan Sleevib8449e02018-07-15 04:31:076517 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166518 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6519 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446520
[email protected]f7022f32014-08-21 16:32:196521 r->Start();
6522 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446523
6524 // The request will be implicitly canceled when it is destroyed. The
6525 // test delegate must not post a quit message when this happens because
6526 // this test doesn't actually have a message loop. The quit message would
6527 // get put on this thread's message queue and the next test would exit
6528 // early, causing problems.
Wez0e717112018-06-18 23:09:226529 d.set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:446530 }
6531 // expect things to just cleanup properly.
6532
kimwjdalsl2bb4ff02015-12-16 22:06:026533 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446534 // message loop
6535 EXPECT_FALSE(d.received_data_before_response());
6536 EXPECT_EQ(0, d.bytes_received());
6537}
6538
mmenke94f1bd92016-12-07 21:13:056539TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556540 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446541
6542 // populate cache
6543 {
6544 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076545 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166546 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6547 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196548 r->Start();
Wez2a31b222018-06-07 22:07:156549 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506550 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446551 }
6552
6553 // cancel read from cache (see bug 990242)
6554 {
6555 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076556 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166557 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6558 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196559 r->Start();
6560 r->Cancel();
Wez2a31b222018-06-07 22:07:156561 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446562
maksim.sisovb53724b52016-09-16 05:30:506563 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446564 EXPECT_EQ(1, d.response_started_count());
6565 EXPECT_EQ(0, d.bytes_received());
6566 EXPECT_FALSE(d.received_data_before_response());
6567 }
6568}
6569
6570TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556571 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446572 HTTPUploadDataOperationTest("POST");
6573}
6574
6575TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556576 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446577 HTTPUploadDataOperationTest("PUT");
6578}
6579
6580TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556581 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446582
6583 TestDelegate d;
6584 {
Ryan Sleevib8449e02018-07-15 04:31:076585 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166586 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6587 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196588 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446589
[email protected]f7022f32014-08-21 16:32:196590 r->Start();
6591 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446592
Wez2a31b222018-06-07 22:07:156593 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446594
maksim.sisovb53724b52016-09-16 05:30:506595 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6596 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446597
6598 EXPECT_FALSE(d.received_data_before_response());
6599 EXPECT_TRUE(d.data_received().empty());
6600 }
6601}
6602
6603TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556604 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446605
6606 TestDelegate d;
6607 {
Ryan Sleevib8449e02018-07-15 04:31:076608 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166609 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6610 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196611 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446612
[email protected]6cdfd7f2013-02-08 20:40:156613 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196614 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026615 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446616
danakj8522a25b2016-04-16 00:17:366617 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446618
[email protected]6cdfd7f2013-02-08 20:40:156619 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196620 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476621 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446622 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196623 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146624 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076625 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046626 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6627 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446628
[email protected]f7022f32014-08-21 16:32:196629 r->Start();
6630 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446631
Wez2a31b222018-06-07 22:07:156632 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446633
avibf0746c2015-12-09 19:53:146634 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296635 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6636 ASSERT_LE(size64, std::numeric_limits<int>::max());
6637 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366638 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446639
[email protected]7600d0b2013-12-08 21:43:306640 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446641
maksim.sisovb53724b52016-09-16 05:30:506642 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6643 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446644
6645 EXPECT_FALSE(d.received_data_before_response());
6646
[email protected]329b68b2012-11-14 17:54:276647 EXPECT_EQ(size, d.bytes_received());
6648 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446649 }
6650}
6651
[email protected]999dd8c2013-11-12 06:45:546652TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556653 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546654
6655 TestDelegate d;
6656 {
Ryan Sleevib8449e02018-07-15 04:31:076657 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166658 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6659 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196660 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546661
danakj8522a25b2016-04-16 00:17:366662 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546663
Jeremy Roman0579ed62017-08-29 15:56:196664 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456665 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546666 base::FilePath(FILE_PATH_LITERAL(
6667 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076668 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046669 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6670 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546671
[email protected]f7022f32014-08-21 16:32:196672 r->Start();
6673 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546674
Wez2a31b222018-06-07 22:07:156675 d.RunUntilComplete();
[email protected]999dd8c2013-11-12 06:45:546676
[email protected]999dd8c2013-11-12 06:45:546677 EXPECT_TRUE(d.request_failed());
6678 EXPECT_FALSE(d.received_data_before_response());
6679 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506680 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546681 }
6682}
6683
mmenke56b0cbb912016-03-28 21:34:536684namespace {
6685
6686// Adds a standard set of data to an upload for chunked upload integration
6687// tests.
6688void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6689 writer->AppendData("a", 1, false);
6690 writer->AppendData("bcd", 3, false);
6691 writer->AppendData("this is a longer chunk than before.", 35, false);
6692 writer->AppendData("\r\n\r\n", 4, false);
6693 writer->AppendData("0", 1, false);
6694 writer->AppendData("2323", 4, true);
6695}
6696
6697// Checks that the upload data added in AddChunksToUpload() was echoed back from
6698// the server.
6699void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6700 // This should match the chunks sent by AddChunksToUpload().
6701 const std::string expected_data =
6702 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6703
maksim.sisovb53724b52016-09-16 05:30:506704 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6705 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536706
6707 EXPECT_FALSE(d->received_data_before_response());
6708
6709 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6710 EXPECT_EQ(expected_data, d->data_received());
6711}
6712
6713} // namespace
6714
[email protected]316c1e5e2012-09-12 15:17:446715TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556716 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446717
6718 TestDelegate d;
6719 {
Ryan Sleevib8449e02018-07-15 04:31:076720 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166721 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6722 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366723 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536724 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366725 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536726 upload_data_stream->CreateWriter();
6727 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196728 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536729 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196730 r->Start();
6731 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446732
Wez2a31b222018-06-07 22:07:156733 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446734
[email protected]f7022f32014-08-21 16:32:196735 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446736 }
6737}
6738
[email protected]329b68b2012-11-14 17:54:276739TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556740 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276741
6742 TestDelegate d;
6743 {
Ryan Sleevib8449e02018-07-15 04:31:076744 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166745 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6746 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366747 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536748 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366749 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536750 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046751 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196752 r->set_method("POST");
6753 r->Start();
6754 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536755 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156756 d.RunUntilComplete();
[email protected]329b68b2012-11-14 17:54:276757
[email protected]f7022f32014-08-21 16:32:196758 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276759 }
6760}
6761
Asanka Herathf05753e2018-08-16 17:38:206762TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556763 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446764
6765 TestDelegate d;
6766 {
Ryan Sleevib8449e02018-07-15 04:31:076767 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166768 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6769 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366770 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536771 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366772 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536773 upload_data_stream->CreateWriter();
6774 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196775 r->set_method("POST");
6776 r->Start();
6777 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446778
Asanka Herathf05753e2018-08-16 17:38:206779 // Pump messages until we start sending headers..
[email protected]255620da2013-08-19 13:14:296780 base::RunLoop().RunUntilIdle();
Asanka Herathf05753e2018-08-16 17:38:206781
6782 // And now wait for completion.
6783 base::RunLoop run_loop;
6784 d.set_on_complete(run_loop.QuitClosure());
mmenke56b0cbb912016-03-28 21:34:536785 AddDataToUpload(writer.get());
Asanka Herathf05753e2018-08-16 17:38:206786 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:446787
[email protected]f7022f32014-08-21 16:32:196788 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446789 }
6790}
6791
6792TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556793 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446794
6795 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076796 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166797 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6798 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196799 req->Start();
Wez2a31b222018-06-07 22:07:156800 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446801
[email protected]f7022f32014-08-21 16:32:196802 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446803
6804 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196805 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446806
6807 std::string header;
6808 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6809 EXPECT_EQ("private", header);
6810
6811 header.clear();
6812 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6813 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6814
6815 // The response has two "X-Multiple-Entries" headers.
6816 // This verfies our output has them concatenated together.
6817 header.clear();
6818 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6819 EXPECT_EQ("a, b", header);
6820}
6821
tommycli59a63432015-11-06 00:10:556822// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6823// security state. (see http://crbug.com/550977).
6824#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466825TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556826 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6827 https_test_server.SetSSLConfig(
6828 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6829 https_test_server.ServeFilesFromSourceDirectory(
6830 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466831 ASSERT_TRUE(https_test_server.Start());
6832
tommycli59a63432015-11-06 00:10:556833 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466834 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076835 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166836 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6837 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196838 request->Start();
Wez2a31b222018-06-07 22:07:156839 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466840
6841 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076842 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406843 TransportSecurityState::STSState sts_state;
6844 TransportSecurityState::PKPState pkp_state;
6845 EXPECT_TRUE(
6846 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6847 EXPECT_FALSE(
6848 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6849 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6850 sts_state.upgrade_mode);
6851 EXPECT_TRUE(sts_state.include_subdomains);
6852 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036853#if defined(OS_ANDROID)
6854 // Android's CertVerifyProc does not (yet) handle pins.
6855#else
martijnc0d6b622015-06-30 19:14:406856 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036857#endif
[email protected]37fd55fb2013-06-29 13:13:276858}
6859
estarka5da76702015-04-09 04:00:166860TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556861 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6862 https_test_server.ServeFilesFromSourceDirectory(
6863 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166864 ASSERT_TRUE(https_test_server.Start());
6865 // Make sure this test fails if the test server is changed to not
6866 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556867 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6868 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166869
6870 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076871 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166872 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6873 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166874 request->Start();
Wez2a31b222018-06-07 22:07:156875 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:166876 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076877 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406878 TransportSecurityState::STSState sts_state;
6879 EXPECT_FALSE(
6880 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166881}
6882
estark06e0dac2015-08-07 21:56:016883namespace {
Martijn Croonenb1383da2017-10-11 11:56:356884const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
Matt Mueller230996f12018-10-22 19:39:446885const char kPKPReportUri[] = "http://report-uri.preloaded.test/pkp";
6886const char kPKPHost[] = "with-report-uri-pkp.preloaded.test";
estark06e0dac2015-08-07 21:56:016887} // namespace
6888
Matt Mueller230996f12018-10-22 19:39:446889// Tests that reports get sent on PKP violations when a report-uri is set.
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516890TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
Matt Mueller230996f12018-10-22 19:39:446891 GURL report_uri(kPKPReportUri);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516892 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6893 https_test_server.SetSSLConfig(
6894 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6895 https_test_server.ServeFilesFromSourceDirectory(
6896 base::FilePath(kTestFilePath));
6897 ASSERT_TRUE(https_test_server.Start());
6898
Matt Mueller230996f12018-10-22 19:39:446899 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016900
6901 // Set up a pin for |test_server_hostname|.
6902 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446903 security_state.EnableStaticPinsForTesting();
6904 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016905
6906 MockCertificateReportSender mock_report_sender;
6907 security_state.SetReportSender(&mock_report_sender);
6908
6909 // Set up a MockCertVerifier to trigger a violation of the previously
6910 // set pin.
6911 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6912 ASSERT_TRUE(cert);
6913
6914 MockCertVerifier cert_verifier;
6915 CertVerifyResult verify_result;
6916 verify_result.verified_cert = cert;
6917 verify_result.is_issued_by_known_root = true;
6918 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446919 ASSERT_TRUE(
6920 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016921 verify_result.public_key_hashes.push_back(hash3);
6922 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6923
6924 TestNetworkDelegate network_delegate;
6925 TestURLRequestContext context(true);
6926 context.set_transport_security_state(&security_state);
6927 context.set_network_delegate(&network_delegate);
6928 context.set_cert_verifier(&cert_verifier);
6929 context.Init();
6930
6931 // Now send a request to trigger the violation.
6932 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366933 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446934 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166935 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016936 violating_request->Start();
Wez2a31b222018-06-07 22:07:156937 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016938
6939 // Check that a report was sent.
6940 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6941 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446942 EXPECT_EQ("application/json; charset=utf-8",
6943 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366944 std::unique_ptr<base::Value> value(
Lei Zhanga8b4c5fb2019-02-16 03:02:036945 base::JSONReader::ReadDeprecated(mock_report_sender.latest_report()));
estark06e0dac2015-08-07 21:56:016946 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086947 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016948 base::DictionaryValue* report_dict;
6949 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6950 std::string report_hostname;
6951 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6952 EXPECT_EQ(test_server_hostname, report_hostname);
6953}
6954
Matt Mueller230996f12018-10-22 19:39:446955// Tests that reports do not get sent on requests to static pkp hosts that
6956// don't have pin violations.
6957TEST_F(URLRequestTestHTTP, ProcessPKPWithNoViolation) {
tommycli59a63432015-11-06 00:10:556958 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6959 https_test_server.SetSSLConfig(
6960 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6961 https_test_server.ServeFilesFromSourceDirectory(
6962 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016963 ASSERT_TRUE(https_test_server.Start());
6964
Matt Mueller230996f12018-10-22 19:39:446965 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016966
6967 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446968 security_state.EnableStaticPinsForTesting();
6969 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016970 MockCertificateReportSender mock_report_sender;
6971 security_state.SetReportSender(&mock_report_sender);
6972
Matt Mueller230996f12018-10-22 19:39:446973 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6974 ASSERT_TRUE(cert);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516975 MockCertVerifier mock_cert_verifier;
Matt Mueller230996f12018-10-22 19:39:446976 CertVerifyResult verify_result;
6977 verify_result.verified_cert = cert;
6978 verify_result.is_issued_by_known_root = true;
6979 HashValue hash;
6980 // The expected value of GoodPin1 used by |test_default::kHSTSSource|.
6981 ASSERT_TRUE(
6982 hash.FromString("sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY="));
6983 verify_result.public_key_hashes.push_back(hash);
6984 mock_cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6985
6986 TestNetworkDelegate network_delegate;
estark06e0dac2015-08-07 21:56:016987 TestURLRequestContext context(true);
6988 context.set_transport_security_state(&security_state);
6989 context.set_network_delegate(&network_delegate);
6990 context.set_cert_verifier(&mock_cert_verifier);
estark06e0dac2015-08-07 21:56:016991 context.Init();
6992
6993 // Now send a request that does not trigger the violation.
6994 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366995 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446996 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166997 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016998 request->Start();
Wez2a31b222018-06-07 22:07:156999 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:017000
Matt Mueller230996f12018-10-22 19:39:447001 // Check that the request succeeded, a report was not sent and the pkp was
7002 // not bypassed.
7003 EXPECT_EQ(OK, d.request_status());
estark06e0dac2015-08-07 21:56:017004 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
7005 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
Matt Mueller230996f12018-10-22 19:39:447006 TransportSecurityState::STSState sts_state;
martijnc0d6b622015-06-30 19:14:407007 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:447008 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
7009 &sts_state, &pkp_state));
7010 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
7011 EXPECT_FALSE(request->ssl_info().pkp_bypassed);
estarka5da76702015-04-09 04:00:167012}
7013
dadriandf302c42016-06-10 18:48:597014TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
7015 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7016 https_test_server.SetSSLConfig(
7017 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7018 https_test_server.ServeFilesFromSourceDirectory(
7019 base::FilePath(kTestFilePath));
7020 ASSERT_TRUE(https_test_server.Start());
7021
7022 // Set up a MockCertVerifier to be a local root that violates the pin
7023 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7024 ASSERT_TRUE(cert);
7025
7026 MockCertVerifier cert_verifier;
7027 CertVerifyResult verify_result;
7028 verify_result.verified_cert = cert;
7029 verify_result.is_issued_by_known_root = false;
7030 HashValue hash;
7031 ASSERT_TRUE(
7032 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
7033 verify_result.public_key_hashes.push_back(hash);
7034 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
dadriandf302c42016-06-10 18:48:597035
Matt Mueller230996f12018-10-22 19:39:447036 std::string test_server_hostname = kPKPHost;
dadriandf302c42016-06-10 18:48:597037
Matt Mueller230996f12018-10-22 19:39:447038 // Set up PKP
dadriandf302c42016-06-10 18:48:597039 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:447040 security_state.EnableStaticPinsForTesting();
7041 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7042 MockCertificateReportSender mock_report_sender;
7043 security_state.SetReportSender(&mock_report_sender);
dadriandf302c42016-06-10 18:48:597044
7045 TestNetworkDelegate network_delegate;
7046 TestURLRequestContext context(true);
7047 context.set_transport_security_state(&security_state);
7048 context.set_network_delegate(&network_delegate);
7049 context.set_cert_verifier(&cert_verifier);
7050 context.Init();
7051
7052 TestDelegate d;
7053 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:447054 https_test_server.GetURL(test_server_hostname, "/simple.html"),
7055 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:597056 request->Start();
Wez2a31b222018-06-07 22:07:157057 d.RunUntilComplete();
dadriandf302c42016-06-10 18:48:597058
Matt Mueller230996f12018-10-22 19:39:447059 // Check that the request succeeded, a report was not sent and the PKP was
7060 // bypassed.
7061 EXPECT_EQ(OK, d.request_status());
7062 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
7063 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
7064 TransportSecurityState::STSState sts_state;
dadriandf302c42016-06-10 18:48:597065 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:447066 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
7067 &sts_state, &pkp_state));
7068 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
dadriandf302c42016-06-10 18:48:597069 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
7070}
7071
[email protected]242d8562012-10-30 21:20:467072TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:557073 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7074 https_test_server.SetSSLConfig(
7075 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7076 https_test_server.ServeFilesFromSourceDirectory(
7077 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:467078 ASSERT_TRUE(https_test_server.Start());
7079
tommycli59a63432015-11-06 00:10:557080 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167081
[email protected]242d8562012-10-30 21:20:467082 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077083 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557084 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167085 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197086 request->Start();
Wez2a31b222018-06-07 22:07:157087 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:467088
7089 // We should have set parameters from the first header, not the second.
7090 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:077091 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:407092 TransportSecurityState::STSState sts_state;
7093 EXPECT_TRUE(
7094 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7095 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7096 sts_state.upgrade_mode);
7097 EXPECT_FALSE(sts_state.include_subdomains);
7098 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:467099}
7100
estark1614475f2016-03-10 03:46:477101// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
7102// called.
7103class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
7104 public:
7105 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:277106 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:477107
7108 void OnExpectCTFailed(const HostPortPair& host_port_pair,
7109 const GURL& report_uri,
estarkae028b462017-06-20 23:25:017110 base::Time expiration,
estarkbf1b52962017-05-05 17:05:257111 const X509Certificate* validated_certificate_chain,
7112 const X509Certificate* served_certificate_chain,
7113 const SignedCertificateTimestampAndStatusList&
7114 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:477115 num_failures_++;
7116 }
7117
7118 uint32_t num_failures() { return num_failures_; }
7119
7120 private:
7121 uint32_t num_failures_;
7122};
7123
Emily Stark627238f2017-11-29 03:29:547124// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:477125// for every certificate.
7126class MockCTPolicyEnforcer : public CTPolicyEnforcer {
7127 public:
7128 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:547129 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:277130 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:477131
Emily Stark627238f2017-11-29 03:29:547132 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:477133 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:237134 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:207135 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:477136 return default_result_;
7137 }
7138
Emily Stark627238f2017-11-29 03:29:547139 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:477140 default_result_ = default_result;
7141 }
7142
7143 private:
Emily Stark627238f2017-11-29 03:29:547144 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:477145};
7146
Emily Stark4cfecf072017-08-08 01:05:517147// Tests that Expect CT headers for the preload list are processed correctly.
7148TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:357149 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7150
estark1614475f2016-03-10 03:46:477151 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7152 https_test_server.SetSSLConfig(
7153 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7154 https_test_server.ServeFilesFromSourceDirectory(
7155 base::FilePath(kTestFilePath));
7156 ASSERT_TRUE(https_test_server.Start());
7157
7158 MockExpectCTReporter reporter;
7159 TransportSecurityState transport_security_state;
7160 transport_security_state.enable_static_expect_ct_ = true;
7161 transport_security_state.SetExpectCTReporter(&reporter);
7162
7163 // Set up a MockCertVerifier to accept the certificate that the server sends.
7164 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7165 ASSERT_TRUE(cert);
7166 MockCertVerifier cert_verifier;
7167 CertVerifyResult verify_result;
7168 verify_result.verified_cert = cert;
7169 verify_result.is_issued_by_known_root = true;
7170 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7171
rsleevi22cae1672016-12-28 01:53:367172 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
7173 // CT violation.
7174 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:477175 MockCTPolicyEnforcer ct_policy_enforcer;
7176 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547177 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:477178
7179 TestNetworkDelegate network_delegate;
7180 // Use a MockHostResolver (which by default maps all hosts to
7181 // 127.0.0.1) so that the request can be sent to a site on the Expect
7182 // CT preload list.
7183 MockHostResolver host_resolver;
7184 TestURLRequestContext context(true);
7185 context.set_host_resolver(&host_resolver);
7186 context.set_transport_security_state(&transport_security_state);
7187 context.set_network_delegate(&network_delegate);
7188 context.set_cert_verifier(&cert_verifier);
7189 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:467190 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:477191 context.Init();
7192
7193 // Now send a request to trigger the violation.
7194 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:517195 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:477196 GURL::Replacements replace_host;
7197 replace_host.SetHostStr(kExpectCTStaticHostname);
7198 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:167199 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
7200 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:477201 violating_request->Start();
Wez2a31b222018-06-07 22:07:157202 d.RunUntilComplete();
estark1614475f2016-03-10 03:46:477203
7204 EXPECT_EQ(1u, reporter.num_failures());
7205}
Emily Stark4cfecf072017-08-08 01:05:517206
7207// Tests that Expect CT HTTP headers are processed correctly.
7208TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
7209 base::test::ScopedFeatureList feature_list;
7210 feature_list.InitAndEnableFeature(
7211 TransportSecurityState::kDynamicExpectCTFeature);
7212
7213 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7214 https_test_server.SetSSLConfig(
7215 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7216 https_test_server.ServeFilesFromSourceDirectory(
7217 base::FilePath(kTestFilePath));
7218 ASSERT_TRUE(https_test_server.Start());
7219
7220 MockExpectCTReporter reporter;
7221 TransportSecurityState transport_security_state;
7222 transport_security_state.SetExpectCTReporter(&reporter);
7223
7224 // Set up a MockCertVerifier to accept the certificate that the server sends.
7225 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7226 ASSERT_TRUE(cert);
7227 MockCertVerifier cert_verifier;
7228 CertVerifyResult verify_result;
7229 verify_result.verified_cert = cert;
7230 verify_result.is_issued_by_known_root = true;
7231 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7232
7233 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7234 // compliance.
7235 DoNothingCTVerifier ct_verifier;
7236 MockCTPolicyEnforcer ct_policy_enforcer;
7237 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547238 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517239
7240 TestNetworkDelegate network_delegate;
7241 // Use a MockHostResolver (which by default maps all hosts to
7242 // 127.0.0.1).
7243 MockHostResolver host_resolver;
7244 TestURLRequestContext context(true);
7245 context.set_host_resolver(&host_resolver);
7246 context.set_transport_security_state(&transport_security_state);
7247 context.set_network_delegate(&network_delegate);
7248 context.set_cert_verifier(&cert_verifier);
7249 context.set_cert_transparency_verifier(&ct_verifier);
7250 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7251 context.Init();
7252
7253 // Now send a request to trigger the header processing.
7254 TestDelegate d;
7255 GURL url = https_test_server.GetURL("/expect-ct-header.html");
7256 std::unique_ptr<URLRequest> request(context.CreateRequest(
7257 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7258 request->Start();
Wez2a31b222018-06-07 22:07:157259 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517260
7261 TransportSecurityState::ExpectCTState state;
7262 ASSERT_TRUE(
7263 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7264 EXPECT_TRUE(state.enforce);
7265 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7266}
7267
7268// Tests that if multiple Expect CT HTTP headers are sent, they are all
7269// processed.
7270TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
7271 base::test::ScopedFeatureList feature_list;
7272 feature_list.InitAndEnableFeature(
7273 TransportSecurityState::kDynamicExpectCTFeature);
7274
7275 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7276 https_test_server.SetSSLConfig(
7277 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7278 https_test_server.ServeFilesFromSourceDirectory(
7279 base::FilePath(kTestFilePath));
7280 ASSERT_TRUE(https_test_server.Start());
7281
7282 MockExpectCTReporter reporter;
7283 TransportSecurityState transport_security_state;
7284 transport_security_state.SetExpectCTReporter(&reporter);
7285
7286 // Set up a MockCertVerifier to accept the certificate that the server sends.
7287 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7288 ASSERT_TRUE(cert);
7289 MockCertVerifier cert_verifier;
7290 CertVerifyResult verify_result;
7291 verify_result.verified_cert = cert;
7292 verify_result.is_issued_by_known_root = true;
7293 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7294
7295 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7296 // compliance.
7297 DoNothingCTVerifier ct_verifier;
7298 MockCTPolicyEnforcer ct_policy_enforcer;
7299 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547300 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517301
7302 TestNetworkDelegate network_delegate;
7303 // Use a MockHostResolver (which by default maps all hosts to
7304 // 127.0.0.1).
7305 MockHostResolver host_resolver;
7306 TestURLRequestContext context(true);
7307 context.set_host_resolver(&host_resolver);
7308 context.set_transport_security_state(&transport_security_state);
7309 context.set_network_delegate(&network_delegate);
7310 context.set_cert_verifier(&cert_verifier);
7311 context.set_cert_transparency_verifier(&ct_verifier);
7312 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7313 context.Init();
7314
7315 // Now send a request to trigger the header processing.
7316 TestDelegate d;
7317 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7318 std::unique_ptr<URLRequest> request(context.CreateRequest(
7319 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7320 request->Start();
Wez2a31b222018-06-07 22:07:157321 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517322
7323 TransportSecurityState::ExpectCTState state;
7324 ASSERT_TRUE(
7325 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7326 EXPECT_TRUE(state.enforce);
7327 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7328}
7329
mmenkefd9d15c2017-06-29 13:45:547330#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477331
Lily Chenfec60d92019-01-24 01:16:427332#if BUILDFLAG(ENABLE_REPORTING)
7333
Lily Chend3930e72019-03-01 19:31:117334TEST_F(URLRequestTestHTTP, NetworkErrorLogging_DontReportIfNetworkNotAccessed) {
7335 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7336 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7337 ASSERT_TRUE(https_test_server.Start());
7338 GURL request_url = https_test_server.GetURL("/cachetime");
7339
7340 TestNetworkErrorLoggingService nel_service;
7341 TestURLRequestContext context(true);
7342 context.set_network_error_logging_service(&nel_service);
7343 context.Init();
7344
7345 // Populate the cache.
7346 TestDelegate d;
7347 std::unique_ptr<URLRequest> request(context.CreateRequest(
7348 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7349 request->Start();
7350 d.RunUntilComplete();
7351
7352 ASSERT_EQ(1u, nel_service.errors().size());
7353 const TestNetworkErrorLoggingService::RequestDetails& error =
7354 nel_service.errors()[0];
7355 EXPECT_EQ(request_url, error.uri);
7356 EXPECT_EQ(200, error.status_code);
7357 EXPECT_EQ(OK, error.type);
7358
7359 request = context.CreateRequest(request_url, DEFAULT_PRIORITY, &d,
7360 TRAFFIC_ANNOTATION_FOR_TESTS);
7361 request->Start();
7362 d.RunUntilComplete();
7363
7364 EXPECT_FALSE(request->response_info().network_accessed);
7365 EXPECT_TRUE(request->response_info().was_cached);
7366 // No additional NEL report was generated.
7367 EXPECT_EQ(1u, nel_service.errors().size());
7368}
7369
Lily Chenfec60d92019-01-24 01:16:427370TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicSuccess) {
7371 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7372 https_test_server.ServeFilesFromSourceDirectory(
7373 base::FilePath(kTestFilePath));
7374 ASSERT_TRUE(https_test_server.Start());
7375 GURL request_url = https_test_server.GetURL("/simple.html");
7376
7377 TestNetworkErrorLoggingService nel_service;
7378 TestURLRequestContext context(true);
7379 context.set_network_error_logging_service(&nel_service);
7380 context.Init();
7381
7382 TestDelegate d;
7383 std::unique_ptr<URLRequest> request(context.CreateRequest(
7384 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7385 request->Start();
7386 d.RunUntilComplete();
7387
7388 ASSERT_EQ(1u, nel_service.errors().size());
7389 const TestNetworkErrorLoggingService::RequestDetails& error =
7390 nel_service.errors()[0];
7391 EXPECT_EQ(request_url, error.uri);
7392 EXPECT_EQ(200, error.status_code);
7393 EXPECT_EQ(OK, error.type);
7394}
7395
7396TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicError) {
7397 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7398 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7399 ASSERT_TRUE(https_test_server.Start());
7400 GURL request_url = https_test_server.GetURL("/close-socket");
7401
7402 TestNetworkErrorLoggingService nel_service;
7403 TestURLRequestContext context(true);
7404 context.set_network_error_logging_service(&nel_service);
7405 context.Init();
7406
7407 TestDelegate d;
7408 std::unique_ptr<URLRequest> request(context.CreateRequest(
7409 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7410 request->Start();
7411 d.RunUntilComplete();
7412
7413 ASSERT_EQ(1u, nel_service.errors().size());
7414 const TestNetworkErrorLoggingService::RequestDetails& error =
7415 nel_service.errors()[0];
7416 EXPECT_EQ(request_url, error.uri);
7417 EXPECT_EQ(0, error.status_code);
7418 EXPECT_EQ(ERR_EMPTY_RESPONSE, error.type);
7419}
7420
7421TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Redirect) {
7422 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7423 https_test_server.ServeFilesFromSourceDirectory(
7424 base::FilePath(kTestFilePath));
7425 ASSERT_TRUE(https_test_server.Start());
7426 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7427 GURL redirect_url = https_test_server.GetURL("/with-headers.html");
7428
7429 TestNetworkErrorLoggingService nel_service;
7430 TestURLRequestContext context(true);
7431 context.set_network_error_logging_service(&nel_service);
7432 context.Init();
7433
7434 TestDelegate d;
7435 std::unique_ptr<URLRequest> request(context.CreateRequest(
7436 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7437 request->Start();
7438 d.RunUntilComplete();
7439
7440 ASSERT_EQ(2u, nel_service.errors().size());
7441 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7442 nel_service.errors()[0];
7443 EXPECT_EQ(request_url, error1.uri);
7444 EXPECT_EQ(302, error1.status_code);
7445 EXPECT_EQ(OK, error1.type);
7446 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7447 nel_service.errors()[1];
7448 EXPECT_EQ(redirect_url, error2.uri);
7449 EXPECT_EQ(200, error2.status_code);
7450 EXPECT_EQ(OK, error2.type);
7451}
7452
Lily Chend3930e72019-03-01 19:31:117453TEST_F(URLRequestTestHTTP, NetworkErrorLogging_RedirectWithoutLocationHeader) {
7454 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7455 https_test_server.ServeFilesFromSourceDirectory(
7456 base::FilePath(kTestFilePath));
7457 ASSERT_TRUE(https_test_server.Start());
7458 GURL request_url = https_test_server.GetURL("/308-without-location-header");
7459
7460 TestNetworkErrorLoggingService nel_service;
7461 TestURLRequestContext context(true);
7462 context.set_network_error_logging_service(&nel_service);
7463 context.Init();
7464
7465 TestDelegate d;
7466 std::unique_ptr<URLRequest> request(context.CreateRequest(
7467 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7468 request->Start();
7469 d.RunUntilComplete();
7470
7471 ASSERT_EQ(1u, nel_service.errors().size());
7472 const TestNetworkErrorLoggingService::RequestDetails& error =
7473 nel_service.errors()[0];
7474 EXPECT_EQ(request_url, error.uri);
7475 EXPECT_EQ(308, error.status_code);
7476 // The body of the response was successfully read.
7477 EXPECT_EQ(OK, error.type);
7478}
7479
Lily Chenfec60d92019-01-24 01:16:427480TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Auth) {
7481 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7482 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7483 ASSERT_TRUE(https_test_server.Start());
7484 GURL request_url = https_test_server.GetURL("/auth-basic");
7485
7486 TestNetworkErrorLoggingService nel_service;
7487 TestURLRequestContext context(true);
7488 context.set_network_error_logging_service(&nel_service);
7489 context.Init();
7490
7491 TestDelegate d;
7492 d.set_credentials(AuthCredentials(kUser, kSecret));
7493 std::unique_ptr<URLRequest> request(context.CreateRequest(
7494 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7495 request->Start();
7496 d.RunUntilComplete();
7497
7498 ASSERT_EQ(2u, nel_service.errors().size());
7499 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7500 nel_service.errors()[0];
7501 EXPECT_EQ(request_url, error1.uri);
7502 EXPECT_EQ(401, error1.status_code);
7503 EXPECT_EQ(OK, error1.type);
7504 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7505 nel_service.errors()[1];
7506 EXPECT_EQ(request_url, error2.uri);
7507 EXPECT_EQ(200, error2.status_code);
7508 EXPECT_EQ(OK, error2.type);
7509}
7510
Lily Chend3930e72019-03-01 19:31:117511TEST_F(URLRequestTestHTTP, NetworkErrorLogging_304Response) {
7512 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7513 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7514 ASSERT_TRUE(https_test_server.Start());
7515 GURL request_url = https_test_server.GetURL("/auth-basic");
7516
7517 TestNetworkErrorLoggingService nel_service;
7518 TestURLRequestContext context(true);
7519 context.set_network_error_logging_service(&nel_service);
7520 context.Init();
7521
7522 // populate the cache
7523 {
7524 TestDelegate d;
7525 d.set_credentials(AuthCredentials(kUser, kSecret));
7526 std::unique_ptr<URLRequest> r(context.CreateRequest(
7527 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7528 r->Start();
7529 d.RunUntilComplete();
7530 }
7531 ASSERT_EQ(2u, nel_service.errors().size());
7532 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7533 nel_service.errors()[0];
7534 EXPECT_EQ(request_url, error1.uri);
7535 EXPECT_EQ(401, error1.status_code);
7536 EXPECT_EQ(OK, error1.type);
7537 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7538 nel_service.errors()[1];
7539 EXPECT_EQ(request_url, error2.uri);
7540 EXPECT_EQ(200, error2.status_code);
7541 EXPECT_EQ(OK, error2.type);
7542
7543 // repeat request with end-to-end validation. since auth-basic results in a
7544 // cachable page, we expect this test to result in a 304. in which case, the
7545 // response should be fetched from the cache.
7546 {
7547 TestDelegate d;
7548 d.set_credentials(AuthCredentials(kUser, kSecret));
7549 std::unique_ptr<URLRequest> r(context.CreateRequest(
7550 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7551 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7552 r->Start();
7553 d.RunUntilComplete();
7554
7555 // Should be the same cached document.
7556 EXPECT_TRUE(r->was_cached());
7557 }
7558 ASSERT_EQ(3u, nel_service.errors().size());
7559 const TestNetworkErrorLoggingService::RequestDetails& error3 =
7560 nel_service.errors()[2];
7561 EXPECT_EQ(request_url, error3.uri);
7562 EXPECT_EQ(304, error3.status_code);
7563 EXPECT_EQ(OK, error3.type);
7564}
7565
7566TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelInResponseStarted) {
Lily Chenfec60d92019-01-24 01:16:427567 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7568 https_test_server.ServeFilesFromSourceDirectory(
7569 base::FilePath(kTestFilePath));
7570 ASSERT_TRUE(https_test_server.Start());
7571 GURL request_url = https_test_server.GetURL("/simple.html");
7572
7573 TestNetworkErrorLoggingService nel_service;
7574 TestURLRequestContext context(true);
7575 context.set_network_error_logging_service(&nel_service);
7576 context.Init();
7577
7578 TestDelegate d;
7579 d.set_cancel_in_response_started(true);
7580 std::unique_ptr<URLRequest> request(context.CreateRequest(
7581 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7582 request->Start();
7583 d.RunUntilComplete();
7584
7585 ASSERT_EQ(1u, nel_service.errors().size());
7586 const TestNetworkErrorLoggingService::RequestDetails& error =
7587 nel_service.errors()[0];
7588 EXPECT_EQ(request_url, error.uri);
7589 EXPECT_EQ(200, error.status_code);
Lily Chend3930e72019-03-01 19:31:117590 // Headers were received and the body should have been read but was not.
7591 EXPECT_EQ(ERR_ABORTED, error.type);
7592}
7593
7594TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelOnDataReceived) {
7595 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7596 https_test_server.ServeFilesFromSourceDirectory(
7597 base::FilePath(kTestFilePath));
7598 ASSERT_TRUE(https_test_server.Start());
7599 GURL request_url = https_test_server.GetURL("/simple.html");
7600
7601 TestNetworkErrorLoggingService nel_service;
7602 TestURLRequestContext context(true);
7603 context.set_network_error_logging_service(&nel_service);
7604 context.Init();
7605
7606 TestDelegate d;
7607 d.set_cancel_in_received_data(true);
7608 std::unique_ptr<URLRequest> request(context.CreateRequest(
7609 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7610 request->Start();
7611 d.RunUntilComplete();
7612
7613 ASSERT_EQ(1u, nel_service.errors().size());
7614 const TestNetworkErrorLoggingService::RequestDetails& error =
7615 nel_service.errors()[0];
7616 EXPECT_EQ(request_url, error.uri);
7617 EXPECT_EQ(200, error.status_code);
7618 // Data was received but the body was not completely read.
7619 EXPECT_EQ(ERR_ABORTED, error.type);
7620}
7621
7622TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelRedirect) {
7623 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7624 https_test_server.ServeFilesFromSourceDirectory(
7625 base::FilePath(kTestFilePath));
7626 ASSERT_TRUE(https_test_server.Start());
7627 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7628
7629 TestNetworkErrorLoggingService nel_service;
7630 TestURLRequestContext context(true);
7631 context.set_network_error_logging_service(&nel_service);
7632 context.Init();
7633
7634 TestDelegate d;
7635 d.set_cancel_in_received_redirect(true);
7636 std::unique_ptr<URLRequest> request(context.CreateRequest(
7637 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7638 request->Start();
7639 d.RunUntilComplete();
7640
7641 ASSERT_EQ(1u, nel_service.errors().size());
7642 const TestNetworkErrorLoggingService::RequestDetails& error =
7643 nel_service.errors()[0];
7644 EXPECT_EQ(request_url, error.uri);
7645 EXPECT_EQ(302, error.status_code);
7646 // A valid HTTP response was received, even though the request was cancelled.
Lily Chenfec60d92019-01-24 01:16:427647 EXPECT_EQ(OK, error.type);
7648}
7649
7650#endif // BUILDFLAG(ENABLE_REPORTING)
7651
[email protected]316c1e5e2012-09-12 15:17:447652TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557653 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447654
7655 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077656 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557657 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167658 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197659 req->Start();
Wez2a31b222018-06-07 22:07:157660 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447661
7662 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197663 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447664 EXPECT_EQ("text/html", mime_type);
7665
7666 std::string charset;
[email protected]f7022f32014-08-21 16:32:197667 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447668 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197669 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447670}
7671
[email protected]02494ec2014-05-07 15:05:297672TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347673 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347674 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347675 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027676 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347677
7678 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507679 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347680}
7681
brettwa1228ebb2016-10-28 03:51:347682#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297683TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7684 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7685 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457686 FileProtocolHandler file_protocol_handler(
7687 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297688 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7689
7690 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507691 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297692}
7693
[email protected]588614c22013-08-16 00:09:027694TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557695 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447696
7697 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077698 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557699 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167700 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197701 req->Start();
Wez2a31b222018-06-07 22:07:157702 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447703
maksim.sisovb53724b52016-09-16 05:30:507704 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307705
7706 // The redirect should have been rejected before reporting it to the caller.
7707 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447708}
brettwa1228ebb2016-10-28 03:51:347709#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447710
[email protected]588614c22013-08-16 00:09:027711TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557712 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027713
7714 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077715 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557716 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167717 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197718 req->Start();
Wez2a31b222018-06-07 22:07:157719 d.RunUntilComplete();
[email protected]588614c22013-08-16 00:09:027720
maksim.sisovb53724b52016-09-16 05:30:507721 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307722
7723 // The redirect should have been rejected before reporting it to the
7724 // caller. See https://crbug.com/723796
7725 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027726}
7727
davidbend894710b2017-06-06 19:28:307728// Test that redirects to invalid URLs are rejected. See
7729// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447730TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557731 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447732
7733 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077734 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557735 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167736 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197737 req->Start();
Wez2a31b222018-06-07 22:07:157738 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447739
davidbend894710b2017-06-06 19:28:307740 EXPECT_EQ(1, d.response_started_count());
7741 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7742
7743 // The redirect should have been rejected before reporting it to the caller.
7744 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447745}
7746
[email protected]e50efea2014-03-24 18:41:007747// Make sure redirects are cached, despite not reading their bodies.
7748TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557749 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007750 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557751 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007752
7753 {
7754 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077755 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167756 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197757 req->Start();
Wez2a31b222018-06-07 22:07:157758 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507759 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007760 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557761 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007762 }
7763
7764 {
7765 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077766 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167767 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197768 req->Start();
Wez0e717112018-06-18 23:09:227769 d.RunUntilRedirect();
[email protected]e50efea2014-03-24 18:41:007770
7771 EXPECT_EQ(1, d.received_redirect_count());
7772 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197773 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007774
Arthur Sonzognib8465ff72019-01-04 18:44:357775 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7776 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157777 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007778 EXPECT_EQ(1, d.received_redirect_count());
7779 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507780 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557781 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007782 }
7783}
7784
7785// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7786// when the headers are read, since the body won't have been read.
7787TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557788 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007789 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557790 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007791
7792 {
7793 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557794 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007795 default_network_delegate_.set_redirect_on_headers_received_url(
7796 redirect_to_url);
7797
7798 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077799 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167800 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197801 req->Start();
Wez2a31b222018-06-07 22:07:157802 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507803 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007804 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197805 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007806 }
7807
7808 {
7809 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077810 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167811 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197812 req->Start();
Wez2a31b222018-06-07 22:07:157813 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007814
maksim.sisovb53724b52016-09-16 05:30:507815 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197816 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007817 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197818 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007819 }
7820}
7821
[email protected]5f714132014-03-26 10:41:167822// Tests that redirection to an unsafe URL is allowed when it has been marked as
7823// safe.
Ryan Sleevia9d6aa62019-07-26 13:32:187824TEST_F(URLRequestTestHTTP, UnsafeRedirectToAllowedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557825 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167826
7827 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7828 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7829 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7830
7831 TestDelegate d;
7832 {
Ryan Sleevib8449e02018-07-15 04:31:077833 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167834 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7835 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167836
[email protected]f7022f32014-08-21 16:32:197837 r->Start();
Wez2a31b222018-06-07 22:07:157838 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167839
maksim.sisovb53724b52016-09-16 05:30:507840 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197841 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197842 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167843 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7844 }
7845}
7846
7847// Tests that a redirect to a different unsafe URL is blocked, even after adding
Ryan Sleevia9d6aa62019-07-26 13:32:187848// some other URL to the allowlist.
[email protected]5f714132014-03-26 10:41:167849TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557850 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167851
7852 GURL unsafe_url("data:text/html,something");
7853 GURL different_unsafe_url("data:text/html,something-else");
7854 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7855 default_network_delegate_.set_allowed_unsafe_redirect_url(
7856 different_unsafe_url);
7857
7858 TestDelegate d;
7859 {
Ryan Sleevib8449e02018-07-15 04:31:077860 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167861 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7862 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167863
[email protected]f7022f32014-08-21 16:32:197864 r->Start();
Wez2a31b222018-06-07 22:07:157865 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167866
maksim.sisovb53724b52016-09-16 05:30:507867 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307868
7869 // The redirect should have been rejected before reporting it to the caller.
7870 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167871 }
7872}
7873
[email protected]5f714132014-03-26 10:41:167874// Redirects from an URL with fragment to an unsafe URL with fragment should
7875// be allowed, and the reference fragment of the target URL should be preserved.
7876TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557877 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167878
tommycli59a63432015-11-06 00:10:557879 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167880 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7881 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7882
7883 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7884 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7885
7886 TestDelegate d;
7887 {
Ryan Sleevib8449e02018-07-15 04:31:077888 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167889 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167890
[email protected]f7022f32014-08-21 16:32:197891 r->Start();
Wez2a31b222018-06-07 22:07:157892 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167893
[email protected]f7022f32014-08-21 16:32:197894 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507895 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197896 EXPECT_EQ(original_url, r->original_url());
7897 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167898 }
7899}
7900
7901// When a delegate has specified a safe redirect URL, but it does not match the
7902// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147903TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557904 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167905
tommycli59a63432015-11-06 00:10:557906 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167907 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557908 GURL redirect_url(http_test_server()->GetURL("/target"));
7909 GURL expected_redirect_url(
7910 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167911
7912 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7913 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7914
7915 TestDelegate d;
7916 {
Ryan Sleevib8449e02018-07-15 04:31:077917 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167918 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167919
[email protected]f7022f32014-08-21 16:32:197920 r->Start();
Wez2a31b222018-06-07 22:07:157921 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167922
[email protected]f7022f32014-08-21 16:32:197923 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507924 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197925 EXPECT_EQ(original_url, r->original_url());
7926 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167927 }
7928}
7929
[email protected]f878230e2014-04-03 15:36:147930// When a delegate has specified a safe redirect URL, assume that the redirect
7931// URL should not be changed. In particular, the reference fragment should not
7932// be modified.
7933TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557934 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147935
tommycli59a63432015-11-06 00:10:557936 GURL original_url(
7937 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147938 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7939
7940 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7941 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7942
7943 TestDelegate d;
7944 {
Ryan Sleevib8449e02018-07-15 04:31:077945 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167946 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147947
[email protected]f7022f32014-08-21 16:32:197948 r->Start();
Wez2a31b222018-06-07 22:07:157949 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147950
[email protected]f7022f32014-08-21 16:32:197951 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507952 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197953 EXPECT_EQ(original_url, r->original_url());
7954 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147955 }
7956}
7957
7958// When a URLRequestRedirectJob is created, the redirection must be followed and
7959// the reference fragment of the target URL must not be modified.
7960TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557961 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147962
tommycli59a63432015-11-06 00:10:557963 GURL original_url(
7964 http_test_server()->GetURL("/original#should-not-be-appended"));
7965 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147966
7967 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077968 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167969 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147970
danakj8522a25b2016-04-16 00:17:367971 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197972 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427973 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7974 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:147975
[email protected]f7022f32014-08-21 16:32:197976 r->Start();
Wez2a31b222018-06-07 22:07:157977 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147978
maksim.sisovb53724b52016-09-16 05:30:507979 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197980 EXPECT_EQ(original_url, r->original_url());
7981 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147982}
7983
lizeb5120f6dc2016-02-19 09:29:447984TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
7985 ASSERT_TRUE(http_test_server()->Start());
7986
7987 const std::string referrer("foobar://totally.legit.referrer");
7988 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077989 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167990 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7991 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:447992 req->SetReferrer(referrer);
7993 req->Start();
Wez2a31b222018-06-07 22:07:157994 d.RunUntilComplete();
lizeb5120f6dc2016-02-19 09:29:447995
7996 EXPECT_EQ(std::string("None"), d.data_received());
7997}
7998
[email protected]316c1e5e2012-09-12 15:17:447999TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:558000 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448001
8002 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078003 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168004 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8005 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198006 req->SetReferrer("http://user:[email protected]/");
8007 req->Start();
Wez2a31b222018-06-07 22:07:158008 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448009
8010 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
8011}
8012
[email protected]99ecf6e2013-04-10 22:46:138013TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:558014 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138015
8016 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078017 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168018 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8019 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198020 req->SetReferrer("http://foo.com/test#fragment");
8021 req->Start();
Wez2a31b222018-06-07 22:07:158022 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138023
8024 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
8025}
8026
8027TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:558028 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138029
8030 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078031 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168032 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8033 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198034 req->SetReferrer("http://foo.com/test#fragment");
8035 req->SetReferrer("");
8036 req->Start();
Wez2a31b222018-06-07 22:07:158037 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138038
8039 EXPECT_EQ(std::string("None"), d.data_received());
8040}
8041
Mike Westfbd44112019-05-08 18:23:378042TEST_F(URLRequestTestHTTP, CapRefererDisabled) {
8043 ASSERT_TRUE(http_test_server()->Start());
8044
8045 // Create a string, and pad it out to ~10k with a very exciting path.
8046 std::string long_referer_header = "http://foo.com/";
8047 long_referer_header.resize(10000, 'a');
8048
8049 // If the feature isn't enabled, a long `referer` will remain long.
8050 TestDelegate d;
Mike West9e3affdd2019-06-07 07:43:578051 base::test::ScopedFeatureList feature_list;
8052 feature_list.InitAndDisableFeature(features::kCapRefererHeaderLength);
Mike Westfbd44112019-05-08 18:23:378053 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8054 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8055 TRAFFIC_ANNOTATION_FOR_TESTS));
8056 req->SetReferrer(long_referer_header);
8057 req->Start();
8058 d.RunUntilComplete();
8059
8060 EXPECT_EQ(long_referer_header, d.data_received());
8061}
8062
8063TEST_F(URLRequestTestHTTP, CapRefererHeaderLengthEnabled) {
8064 ASSERT_TRUE(http_test_server()->Start());
8065
8066 // Create a string, and pad it out to ~10k with a very exciting path.
8067 std::string long_referer_header = "http://foo.com/";
8068 long_referer_header.resize(10000, 'a');
8069
8070 // If the feature is enabled without params, a `referer` longer than 4096
8071 // bytes will be shortened.
8072 {
8073 TestDelegate d;
8074 base::test::ScopedFeatureList feature_list;
8075 feature_list.InitAndEnableFeature(features::kCapRefererHeaderLength);
8076
8077 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8078 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8079 TRAFFIC_ANNOTATION_FOR_TESTS));
8080 req->SetReferrer(long_referer_header);
8081 req->Start();
8082 d.RunUntilComplete();
8083
8084 EXPECT_EQ("http://foo.com/", d.data_received());
8085 }
8086
8087 // If the feature is enabled with params, they will govern the shortening
8088 // behavior as expected. The following three tests verify behavior for a
8089 // param larger than the referrer length, exactly the same as the string
8090 // length, and shorter than the string length.
8091 {
8092 TestDelegate d;
8093 std::map<std::string, std::string> params;
8094 params["MaxRefererHeaderLength"] =
8095 base::NumberToString(long_referer_header.length() + 1);
8096
8097 base::test::ScopedFeatureList feature_list;
8098 feature_list.InitAndEnableFeatureWithParameters(
8099 features::kCapRefererHeaderLength, params);
8100
8101 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8102 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8103 TRAFFIC_ANNOTATION_FOR_TESTS));
8104 req->SetReferrer(long_referer_header);
8105 req->Start();
8106 d.RunUntilComplete();
8107
8108 EXPECT_EQ(long_referer_header, d.data_received());
8109 }
8110
8111 {
8112 TestDelegate d;
8113 std::map<std::string, std::string> params;
8114 params["MaxRefererHeaderLength"] =
8115 base::NumberToString(long_referer_header.length());
8116
8117 base::test::ScopedFeatureList feature_list;
8118 feature_list.InitAndEnableFeatureWithParameters(
8119 features::kCapRefererHeaderLength, params);
8120
8121 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8122 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8123 TRAFFIC_ANNOTATION_FOR_TESTS));
8124 req->SetReferrer(long_referer_header);
8125 req->Start();
8126 d.RunUntilComplete();
8127
8128 EXPECT_EQ(long_referer_header, d.data_received());
8129 }
8130
8131 {
8132 TestDelegate d;
8133 std::map<std::string, std::string> params;
8134 params["MaxRefererHeaderLength"] =
8135 base::NumberToString(long_referer_header.length() - 1);
8136
8137 base::test::ScopedFeatureList feature_list;
8138 feature_list.InitAndEnableFeatureWithParameters(
8139 features::kCapRefererHeaderLength, params);
8140
8141 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8142 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8143 TRAFFIC_ANNOTATION_FOR_TESTS));
8144 req->SetReferrer(long_referer_header);
8145 req->Start();
8146 d.RunUntilComplete();
8147
8148 EXPECT_EQ("http://foo.com/", d.data_received());
8149 }
8150}
8151
[email protected]316c1e5e2012-09-12 15:17:448152TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:558153 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448154
8155 TestDelegate d;
8156 {
8157 d.set_cancel_in_received_redirect(true);
Ryan Sleevib8449e02018-07-15 04:31:078158 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168159 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8160 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198161 req->Start();
Wez2a31b222018-06-07 22:07:158162 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448163
8164 EXPECT_EQ(1, d.response_started_count());
8165 EXPECT_EQ(0, d.bytes_received());
8166 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508167 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448168 }
8169}
8170
8171TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:558172 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448173
8174 TestDelegate d;
8175 {
tommycli59a63432015-11-06 00:10:558176 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078177 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168178 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048179
[email protected]f7022f32014-08-21 16:32:198180 req->Start();
Wez0e717112018-06-18 23:09:228181 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:448182
8183 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:238184 EXPECT_TRUE(d.have_full_request_headers());
8185 CheckFullRequestHeaders(d.full_request_headers(), test_url);
8186 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:448187
Arthur Sonzognib8465ff72019-01-04 18:44:358188 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8189 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:158190 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448191
8192 EXPECT_EQ(1, d.response_started_count());
8193 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508194 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448195
[email protected]6cdfd7f2013-02-08 20:40:158196 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198197 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478198 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:448199 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8200
8201 std::string contents;
[email protected]82f84b92013-08-30 18:23:508202 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:448203 EXPECT_EQ(contents, d.data_received());
8204 }
8205}
8206
[email protected]79e1fd62013-06-20 06:50:048207TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:558208 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:048209
8210 TestDelegate d;
8211 {
tommycli59a63432015-11-06 00:10:558212 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078213 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168214 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048215
8216 EXPECT_FALSE(d.have_full_request_headers());
8217
[email protected]f7022f32014-08-21 16:32:198218 req->Start();
Wez0e717112018-06-18 23:09:228219 d.RunUntilRedirect();
[email protected]79e1fd62013-06-20 06:50:048220
8221 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:048222
Arthur Sonzognib8465ff72019-01-04 18:44:358223 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8224 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:158225 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:048226
tommycli59a63432015-11-06 00:10:558227 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:048228 EXPECT_EQ(1, d.response_started_count());
8229 EXPECT_TRUE(d.have_full_request_headers());
8230 CheckFullRequestHeaders(d.full_request_headers(), target_url);
8231 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508232 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:048233
8234 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198235 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478236 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:048237 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8238
8239 std::string contents;
[email protected]82f84b92013-08-30 18:23:508240 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:048241 EXPECT_EQ(contents, d.data_received());
8242 }
8243}
8244
Arthur Sonzognib8465ff72019-01-04 18:44:358245TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedHeaders) {
Chong Zhang7607f1f2018-06-01 20:52:208246 ASSERT_TRUE(http_test_server()->Start());
8247
8248 TestDelegate d;
8249 {
Chong Zhang7607f1f2018-06-01 20:52:208250 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078251 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Chong Zhang7607f1f2018-06-01 20:52:208252 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8253
8254 // Set initial headers for the request.
8255 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8256 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8257
8258 req->Start();
Wez0e717112018-06-18 23:09:228259 d.RunUntilRedirect();
Chong Zhang7607f1f2018-06-01 20:52:208260
8261 // Initial request should only have initial headers.
8262 EXPECT_EQ(1, d.received_redirect_count());
8263 EXPECT_TRUE(d.have_full_request_headers());
8264 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8265 std::string sent_value;
8266 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8267 EXPECT_EQ("Value1", sent_value);
8268 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8269 EXPECT_EQ("Value2", sent_value);
8270 EXPECT_FALSE(sent_headers1.GetHeader("Header3", &sent_value));
8271 d.ClearFullRequestHeaders();
8272
8273 // Overwrite Header2 and add Header3.
Arthur Sonzognib8465ff72019-01-04 18:44:358274 net::HttpRequestHeaders modified_headers;
8275 modified_headers.SetHeader("Header2", "");
8276 modified_headers.SetHeader("Header3", "Value3");
Chong Zhang7607f1f2018-06-01 20:52:208277
Arthur Sonzognib8465ff72019-01-04 18:44:358278 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8279 modified_headers);
Wez2a31b222018-06-07 22:07:158280 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:208281
8282 EXPECT_EQ(1, d.response_started_count());
8283 EXPECT_FALSE(d.received_data_before_response());
8284 EXPECT_EQ(OK, d.request_status());
8285
8286 // Redirected request should also have modified headers.
8287 EXPECT_TRUE(d.have_full_request_headers());
8288 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8289 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8290 EXPECT_EQ("Value1", sent_value);
8291 EXPECT_TRUE(sent_headers2.GetHeader("Header2", &sent_value));
8292 EXPECT_EQ("", sent_value);
8293 EXPECT_TRUE(sent_headers2.GetHeader("Header3", &sent_value));
8294 EXPECT_EQ("Value3", sent_value);
8295 }
8296}
8297
Arthur Sonzognib8465ff72019-01-04 18:44:358298TEST_F(URLRequestTestHTTP, DeferredRedirect_RemovedHeaders) {
8299 ASSERT_TRUE(http_test_server()->Start());
8300
8301 TestDelegate d;
8302 {
8303 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
8304 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8305 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8306
8307 // Set initial headers for the request.
8308 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8309 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8310
8311 req->Start();
8312 d.RunUntilRedirect();
8313
8314 // Initial request should have initial headers.
8315 EXPECT_EQ(1, d.received_redirect_count());
8316 EXPECT_TRUE(d.have_full_request_headers());
8317 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8318 std::string sent_value;
8319 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8320 EXPECT_EQ("Value1", sent_value);
8321 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8322 EXPECT_EQ("Value2", sent_value);
8323 d.ClearFullRequestHeaders();
8324
8325 // Keep Header1 and remove Header2.
8326 std::vector<std::string> removed_headers({"Header2"});
8327 req->FollowDeferredRedirect(removed_headers,
8328 base::nullopt /* modified_headers */);
8329 d.RunUntilComplete();
8330
8331 EXPECT_EQ(1, d.response_started_count());
8332 EXPECT_FALSE(d.received_data_before_response());
8333 EXPECT_EQ(OK, d.request_status());
8334
8335 // Redirected request should also have
8336 EXPECT_TRUE(d.have_full_request_headers());
8337 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8338 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8339 EXPECT_EQ("Value1", sent_value);
8340 EXPECT_FALSE(sent_headers2.GetHeader("Header2", &sent_value));
8341 }
8342}
8343
[email protected]316c1e5e2012-09-12 15:17:448344TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:558345 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448346
8347 TestDelegate d;
8348 {
Ryan Sleevib8449e02018-07-15 04:31:078349 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168350 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8351 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198352 req->Start();
Wez0e717112018-06-18 23:09:228353 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:448354
8355 EXPECT_EQ(1, d.received_redirect_count());
8356
[email protected]f7022f32014-08-21 16:32:198357 req->Cancel();
Wez2a31b222018-06-07 22:07:158358 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448359
8360 EXPECT_EQ(1, d.response_started_count());
8361 EXPECT_EQ(0, d.bytes_received());
8362 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508363 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448364 }
8365}
8366
8367TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:558368 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448369
[email protected]3b23a222013-05-15 21:33:258370 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:448371 {
8372 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078373 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558374 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168375 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448376 HttpRequestHeaders headers;
8377 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198378 req->SetExtraRequestHeaders(headers);
8379 req->Start();
Wez2a31b222018-06-07 22:07:158380 d.RunUntilComplete();
[email protected]3b23a222013-05-15 21:33:258381
8382 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198383 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258384 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448385 }
8386
[email protected]3b23a222013-05-15 21:33:258387 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:448388 {
8389 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078390 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558391 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168392 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448393 HttpRequestHeaders headers;
8394 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198395 req->SetExtraRequestHeaders(headers);
8396 req->Start();
Wez2a31b222018-06-07 22:07:158397 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448398
[email protected]f7022f32014-08-21 16:32:198399 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258400
8401 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198402 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258403 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:448404 }
8405
[email protected]3b23a222013-05-15 21:33:258406 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:448407 {
8408 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078409 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558410 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168411 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448412 HttpRequestHeaders headers;
8413 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:198414 req->SetExtraRequestHeaders(headers);
8415 req->Start();
Wez2a31b222018-06-07 22:07:158416 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448417
[email protected]f7022f32014-08-21 16:32:198418 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258419
8420 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198421 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258422 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448423 }
8424}
8425
8426TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:558427 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448428
8429 // populate the cache
8430 {
8431 TestDelegate d;
8432 d.set_credentials(AuthCredentials(kUser, kSecret));
8433
Ryan Sleevib8449e02018-07-15 04:31:078434 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168435 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8436 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198437 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448438
Wez2a31b222018-06-07 22:07:158439 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448440
8441 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8442 }
8443
8444 // repeat request with end-to-end validation. since auth-basic results in a
8445 // cachable page, we expect this test to result in a 304. in which case, the
8446 // response should be fetched from the cache.
8447 {
8448 TestDelegate d;
8449 d.set_credentials(AuthCredentials(kUser, kSecret));
8450
Ryan Sleevib8449e02018-07-15 04:31:078451 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168452 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8453 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198454 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8455 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448456
Wez2a31b222018-06-07 22:07:158457 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448458
8459 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8460
8461 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198462 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:448463 }
8464}
8465
8466// Check that Set-Cookie headers in 401 responses are respected.
8467// http://crbug.com/6450
8468TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:558469 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448470
8471 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:558472 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:448473
8474 // Request a page that will give a 401 containing a Set-Cookie header.
8475 // Verify that when the transaction is restarted, it includes the new cookie.
8476 {
[email protected]ceefd7fd2012-11-29 00:36:248477 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448478 TestURLRequestContext context(true);
8479 context.set_network_delegate(&network_delegate);
8480 context.Init();
8481
8482 TestDelegate d;
8483 d.set_credentials(AuthCredentials(kUser, kSecret));
8484
danakj8522a25b2016-04-16 00:17:368485 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:168486 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
8487 TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298488 r->set_site_for_cookies(url_requiring_auth);
[email protected]f7022f32014-08-21 16:32:198489 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448490
Wez2a31b222018-06-07 22:07:158491 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448492
8493 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8494
8495 // Make sure we sent the cookie in the restarted transaction.
8496 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8497 != std::string::npos);
8498 }
8499
8500 // Same test as above, except this time the restart is initiated earlier
8501 // (without user intervention since identity is embedded in the URL).
8502 {
[email protected]ceefd7fd2012-11-29 00:36:248503 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448504 TestURLRequestContext context(true);
8505 context.set_network_delegate(&network_delegate);
8506 context.Init();
8507
8508 TestDelegate d;
8509
8510 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:188511 replacements.SetUsernameStr("user2");
8512 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:448513 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
8514
rhalavatib7bd7c792017-04-27 05:25:168515 std::unique_ptr<URLRequest> r(context.CreateRequest(
8516 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298517 r->set_site_for_cookies(url_with_identity);
[email protected]f7022f32014-08-21 16:32:198518 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448519
Wez2a31b222018-06-07 22:07:158520 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448521
8522 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
8523
8524 // Make sure we sent the cookie in the restarted transaction.
8525 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8526 != std::string::npos);
8527 }
8528}
8529
Matt Menke0743e342019-06-11 20:48:108530TEST_F(URLRequestTestHTTP, BasicAuthWithCookiesCancelAuth) {
8531 ASSERT_TRUE(http_test_server()->Start());
8532
8533 GURL url_requiring_auth =
8534 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
8535
8536 // Request a page that will give a 401 containing a Set-Cookie header.
8537 // Verify that cookies are set before credentials are provided, and then
8538 // cancelling auth does not result in setting the cookies again.
8539 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8540 TestURLRequestContext context(true);
8541 context.set_network_delegate(&network_delegate);
8542 context.Init();
8543
8544 TestDelegate d;
8545
8546 EXPECT_TRUE(GetAllCookies(&context).empty());
8547
8548 std::unique_ptr<URLRequest> r(context.CreateRequest(
8549 url_requiring_auth, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8550 r->set_site_for_cookies(url_requiring_auth);
8551 r->Start();
8552 d.RunUntilAuthRequired();
8553
8554 // Cookie should have been set.
8555 EXPECT_EQ(1, network_delegate.set_cookie_count());
8556 CookieList cookies = GetAllCookies(&context);
8557 ASSERT_EQ(1u, cookies.size());
8558 EXPECT_EQ("got_challenged", cookies[0].Name());
8559 EXPECT_EQ("true", cookies[0].Value());
8560
8561 // Delete cookie.
8562 context.cookie_store()->DeleteAllAsync(CookieStore::DeleteCallback());
8563
8564 // Cancel auth and continue the request.
8565 r->CancelAuth();
8566 d.RunUntilComplete();
8567 ASSERT_TRUE(r->response_headers());
8568 EXPECT_EQ(401, r->response_headers()->response_code());
8569
8570 // Cookie should not have been set again.
8571 EXPECT_TRUE(GetAllCookies(&context).empty());
8572 EXPECT_EQ(1, network_delegate.set_cookie_count());
8573}
8574
Maks Orlovich15714232019-06-16 23:14:098575TEST_F(URLRequestTest, ReportCookieActivity) {
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548576 HttpTestServer test_server;
8577 ASSERT_TRUE(test_server.Start());
8578
8579 FilteringTestLayeredNetworkDelegate network_delegate(
8580 std::make_unique<TestNetworkDelegate>());
8581 network_delegate.SetCookieFilter("not_stored_cookie");
8582 network_delegate.set_block_get_cookies();
8583 TestURLRequestContext context(true);
8584 context.set_network_delegate(&network_delegate);
8585 context.Init();
Maks Orlovich15714232019-06-16 23:14:098586 // Make sure cookies blocked from being stored are caught, and those that are
8587 // accepted are reported as well.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548588 {
8589 TestDelegate d;
Maks Orlovich15714232019-06-16 23:14:098590 GURL test_url = test_server.GetURL(
8591 "/set-cookie?not_stored_cookie=true&"
8592 "stored_cookie=tasty"
8593 "&path_cookie=narrow;path=/set-cookie");
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548594 std::unique_ptr<URLRequest> req(context.CreateRequest(
Lily Chen3ac7cf42019-05-30 23:29:298595 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8596 req->set_site_for_cookies(test_url);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548597 req->Start();
8598 d.RunUntilComplete();
8599
Maks Orlovich15714232019-06-16 23:14:098600 ASSERT_EQ(3u, req->maybe_stored_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548601 EXPECT_EQ("not_stored_cookie",
Maks Orlovich15714232019-06-16 23:14:098602 req->maybe_stored_cookies()[0].cookie->Name());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548603 EXPECT_EQ(
8604 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
Maks Orlovich15714232019-06-16 23:14:098605 req->maybe_stored_cookies()[0].status);
8606 EXPECT_EQ("stored_cookie", req->maybe_stored_cookies()[1].cookie->Name());
8607 EXPECT_EQ(net::CanonicalCookie::CookieInclusionStatus::INCLUDE,
8608 req->maybe_stored_cookies()[1].status);
8609 EXPECT_EQ("stored_cookie", req->maybe_stored_cookies()[1].cookie->Name());
8610 EXPECT_EQ(net::CanonicalCookie::CookieInclusionStatus::INCLUDE,
8611 req->maybe_stored_cookies()[2].status);
8612 EXPECT_EQ("path_cookie", req->maybe_stored_cookies()[2].cookie->Name());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548613 }
8614 {
8615 TestDelegate d;
8616 // Make sure cookies blocked from being sent are caught.
Lily Chen3ac7cf42019-05-30 23:29:298617 GURL test_url = test_server.GetURL("/echoheader?Cookie");
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548618 std::unique_ptr<URLRequest> req(context.CreateRequest(
Lily Chen3ac7cf42019-05-30 23:29:298619 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8620 req->set_site_for_cookies(test_url);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548621 req->Start();
8622 d.RunUntilComplete();
8623
Maks Orlovich15714232019-06-16 23:14:098624 EXPECT_TRUE(d.data_received().find("stored_cookie=tasty") ==
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548625 std::string::npos);
8626
Maks Orlovich15714232019-06-16 23:14:098627 ASSERT_EQ(2u, req->maybe_sent_cookies().size());
8628 EXPECT_EQ("path_cookie", req->maybe_sent_cookies()[0].cookie.Name());
8629 EXPECT_EQ(net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_NOT_ON_PATH,
8630 req->maybe_sent_cookies()[0].status);
8631 EXPECT_EQ("stored_cookie", req->maybe_sent_cookies()[1].cookie.Name());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548632 EXPECT_EQ(
8633 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
Maks Orlovich15714232019-06-16 23:14:098634 req->maybe_sent_cookies()[1].status);
8635 }
8636
8637 network_delegate.unset_block_get_cookies();
8638 {
8639 // Now with sending cookies re-enabled, it should actually be sent.
8640 TestDelegate d;
8641 GURL test_url = test_server.GetURL("/echoheader?Cookie");
8642 std::unique_ptr<URLRequest> req(context.CreateRequest(
8643 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8644 req->set_site_for_cookies(test_url);
8645 req->Start();
8646 d.RunUntilComplete();
8647
8648 EXPECT_TRUE(d.data_received().find("stored_cookie=tasty") !=
8649 std::string::npos);
8650
8651 ASSERT_EQ(2u, req->maybe_sent_cookies().size());
8652 EXPECT_EQ("path_cookie", req->maybe_sent_cookies()[0].cookie.Name());
8653 EXPECT_EQ(net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_NOT_ON_PATH,
8654 req->maybe_sent_cookies()[0].status);
8655 EXPECT_EQ("stored_cookie", req->maybe_sent_cookies()[1].cookie.Name());
8656 EXPECT_EQ(net::CanonicalCookie::CookieInclusionStatus::INCLUDE,
8657 req->maybe_sent_cookies()[1].status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548658 }
8659}
8660
Maks Orlovich0d9da122019-06-13 20:14:438661TEST_F(URLRequestTestHTTP, AuthChallengeCancelCookieCollect) {
8662 ASSERT_TRUE(http_test_server()->Start());
8663 GURL url_requiring_auth =
8664 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
8665
8666 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8667 std::make_unique<TestNetworkDelegate>());
8668 filtering_network_delegate.SetCookieFilter("got_challenged");
8669 TestURLRequestContext context(true);
8670 context.set_network_delegate(&filtering_network_delegate);
8671 context.Init();
8672
8673 TestDelegate delegate;
8674
8675 std::unique_ptr<URLRequest> request(
8676 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &delegate,
8677 TRAFFIC_ANNOTATION_FOR_TESTS));
8678 request->set_site_for_cookies(url_requiring_auth);
8679 request->Start();
8680
8681 delegate.RunUntilAuthRequired();
Maks Orlovich15714232019-06-16 23:14:098682 ASSERT_EQ(1u, request->maybe_stored_cookies().size());
Maks Orlovich0d9da122019-06-13 20:14:438683 EXPECT_EQ(
8684 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
Maks Orlovich15714232019-06-16 23:14:098685 request->maybe_stored_cookies()[0].status);
Maks Orlovich0d9da122019-06-13 20:14:438686 EXPECT_EQ("got_challenged=true",
Maks Orlovich15714232019-06-16 23:14:098687 request->maybe_stored_cookies()[0].cookie_string);
Maks Orlovich0d9da122019-06-13 20:14:438688
8689 // This shouldn't DCHECK-fail.
8690 request->CancelAuth();
8691 delegate.RunUntilComplete();
8692}
8693
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548694TEST_F(URLRequestTestHTTP, AuthChallengeWithFilteredCookies) {
Aaron Tagliaboschi028009e2019-03-07 16:28:068695 ASSERT_TRUE(http_test_server()->Start());
8696
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548697 GURL url_requiring_auth =
8698 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
8699 GURL url_requiring_auth_wo_cookies =
8700 http_test_server()->GetURL("/auth-basic");
Maks Orlovich15714232019-06-16 23:14:098701 // Check maybe_stored_cookies is populated first round trip, and cleared on
8702 // the second.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548703 {
8704 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8705 std::make_unique<TestNetworkDelegate>());
8706 filtering_network_delegate.SetCookieFilter("got_challenged");
8707 TestURLRequestContext context(true);
8708 context.set_network_delegate(&filtering_network_delegate);
8709 context.Init();
Aaron Tagliaboschi028009e2019-03-07 16:28:068710
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548711 TestDelegate delegate;
Aaron Tagliaboschi028009e2019-03-07 16:28:068712
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548713 std::unique_ptr<URLRequest> request(
8714 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &delegate,
8715 TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298716 request->set_site_for_cookies(url_requiring_auth);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548717 request->Start();
Aaron Tagliaboschi028009e2019-03-07 16:28:068718
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548719 delegate.RunUntilAuthRequired();
8720 // Make sure it was blocked once.
8721 EXPECT_EQ(1, filtering_network_delegate.blocked_set_cookie_count());
Aaron Tagliaboschi028009e2019-03-07 16:28:068722
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548723 // The number of cookies blocked from the most recent round trip.
Maks Orlovich15714232019-06-16 23:14:098724 ASSERT_EQ(1u, request->maybe_stored_cookies().size());
8725 EXPECT_EQ(
8726 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
8727 request->maybe_stored_cookies().front().status);
Aaron Tagliaboschi028009e2019-03-07 16:28:068728
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548729 // Now check the second round trip
8730 request->SetAuth(AuthCredentials(kUser, kSecret));
8731 delegate.RunUntilComplete();
8732 EXPECT_THAT(delegate.request_status(), IsOk());
Aaron Tagliaboschi028009e2019-03-07 16:28:068733
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548734 // There are DCHECKs in URLRequestHttpJob that would fail if
Maks Orlovich15714232019-06-16 23:14:098735 // maybe_sent_cookies and maybe_stored_cookies were not cleared properly.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548736
8737 // Make sure the cookie was actually filtered and not sent.
8738 EXPECT_EQ(std::string::npos,
8739 delegate.data_received().find("Cookie: got_challenged=true"));
8740
Maks Orlovich15714232019-06-16 23:14:098741 // The number of cookies that most recent round trip tried to set.
8742 ASSERT_EQ(0u, request->maybe_stored_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548743 }
8744
Maks Orlovich15714232019-06-16 23:14:098745 // Check maybe_sent_cookies on first round trip (and cleared for the second).
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548746 {
8747 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8748 std::make_unique<TestNetworkDelegate>());
8749 filtering_network_delegate.set_block_get_cookies();
8750 TestURLRequestContext context(true);
8751 context.set_network_delegate(&filtering_network_delegate);
8752
8753 std::unique_ptr<CookieMonster> cm =
8754 std::make_unique<CookieMonster>(nullptr, nullptr);
Lily Chen0f208ea2019-08-08 23:37:538755 auto another_cookie = CanonicalCookie::Create(
8756 url_requiring_auth_wo_cookies, "another_cookie=true", base::Time::Now(),
8757 base::nullopt /* server_time */);
8758 cm->SetCanonicalCookieAsync(
8759 std::move(another_cookie), url_requiring_auth_wo_cookies.scheme(),
8760 CookieOptions(), CookieStore::SetCookiesCallback());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548761 context.set_cookie_store(cm.get());
8762 context.Init();
8763
8764 TestDelegate delegate;
8765
8766 std::unique_ptr<URLRequest> request(
8767 context.CreateRequest(url_requiring_auth_wo_cookies, DEFAULT_PRIORITY,
8768 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298769 request->set_site_for_cookies(url_requiring_auth_wo_cookies);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548770 request->Start();
8771
8772 delegate.RunUntilAuthRequired();
8773
Maks Orlovich15714232019-06-16 23:14:098774 ASSERT_EQ(1u, request->maybe_sent_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548775 EXPECT_EQ("another_cookie",
Maks Orlovich15714232019-06-16 23:14:098776 request->maybe_sent_cookies().front().cookie.Name());
8777 EXPECT_EQ("true", request->maybe_sent_cookies().front().cookie.Value());
8778 EXPECT_EQ(
8779 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
8780 request->maybe_sent_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548781
Maks Orlovich15714232019-06-16 23:14:098782 // Check maybe_sent_cookies on second roundtrip.
8783 request->set_maybe_sent_cookies({});
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548784 cm->DeleteAllAsync(CookieStore::DeleteCallback());
Lily Chen0f208ea2019-08-08 23:37:538785 auto one_more_cookie = CanonicalCookie::Create(
8786 url_requiring_auth_wo_cookies, "one_more_cookie=true",
8787 base::Time::Now(), base::nullopt /* server_time */);
8788 cm->SetCanonicalCookieAsync(
8789 std::move(one_more_cookie), url_requiring_auth_wo_cookies.scheme(),
8790 CookieOptions(), CookieStore::SetCookiesCallback());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548791
8792 request->SetAuth(AuthCredentials(kUser, kSecret));
8793 delegate.RunUntilComplete();
8794 EXPECT_THAT(delegate.request_status(), IsOk());
8795
8796 // There are DCHECKs in URLRequestHttpJob that would fail if
Maks Orlovich15714232019-06-16 23:14:098797 // maybe_sent_cookies and maybe_stored_cookies were not cleared properly.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548798
8799 // Make sure the cookie was actually filtered.
8800 EXPECT_EQ(std::string::npos,
8801 delegate.data_received().find("Cookie: one_more_cookie=true"));
8802 // got_challenged was set after the first request and blocked on the second,
8803 // so it should only have been blocked this time
8804 EXPECT_EQ(2, filtering_network_delegate.blocked_get_cookie_count());
8805
8806 // // The number of cookies blocked from the most recent round trip.
Maks Orlovich15714232019-06-16 23:14:098807 ASSERT_EQ(1u, request->maybe_sent_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548808 EXPECT_EQ("one_more_cookie",
Maks Orlovich15714232019-06-16 23:14:098809 request->maybe_sent_cookies().front().cookie.Name());
8810 EXPECT_EQ(
8811 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
8812 request->maybe_sent_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548813 }
Aaron Tagliaboschi028009e2019-03-07 16:28:068814}
8815
[email protected]58e32bb2013-01-21 18:23:258816// Tests that load timing works as expected with auth and the cache.
8817TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:558818 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:258819
8820 // populate the cache
8821 {
8822 TestDelegate d;
8823 d.set_credentials(AuthCredentials(kUser, kSecret));
8824
Ryan Sleevib8449e02018-07-15 04:31:078825 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168826 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8827 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198828 r->Start();
[email protected]58e32bb2013-01-21 18:23:258829
Wez2a31b222018-06-07 22:07:158830 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258831
8832 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8833
8834 LoadTimingInfo load_timing_info_before_auth;
8835 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
8836 &load_timing_info_before_auth));
8837 TestLoadTimingNotReused(load_timing_info_before_auth,
8838 CONNECT_TIMING_HAS_DNS_TIMES);
8839
8840 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198841 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:258842 // The test server does not support keep alive sockets, so the second
8843 // request with auth should use a new socket.
8844 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
8845 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
8846 load_timing_info.socket_log_id);
8847 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
8848 load_timing_info.connect_timing.connect_start);
8849 }
8850
[email protected]3b23a222013-05-15 21:33:258851 // Repeat request with end-to-end validation. Since auth-basic results in a
8852 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258853 // response should be fetched from the cache.
8854 {
8855 TestDelegate d;
8856 d.set_credentials(AuthCredentials(kUser, kSecret));
8857
Ryan Sleevib8449e02018-07-15 04:31:078858 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168859 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8860 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198861 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8862 r->Start();
[email protected]58e32bb2013-01-21 18:23:258863
Wez2a31b222018-06-07 22:07:158864 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258865
8866 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8867
8868 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198869 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258870
[email protected]3b23a222013-05-15 21:33:258871 // Since there was a request that went over the wire, the load timing
8872 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258873 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198874 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258875 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258876 }
8877}
8878
[email protected]316c1e5e2012-09-12 15:17:448879// In this test, we do a POST which the server will 302 redirect.
8880// The subsequent transaction should use GET, and should not send the
8881// Content-Type header.
8882// http://code.google.com/p/chromium/issues/detail?id=843
8883TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558884 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448885
8886 const char kData[] = "hello world";
8887
8888 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078889 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168890 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8891 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198892 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078893 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448894
8895 // Set headers (some of which are specific to the POST).
8896 HttpRequestHeaders headers;
Yeol45b9e0a2018-07-27 02:03:298897 headers.SetHeader("Content-Type",
8898 "multipart/form-data;"
8899 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ");
8900 headers.SetHeader("Accept",
8901 "text/xml,application/xml,application/xhtml+xml,"
8902 "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
8903 headers.SetHeader("Accept-Language", "en-US,en");
8904 headers.SetHeader("Accept-Charset", "ISO-8859-1,*,utf-8");
8905 headers.SetHeader("Content-Length", "11");
8906 headers.SetHeader("Origin", "http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198907 req->SetExtraRequestHeaders(headers);
8908 req->Start();
Wez2a31b222018-06-07 22:07:158909 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448910
8911 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198912 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448913 EXPECT_EQ("text/html", mime_type);
8914
8915 const std::string& data = d.data_received();
8916
8917 // Check that the post-specific headers were stripped:
8918 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8919 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498920 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448921
8922 // These extra request headers should not have been stripped.
8923 EXPECT_TRUE(ContainsString(data, "Accept:"));
8924 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8925 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8926}
8927
jww5fe460ff2015-03-28 00:22:518928// The following tests check that we handle mutating the request for HTTP
8929// redirects as expected.
8930// See https://crbug.com/56373, https://crbug.com/102130, and
8931// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448932
8933TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558934 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448935
tommycli59a63432015-11-06 00:10:558936 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518937 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558938 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448939
8940 HTTPRedirectMethodTest(url, "POST", "GET", true);
8941 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8942 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518943
8944 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8945 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498946 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8947 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8948 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408949 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8950 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448951}
8952
8953TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558954 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448955
tommycli59a63432015-11-06 00:10:558956 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518957 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558958 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448959
8960 HTTPRedirectMethodTest(url, "POST", "GET", true);
8961 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8962 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518963
8964 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8965 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498966 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8967 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8968 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408969 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8970 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448971}
8972
8973TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558974 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448975
tommycli59a63432015-11-06 00:10:558976 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518977 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558978 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448979
8980 HTTPRedirectMethodTest(url, "POST", "GET", true);
8981 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8982 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518983
Alex Clarke1e08882b32017-10-06 14:22:408984 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8985 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8986 std::string());
8987 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8988 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8989 std::string());
jww5fe460ff2015-03-28 00:22:518990 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8991 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408992 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8993 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8994 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8995 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8996 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498997 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8998 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8999 std::string());
Alex Clarke1e08882b32017-10-06 14:22:409000 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
9001 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:449002}
9003
9004TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:559005 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449006
tommycli59a63432015-11-06 00:10:559007 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:519008 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:559009 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:449010
9011 HTTPRedirectMethodTest(url, "POST", "POST", true);
9012 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
9013 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:519014
9015 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
9016 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
9017 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
9018 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:409019 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
9020 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:449021}
9022
[email protected]0a17aab32014-04-24 03:32:379023TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:559024 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:379025
tommycli59a63432015-11-06 00:10:559026 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:519027 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:559028 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:379029
9030 HTTPRedirectMethodTest(url, "POST", "POST", true);
9031 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
9032 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:519033
9034 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
9035 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
9036 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
9037 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:409038 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
9039 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:379040}
9041
9042// Make sure that 308 responses without bodies are not treated as redirects.
9043// Certain legacy apis that pre-date the response code expect this behavior
9044// (Like Google Drive).
9045TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:559046 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:379047
9048 TestDelegate d;
tommycli59a63432015-11-06 00:10:559049 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:379050
Ryan Sleevib8449e02018-07-15 04:31:079051 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169052 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:379053
[email protected]f7022f32014-08-21 16:32:199054 request->Start();
Wez2a31b222018-06-07 22:07:159055 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:509056 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:379057 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:199058 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:379059 EXPECT_EQ("This is not a redirect.", d.data_received());
9060}
9061
[email protected]f878230e2014-04-03 15:36:149062TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:559063 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:149064
tommycli59a63432015-11-06 00:10:559065 GURL original_url(
9066 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
9067 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:149068
9069 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:149070 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9071 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:149072
Josh Karlinbe37f912018-12-07 01:05:149073 r->Start();
9074 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:149075
Josh Karlinbe37f912018-12-07 01:05:149076 EXPECT_EQ(2U, r->url_chain().size());
9077 EXPECT_EQ(OK, d.request_status());
9078 EXPECT_EQ(original_url, r->original_url());
9079 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:149080}
9081
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549082TEST_F(URLRequestTestHTTP, RedirectWithFilteredCookies) {
9083 ASSERT_TRUE(http_test_server()->Start());
9084
9085 // FilteringTestLayeredNetworkDelegate filters by name, so the names of the
9086 // two cookies have to be the same. The values have been set to different
9087 // strings (the value of the server-redirect cookies is "true" and set-cookie
9088 // is "other") to differentiate between the two round trips.
9089 GURL redirect_to(
9090 http_test_server()->GetURL("/set-cookie?server-redirect=other"));
9091
9092 GURL original_url(http_test_server()->GetURL("/server-redirect-with-cookie?" +
9093 redirect_to.spec()));
9094
9095 GURL original_url_wo_cookie(
9096 http_test_server()->GetURL("/server-redirect?" + redirect_to.spec()));
Maks Orlovich15714232019-06-16 23:14:099097 // Check maybe_stored_cookies on first round trip.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549098 {
9099 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
9100 std::make_unique<TestNetworkDelegate>()); // Must outlive URLRequest.
9101 filtering_network_delegate.SetCookieFilter(
9102 "server-redirect"); // Filter the cookie server-redirect sets.
9103 TestURLRequestContext context(true);
9104 context.set_network_delegate(&filtering_network_delegate);
9105 context.Init();
9106
9107 TestDelegate delegate;
9108 std::unique_ptr<URLRequest> request(
9109 context.CreateRequest(original_url, DEFAULT_PRIORITY, &delegate,
9110 TRAFFIC_ANNOTATION_FOR_TESTS));
9111
Lily Chen3ac7cf42019-05-30 23:29:299112 request->set_site_for_cookies(original_url);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549113 request->Start();
9114 delegate.RunUntilRedirect();
9115
9116 // Make sure it was blocked once.
9117 EXPECT_EQ(1, filtering_network_delegate.blocked_set_cookie_count());
9118
9119 // The number of cookies blocked from the most recent round trip.
Maks Orlovich15714232019-06-16 23:14:099120 ASSERT_EQ(1u, request->maybe_stored_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549121 EXPECT_EQ("server-redirect",
Maks Orlovich15714232019-06-16 23:14:099122 request->maybe_stored_cookies().front().cookie->Name());
9123 EXPECT_EQ("true", request->maybe_stored_cookies().front().cookie->Value());
9124 EXPECT_EQ(
9125 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
9126 request->maybe_stored_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549127
Maks Orlovich15714232019-06-16 23:14:099128 // Check maybe_stored_cookies on second round trip (and clearing from the
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549129 // first).
9130 request->FollowDeferredRedirect(base::nullopt, base::nullopt);
9131 delegate.RunUntilComplete();
9132 EXPECT_THAT(delegate.request_status(), IsOk());
9133
9134 // There are DCHECKs in URLRequestHttpJob that would fail if
Maks Orlovich15714232019-06-16 23:14:099135 // maybe_sent_cookies and maybe_stored_cookies we not cleared properly.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549136
9137 // Make sure it was blocked twice.
9138 EXPECT_EQ(2, filtering_network_delegate.blocked_set_cookie_count());
9139
9140 // The number of cookies blocked from the most recent round trip.
Maks Orlovich15714232019-06-16 23:14:099141 ASSERT_EQ(1u, request->maybe_stored_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549142 EXPECT_EQ("server-redirect",
Maks Orlovich15714232019-06-16 23:14:099143 request->maybe_stored_cookies().front().cookie->Name());
9144 EXPECT_EQ("other", request->maybe_stored_cookies().front().cookie->Value());
9145 EXPECT_EQ(
9146 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
9147 request->maybe_stored_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549148 }
9149
Maks Orlovich15714232019-06-16 23:14:099150 // Check maybe_sent_cookies on first round trip.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549151 {
9152 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
9153 std::make_unique<TestNetworkDelegate>());
9154 filtering_network_delegate.set_block_get_cookies();
9155 TestURLRequestContext context(true);
9156 context.set_network_delegate(&filtering_network_delegate);
9157 std::unique_ptr<CookieMonster> cm =
9158 std::make_unique<CookieMonster>(nullptr, nullptr);
Lily Chen0f208ea2019-08-08 23:37:539159 auto another_cookie = CanonicalCookie::Create(
9160 original_url, "another_cookie=true", base::Time::Now(),
9161 base::nullopt /* server_time */);
9162 cm->SetCanonicalCookieAsync(std::move(another_cookie),
9163 original_url.scheme(), CookieOptions(),
9164 CookieStore::SetCookiesCallback());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549165 context.set_cookie_store(cm.get());
9166 context.Init();
9167
9168 TestDelegate delegate;
9169 std::unique_ptr<URLRequest> request(
9170 context.CreateRequest(original_url_wo_cookie, DEFAULT_PRIORITY,
9171 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
9172
Lily Chen3ac7cf42019-05-30 23:29:299173 request->set_site_for_cookies(original_url_wo_cookie);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549174 request->Start();
9175
9176 delegate.RunUntilRedirect();
9177
Maks Orlovich15714232019-06-16 23:14:099178 ASSERT_EQ(1u, request->maybe_sent_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549179 EXPECT_EQ("another_cookie",
Maks Orlovich15714232019-06-16 23:14:099180 request->maybe_sent_cookies().front().cookie.Name());
9181 EXPECT_EQ(
9182 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
9183 request->maybe_sent_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549184
Maks Orlovich15714232019-06-16 23:14:099185 // Check maybe_sent_cookies on second round trip
9186 request->set_maybe_sent_cookies({});
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549187 cm->DeleteAllAsync(CookieStore::DeleteCallback());
Lily Chen0f208ea2019-08-08 23:37:539188 auto one_more_cookie = CanonicalCookie::Create(
9189 original_url_wo_cookie, "one_more_cookie=true", base::Time::Now(),
9190 base::nullopt /* server_time */);
9191 cm->SetCanonicalCookieAsync(
9192 std::move(one_more_cookie), original_url_wo_cookie.scheme(),
9193 CookieOptions(), CookieStore::SetCookiesCallback());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549194
9195 request->FollowDeferredRedirect(base::nullopt, base::nullopt);
9196 delegate.RunUntilComplete();
9197 EXPECT_THAT(delegate.request_status(), IsOk());
9198
9199 // There are DCHECKs in URLRequestHttpJob that would fail if
Maks Orlovich15714232019-06-16 23:14:099200 // maybe_sent_cookies and maybe_stored_cookies we not cleared properly.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549201
9202 EXPECT_EQ(2, filtering_network_delegate.blocked_get_cookie_count());
9203
9204 // The number of cookies blocked from the most recent round trip.
Maks Orlovich15714232019-06-16 23:14:099205 ASSERT_EQ(1u, request->maybe_sent_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549206 EXPECT_EQ("one_more_cookie",
Maks Orlovich15714232019-06-16 23:14:099207 request->maybe_sent_cookies().front().cookie.Name());
9208 EXPECT_EQ("true", request->maybe_sent_cookies().front().cookie.Value());
9209 EXPECT_EQ(
9210 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
9211 request->maybe_sent_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549212 }
9213}
9214
[email protected]cba24642014-08-15 20:49:599215TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:559216 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:599217
tommycli59a63432015-11-06 00:10:559218 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:599219 GURL first_party_url("http://example.com");
9220
9221 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:149222 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9223 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9224 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:599225
Josh Karlinbe37f912018-12-07 01:05:149226 r->Start();
9227 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:599228
Josh Karlinbe37f912018-12-07 01:05:149229 EXPECT_EQ(2U, r->url_chain().size());
9230 EXPECT_EQ(OK, d.request_status());
9231 EXPECT_EQ(first_party_url, r->site_for_cookies());
9232}
9233
9234TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameOrigin) {
9235 ASSERT_TRUE(http_test_server()->Start());
9236
9237 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9238 url::Origin top_frame_origin =
9239 url::Origin::Create(GURL("http://example.com"));
9240 TestDelegate d;
9241
9242 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9243 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9244 r->set_top_frame_origin(top_frame_origin);
9245
9246 r->Start();
9247 d.RunUntilComplete();
9248
9249 EXPECT_EQ(2U, r->url_chain().size());
9250 EXPECT_EQ(OK, d.request_status());
9251 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
9252}
9253
9254TEST_F(URLRequestTestHTTP, RedirectPreserveUnsetTopFrameOrigin) {
9255 ASSERT_TRUE(http_test_server()->Start());
9256
9257 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9258 TestDelegate d;
9259
9260 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9261 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9262 // Since we're not setting a top frame origin, we wouldn't expect one after
9263 // the redirect.
9264 r->Start();
9265 d.RunUntilComplete();
9266
9267 EXPECT_EQ(2U, r->url_chain().size());
9268 EXPECT_EQ(OK, d.request_status());
9269 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:599270}
9271
Josh Karlinf3caee1642018-12-10 22:54:279272TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameURL) {
9273 ASSERT_TRUE(http_test_server()->Start());
9274
9275 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9276 url::Origin top_frame_origin =
9277 url::Origin::Create(GURL("http://example.com"));
9278 TestDelegate d;
9279 {
9280 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9281 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9282 r->set_top_frame_origin(top_frame_origin);
9283
9284 r->Start();
9285 d.RunUntilComplete();
9286
9287 EXPECT_EQ(2U, r->url_chain().size());
9288 EXPECT_EQ(OK, d.request_status());
9289 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
9290 }
9291}
9292
[email protected]cba24642014-08-15 20:49:599293TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:559294 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:599295
tommycli59a63432015-11-06 00:10:559296 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:599297 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:559298 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:599299
9300 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:149301
Ryan Sleevib8449e02018-07-15 04:31:079302 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169303 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:469304 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:199305 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:599306 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
9307
[email protected]f7022f32014-08-21 16:32:199308 r->Start();
Wez2a31b222018-06-07 22:07:159309 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:599310
[email protected]f7022f32014-08-21 16:32:199311 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:509312 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:469313 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
Josh Karlinbe37f912018-12-07 01:05:149314}
9315
9316TEST_F(URLRequestTestHTTP, RedirectUpdateTopFrameOrigin) {
9317 ASSERT_TRUE(http_test_server()->Start());
9318
9319 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9320 url::Origin original_top_frame_origin =
9321 url::Origin::Create(GURL("http://example.com"));
9322 url::Origin expected_top_frame_origin =
9323 url::Origin::Create(GURL(http_test_server()->GetURL("/echo")));
9324
9325 TestDelegate d;
9326
9327 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9328 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9329 r->set_top_frame_origin(original_top_frame_origin);
9330 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
9331
9332 r->Start();
9333 d.RunUntilComplete();
9334
9335 EXPECT_EQ(2U, r->url_chain().size());
9336 EXPECT_EQ(OK, d.request_status());
9337 EXPECT_EQ(expected_top_frame_origin, *r->top_frame_origin());
9338}
9339
9340TEST_F(URLRequestTestHTTP, RedirectIgnoreUnsetTopFrameOrigin) {
9341 ASSERT_TRUE(http_test_server()->Start());
9342
9343 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9344 TestDelegate d;
9345
9346 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9347 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9348 // Since we're not setting a top frame origin, we wouldn't expect one after
9349 // the redirect.
9350 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
9351
9352 r->Start();
9353 d.RunUntilComplete();
9354
9355 EXPECT_EQ(2U, r->url_chain().size());
9356 EXPECT_EQ(OK, d.request_status());
9357 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:599358}
9359
[email protected]316c1e5e2012-09-12 15:17:449360TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:559361 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449362
9363 const char kData[] = "hello world";
9364
9365 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079366 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169367 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9368 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199369 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079370 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:449371 HttpRequestHeaders headers;
9372 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:249373 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:199374 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:449375
danakj8522a25b2016-04-16 00:17:369376 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559377 req.get(), &default_network_delegate_,
9378 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429379 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9380 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:449381
[email protected]f7022f32014-08-21 16:32:199382 req->Start();
Wez2a31b222018-06-07 22:07:159383 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:199384 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:449385}
9386
9387TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:559388 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449389
9390 const char kData[] = "hello world";
9391
9392 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079393 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169394 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9395 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199396 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079397 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:449398 HttpRequestHeaders headers;
9399 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:249400 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:199401 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:449402
danakj8522a25b2016-04-16 00:17:369403 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559404 req.get(), &default_network_delegate_,
9405 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:099406 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:429407 "Very Good Reason"));
9408 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:449409
[email protected]f7022f32014-08-21 16:32:199410 req->Start();
Wez2a31b222018-06-07 22:07:159411 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:199412 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:449413 EXPECT_EQ(kData, d.data_received());
9414}
9415
9416// Check that default A-L header is sent.
9417TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559418 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449419
[email protected]8790210c2013-12-02 05:29:539420 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:249421 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:449422 TestURLRequestContext context(true);
9423 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:439424 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:449425 context.Init();
9426
9427 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369428 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:559429 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169430 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199431 req->Start();
Wez2a31b222018-06-07 22:07:159432 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449433 EXPECT_EQ("en", d.data_received());
9434}
9435
9436// Check that an empty A-L header is not sent. http://crbug.com/77365.
9437TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559438 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449439
[email protected]8790210c2013-12-02 05:29:539440 std::string empty_string; // Avoid most vexing parse on line below.
9441 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:249442 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:449443 TestURLRequestContext context(true);
9444 context.set_network_delegate(&network_delegate);
9445 context.Init();
9446 // We override the language after initialization because empty entries
9447 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:439448 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:449449
9450 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369451 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:559452 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169453 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199454 req->Start();
Wez2a31b222018-06-07 22:07:159455 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449456 EXPECT_EQ("None", d.data_received());
9457}
9458
9459// Check that if request overrides the A-L header, the default is not appended.
9460// See http://crbug.com/20894
9461TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559462 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449463
9464 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079465 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559466 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169467 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449468 HttpRequestHeaders headers;
9469 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:199470 req->SetExtraRequestHeaders(headers);
9471 req->Start();
Wez2a31b222018-06-07 22:07:159472 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449473 EXPECT_EQ(std::string("ru"), d.data_received());
9474}
9475
9476// Check that default A-E header is sent.
9477TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559478 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449479
9480 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079481 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559482 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169483 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449484 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:199485 req->SetExtraRequestHeaders(headers);
9486 req->Start();
Wez2a31b222018-06-07 22:07:159487 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449488 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
9489}
9490
9491// Check that if request overrides the A-E header, the default is not appended.
9492// See http://crbug.com/47381
9493TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559494 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449495
9496 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079497 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559498 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169499 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449500 HttpRequestHeaders headers;
9501 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:199502 req->SetExtraRequestHeaders(headers);
9503 req->Start();
Wez2a31b222018-06-07 22:07:159504 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449505 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
9506 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
9507}
9508
[email protected]84f05432013-03-15 01:00:129509// Check that setting the A-C header sends the proper header.
9510TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:559511 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449512
9513 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079514 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559515 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:169516 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449517 HttpRequestHeaders headers;
9518 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:199519 req->SetExtraRequestHeaders(headers);
9520 req->Start();
Wez2a31b222018-06-07 22:07:159521 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449522 EXPECT_EQ(std::string("koi-8r"), d.data_received());
9523}
9524
9525// Check that default User-Agent header is sent.
9526TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:559527 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449528
9529 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079530 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559531 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169532 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199533 req->Start();
Wez2a31b222018-06-07 22:07:159534 d.RunUntilComplete();
Ryan Sleevib8449e02018-07-15 04:31:079535 EXPECT_EQ(default_context().http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:379536 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449537}
9538
9539// Check that if request overrides the User-Agent header,
9540// the default is not appended.
marqf14fff8d2015-12-02 15:52:299541// TODO(crbug.com/564656) This test is flaky on iOS.
9542#if defined(OS_IOS)
9543#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
9544#else
9545#define MAYBE_OverrideUserAgent OverrideUserAgent
9546#endif
9547TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:559548 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449549
9550 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079551 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559552 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169553 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449554 HttpRequestHeaders headers;
9555 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:199556 req->SetExtraRequestHeaders(headers);
9557 req->Start();
Wez2a31b222018-06-07 22:07:159558 d.RunUntilComplete();
[email protected]cd6f2522014-01-16 18:27:359559 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449560}
9561
[email protected]ee4c30d2012-11-07 15:08:439562// Check that a NULL HttpUserAgentSettings causes the corresponding empty
9563// User-Agent header to be sent but does not send the Accept-Language and
9564// Accept-Charset headers.
9565TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:559566 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:439567
[email protected]ceefd7fd2012-11-29 00:36:249568 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:439569 TestURLRequestContext context(true);
9570 context.set_network_delegate(&network_delegate);
9571 context.Init();
9572 // We override the HttpUserAgentSettings after initialization because empty
9573 // entries get overridden by Init().
Raul Tambre94493c652019-03-11 17:18:359574 context.set_http_user_agent_settings(nullptr);
[email protected]ee4c30d2012-11-07 15:08:439575
9576 struct {
9577 const char* request;
9578 const char* expected_response;
tommycli59a63432015-11-06 00:10:559579 } tests[] = {{"/echoheader?Accept-Language", "None"},
9580 {"/echoheader?Accept-Charset", "None"},
9581 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:439582
Avi Drissman4365a4782018-12-28 19:26:249583 for (size_t i = 0; i < base::size(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:439584 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369585 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169586 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
9587 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199588 req->Start();
Wez2a31b222018-06-07 22:07:159589 d.RunUntilComplete();
[email protected]ee4c30d2012-11-07 15:08:439590 EXPECT_EQ(tests[i].expected_response, d.data_received())
9591 << " Request = \"" << tests[i].request << "\"";
9592 }
9593}
9594
[email protected]5033ab82013-03-22 20:17:469595// Make sure that URLRequest passes on its priority updates to
9596// newly-created jobs after the first one.
9597TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:559598 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:469599
9600 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079601 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169602 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9603 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199604 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:469605
danakj8522a25b2016-04-16 00:17:369606 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559607 req.get(), &default_network_delegate_,
9608 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429609 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9610 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:469611
[email protected]f7022f32014-08-21 16:32:199612 req->SetPriority(LOW);
9613 req->Start();
9614 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:469615
mmenkeed0498b2015-12-08 23:20:429616 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:369617 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:429618 req.get(), &default_network_delegate_, &job_priority));
9619 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:469620
9621 // Should trigger |job| to be started.
Wez2a31b222018-06-07 22:07:159622 d.RunUntilComplete();
mmenkeed0498b2015-12-08 23:20:429623 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:469624}
9625
[email protected]80abdad2014-03-15 00:20:549626// Check that creating a network request while entering/exiting suspend mode
9627// fails as it should. This is the only case where an HttpTransactionFactory
9628// does not return an HttpTransaction.
9629TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
9630 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:369631 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
Ryan Sleevib8449e02018-07-15 04:31:079632 default_context().http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:549633 network_layer->OnSuspend();
9634
dchengc7eeda422015-12-26 03:56:489635 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:039636 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:279637 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:549638
9639 TestURLRequestContext context(true);
9640 context.set_http_transaction_factory(&http_cache);
9641 context.Init();
9642
9643 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369644 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169645 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9646 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199647 req->Start();
Wez2a31b222018-06-07 22:07:159648 d.RunUntilComplete();
[email protected]80abdad2014-03-15 00:20:549649
9650 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:509651 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:549652}
9653
mmenke2281f3762015-11-02 20:38:179654namespace {
[email protected]80abdad2014-03-15 00:20:549655
mmenke2281f3762015-11-02 20:38:179656// HttpTransactionFactory that synchronously fails to create transactions.
9657class FailingHttpTransactionFactory : public HttpTransactionFactory {
9658 public:
9659 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
9660 : network_session_(network_session) {}
9661
Chris Watkins7a41d3552017-12-01 02:13:279662 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:179663
9664 // HttpTransactionFactory methods:
9665 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:369666 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:179667 return ERR_FAILED;
9668 }
9669
9670 HttpCache* GetCache() override { return nullptr; }
9671
9672 HttpNetworkSession* GetSession() override { return network_session_; }
9673
9674 private:
9675 HttpNetworkSession* network_session_;
9676
9677 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
9678};
9679
9680} // namespace
9681
9682// Check that when a request that fails to create an HttpTransaction can be
9683// cancelled while the failure notification is pending, and doesn't send two
9684// failure notifications.
9685//
9686// This currently only happens when in suspend mode and there's no cache, but
9687// just use a special HttpTransactionFactory, to avoid depending on those
9688// behaviors.
9689TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
9690 FailingHttpTransactionFactory http_transaction_factory(
Ryan Sleevib8449e02018-07-15 04:31:079691 default_context().http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:549692 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:179693 context.set_http_transaction_factory(&http_transaction_factory);
9694 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:549695 context.Init();
9696
9697 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369698 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169699 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9700 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:179701 // Don't send cookies (Collecting cookies is asynchronous, and need request to
9702 // try to create an HttpNetworkTransaction synchronously on start).
9703 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:199704 req->Start();
mmenke2281f3762015-11-02 20:38:179705 req->Cancel();
Wez2a31b222018-06-07 22:07:159706 d.RunUntilComplete();
mmenke2281f3762015-11-02 20:38:179707 // Run pending error task, if there is one.
9708 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:549709
9710 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:179711 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509712 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:179713
9714 // NetworkDelegate should see the cancellation, but not the error.
9715 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
9716 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:549717}
9718
ttuttlec0c828492015-05-15 01:25:559719TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:559720 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559721
9722 TestDelegate d;
tommycli59a63432015-11-06 00:10:559723 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079724 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169725 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559726
9727 req->Start();
Wez2a31b222018-06-07 22:07:159728 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559729
9730 EXPECT_TRUE(req->response_info().network_accessed);
9731}
9732
9733TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:559734 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559735
9736 // Populate the cache.
9737 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079738 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169739 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9740 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559741 req->Start();
Wez2a31b222018-06-07 22:07:159742 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559743
maksim.sisovb53724b52016-09-16 05:30:509744 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559745 EXPECT_TRUE(req->response_info().network_accessed);
9746 EXPECT_FALSE(req->response_info().was_cached);
9747
Ryan Sleevib8449e02018-07-15 04:31:079748 req = default_context().CreateRequest(
9749 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9750 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:559751 req->Start();
Wez2a31b222018-06-07 22:07:159752 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559753
maksim.sisovb53724b52016-09-16 05:30:509754 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559755 EXPECT_FALSE(req->response_info().network_accessed);
9756 EXPECT_TRUE(req->response_info().was_cached);
9757}
9758
9759TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:559760 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559761
9762 TestDelegate d;
tommycli59a63432015-11-06 00:10:559763 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079764 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169765 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:339766 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:559767
9768 req->Start();
Wez2a31b222018-06-07 22:07:159769 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559770
9771 EXPECT_FALSE(req->response_info().network_accessed);
9772}
9773
rdsmithbf8c3c12016-11-18 18:16:249774// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:089775// correctly in the absence of contention.
9776TEST_F(URLRequestTestHTTP, ThrottledPriority) {
9777 ASSERT_TRUE(http_test_server()->Start());
9778
9779 TestDelegate d;
9780 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079781 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169782 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:089783 req->Start();
Wez2a31b222018-06-07 22:07:159784 d.RunUntilComplete();
rdsmith5eb6fbc2016-10-21 17:36:089785
9786 EXPECT_TRUE(req->status().is_success());
9787}
9788
ricea3a1c71f2016-06-17 10:05:269789TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
9790 ASSERT_TRUE(http_test_server()->Start());
9791
9792 TestDelegate d;
9793 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169794 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9795 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269796 req->Start();
Wez2a31b222018-06-07 22:07:159797 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269798
9799 EXPECT_EQ(5, req->GetRawBodyBytes());
9800}
9801
9802TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
9803 ASSERT_TRUE(http_test_server()->Start());
9804
9805 TestDelegate d;
9806 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169807 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
9808 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269809 req->Start();
Wez2a31b222018-06-07 22:07:159810 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269811
9812 EXPECT_EQ(30, req->GetRawBodyBytes());
9813}
9814
jamd3f5a3c2016-10-27 18:52:029815// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
9816// the delegate isn't called back synchronously.
9817TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
9818 ASSERT_TRUE(http_test_server()->Start());
9819 default_network_delegate_.set_before_start_transaction_fails();
9820
9821 TestDelegate d;
9822 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169823 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
9824 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:029825 req->Start();
9826 DCHECK(!d.response_completed());
Wez2a31b222018-06-07 22:07:159827 d.RunUntilComplete();
jamd3f5a3c2016-10-27 18:52:029828 DCHECK(d.response_completed());
9829 EXPECT_EQ(ERR_FAILED, d.request_status());
9830}
9831
bengr1bf8e942014-11-07 01:36:509832class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9833 public:
9834 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9835 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9836 // tests into the factory tests.
Raul Tambre94493c652019-03-11 17:18:359837 URLRequestInterceptorTestHTTP()
9838 : URLRequestTestHTTP(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:509839
9840 void SetUpFactory() override {
9841 interceptor_ = new MockURLRequestInterceptor();
9842 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369843 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509844 }
9845
9846 MockURLRequestInterceptor* interceptor() const {
9847 return interceptor_;
9848 }
9849
9850 private:
9851 MockURLRequestInterceptor* interceptor_;
9852};
9853
9854TEST_F(URLRequestInterceptorTestHTTP,
9855 NetworkDelegateNotificationOnRedirectIntercept) {
9856 interceptor()->set_intercept_redirect(true);
9857 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9858 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9859
tommycli59a63432015-11-06 00:10:559860 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509861
9862 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369863 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169864 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9865 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509866 req->Start();
Wez2a31b222018-06-07 22:07:159867 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509868
9869 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9870 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509871 int status = d.request_status();
9872 EXPECT_EQ(OK, status);
9873 if (status == OK)
bengr1bf8e942014-11-07 01:36:509874 EXPECT_EQ(200, req->response_headers()->response_code());
9875
9876 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9877 EXPECT_EQ(1, d.response_started_count());
9878 EXPECT_EQ(0, d.received_redirect_count());
9879
9880 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009881 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509882 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9883}
9884
9885TEST_F(URLRequestInterceptorTestHTTP,
9886 NetworkDelegateNotificationOnErrorIntercept) {
9887 // Intercept that error and respond with an OK response.
9888 interceptor()->set_intercept_final_response(true);
9889 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9890 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9891 default_network_delegate()->set_can_be_intercepted_on_error(true);
9892
tommycli59a63432015-11-06 00:10:559893 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509894
9895 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369896 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559897 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169898 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509899 req->set_method("GET");
9900 req->Start();
Wez2a31b222018-06-07 22:07:159901 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509902
9903 EXPECT_TRUE(interceptor()->did_intercept_final());
9904
9905 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509906 int status = d.request_status();
9907 EXPECT_EQ(OK, status);
9908 if (status == OK)
bengr1bf8e942014-11-07 01:36:509909 EXPECT_EQ(200, req->response_headers()->response_code());
9910 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9911 EXPECT_EQ(1, d.response_started_count());
9912 EXPECT_EQ(0, d.received_redirect_count());
9913
9914 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009915 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509916 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9917}
9918
9919TEST_F(URLRequestInterceptorTestHTTP,
9920 NetworkDelegateNotificationOnResponseIntercept) {
9921 // Intercept that error and respond with an OK response.
9922 interceptor()->set_intercept_final_response(true);
9923
9924 // Intercept with a real URLRequestHttpJob.
9925 interceptor()->set_use_url_request_http_job(true);
9926
tommycli59a63432015-11-06 00:10:559927 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509928
9929 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369930 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169931 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9932 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509933 req->set_method("GET");
9934 req->Start();
Wez2a31b222018-06-07 22:07:159935 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509936
9937 EXPECT_TRUE(interceptor()->did_intercept_final());
9938
9939 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509940 int status = d.request_status();
9941 EXPECT_EQ(OK, status);
9942 if (status == OK)
bengr1bf8e942014-11-07 01:36:509943 EXPECT_EQ(200, req->response_headers()->response_code());
9944 EXPECT_EQ("hello", d.data_received());
9945 EXPECT_EQ(1, d.response_started_count());
9946 EXPECT_EQ(0, d.received_redirect_count());
9947
9948 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009949 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509950 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9951}
9952
mkwst0c5eab872014-11-21 14:18:549953class URLRequestTestReferrerPolicy : public URLRequestTest {
9954 public:
Chris Watkins7a41d3552017-12-01 02:13:279955 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:549956
tommycli59a63432015-11-06 00:10:559957 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9958 origin_server_.reset(new EmbeddedTestServer(type));
9959 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9960 origin_server_->AddDefaultHandlers(
9961 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9962 } else {
9963 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9964 }
mkwst0c5eab872014-11-21 14:18:549965 ASSERT_TRUE(origin_server_->Start());
9966 }
9967
tommycli59a63432015-11-06 00:10:559968 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9969 net::EmbeddedTestServer::Type dest_type) {
9970 origin_server_.reset(new EmbeddedTestServer(origin_type));
9971 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9972 origin_server_->AddDefaultHandlers(
9973 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9974 } else {
9975 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9976 }
mkwst0c5eab872014-11-21 14:18:549977 ASSERT_TRUE(origin_server_->Start());
9978
tommycli59a63432015-11-06 00:10:559979 destination_server_.reset(new EmbeddedTestServer(dest_type));
9980 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9981 destination_server_->AddDefaultHandlers(
9982 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9983 } else {
9984 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9985 }
mkwst0c5eab872014-11-21 14:18:549986 ASSERT_TRUE(destination_server_->Start());
9987 }
9988
9989 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9990 const GURL& referrer,
9991 const GURL& expected) {
9992 // Create and execute the request: we'll only have a |destination_server_|
9993 // if the origins are meant to be distinct. Otherwise, we'll use the
9994 // |origin_server_| for both endpoints.
9995 GURL destination_url =
tommycli59a63432015-11-06 00:10:559996 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9997 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549998 GURL origin_url =
tommycli59a63432015-11-06 00:10:559999 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:5410000
10001 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0710002 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610003 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:5410004 req->set_referrer_policy(policy);
10005 req->SetReferrer(referrer.spec());
10006 req->Start();
Wez2a31b222018-06-07 22:07:1510007 d.RunUntilComplete();
mkwst0c5eab872014-11-21 14:18:5410008
10009 EXPECT_EQ(1, d.response_started_count());
10010 EXPECT_EQ(1, d.received_redirect_count());
10011 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:5010012 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:5410013 EXPECT_EQ(200, req->response_headers()->response_code());
10014
10015 EXPECT_EQ(expected.spec(), req->referrer());
10016 if (expected.is_empty())
10017 EXPECT_EQ("None", d.data_received());
10018 else
10019 EXPECT_EQ(expected.spec(), d.data_received());
10020 }
10021
tommycli59a63432015-11-06 00:10:5510022 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:5410023
10024 private:
danakj8522a25b2016-04-16 00:17:3610025 std::unique_ptr<EmbeddedTestServer> origin_server_;
10026 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:5410027};
10028
10029TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:5510030 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:5410031
estarkc8ccba82017-06-13 22:37:4010032 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410033 VerifyReferrerAfterRedirect(
10034 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010035 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410036
10037 VerifyReferrerAfterRedirect(
10038 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010039 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410040
10041 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010042 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410043
estarkc8ccba82017-06-13 22:37:4010044 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10045 referrer);
10046
10047 // The original referrer set on the request is expected to obey the referrer
10048 // policy and already be stripped to the origin; thus this test case just
10049 // checks that this policy doesn't cause the referrer to change when following
10050 // a redirect.
10051 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10052 referrer.GetOrigin());
10053
10054 VerifyReferrerAfterRedirect(
10055 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
10056 referrer);
10057
10058 // The original referrer set on the request is expected to obey the referrer
10059 // policy and already be stripped to the origin; thus this test case just
10060 // checks that this policy doesn't cause the referrer to change when following
10061 // a redirect.
10062 VerifyReferrerAfterRedirect(
10063 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10064 referrer.GetOrigin(), referrer.GetOrigin());
10065
10066 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410067}
10068
tommycli59a63432015-11-06 00:10:5510069TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
10070 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
10071 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:4010072 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410073
10074 VerifyReferrerAfterRedirect(
10075 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010076 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410077
10078 VerifyReferrerAfterRedirect(
10079 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010080 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:5410081
10082 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010083 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
10084 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:5410085
estarkc8ccba82017-06-13 22:37:4010086 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10087 referrer);
10088
10089 // The original referrer set on the request is expected to obey the referrer
10090 // policy and already be stripped to the origin; thus this test case just
10091 // checks that this policy doesn't cause the referrer to change when following
10092 // a redirect.
10093 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10094 referrer.GetOrigin());
10095
10096 VerifyReferrerAfterRedirect(
10097 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10098
10099 // The original referrer set on the request is expected to obey the referrer
10100 // policy and already be stripped to the origin; thus this test case just
10101 // checks that this policy doesn't cause the referrer to change when following
10102 // a redirect.
10103 VerifyReferrerAfterRedirect(
10104 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10105 referrer.GetOrigin(), referrer.GetOrigin());
10106
10107 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410108}
10109
10110TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:5510111 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:4010112 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410113
10114 VerifyReferrerAfterRedirect(
10115 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010116 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410117
10118 VerifyReferrerAfterRedirect(
10119 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010120 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410121
10122 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010123 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410124
estarkc8ccba82017-06-13 22:37:4010125 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10126 referrer);
10127
10128 // The original referrer set on the request is expected to obey the referrer
10129 // policy and already be stripped to the origin; thus this test case just
10130 // checks that this policy doesn't cause the referrer to change when following
10131 // a redirect.
10132 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10133 referrer.GetOrigin());
10134
10135 VerifyReferrerAfterRedirect(
10136 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
10137 referrer);
10138
10139 // The original referrer set on the request is expected to obey the referrer
10140 // policy and already be stripped to the origin; thus this test case just
10141 // checks that this policy doesn't cause the referrer to change when following
10142 // a redirect.
10143 VerifyReferrerAfterRedirect(
10144 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10145 referrer.GetOrigin(), referrer.GetOrigin());
10146
10147 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410148}
10149
tommycli59a63432015-11-06 00:10:5510150TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
10151 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
10152 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:4010153 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410154
10155 VerifyReferrerAfterRedirect(
10156 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010157 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410158
10159 VerifyReferrerAfterRedirect(
10160 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010161 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410162
10163 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010164 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:5510165 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410166
estarkc8ccba82017-06-13 22:37:4010167 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10168 referrer);
10169
10170 // The original referrer set on the request is expected to obey the referrer
10171 // policy and already be stripped to the origin; thus this test case just
10172 // checks that this policy doesn't cause the referrer to change when following
10173 // a redirect.
10174 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10175 referrer.GetOrigin());
10176
10177 VerifyReferrerAfterRedirect(
10178 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10179
10180 // The original referrer set on the request is expected to obey the referrer
10181 // policy and already be stripped to the origin; thus this test case just
10182 // checks that this policy doesn't cause the referrer to change when following
10183 // a redirect.
10184 VerifyReferrerAfterRedirect(
10185 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10186 referrer.GetOrigin(), referrer.GetOrigin());
10187
10188 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410189}
10190
tommycli59a63432015-11-06 00:10:5510191TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
10192 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
10193 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:4010194 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410195
10196 VerifyReferrerAfterRedirect(
10197 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010198 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410199
10200 VerifyReferrerAfterRedirect(
10201 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010202 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410203
10204 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010205 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:5510206 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410207
estarkc8ccba82017-06-13 22:37:4010208 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10209 referrer);
10210
10211 // The original referrer set on the request is expected to obey the referrer
10212 // policy and already be stripped to the origin; thus this test case just
10213 // checks that this policy doesn't cause the referrer to change when following
10214 // a redirect.
10215 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10216 referrer.GetOrigin());
10217
10218 VerifyReferrerAfterRedirect(
10219 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10220
10221 // The original referrer set on the request is expected to obey the referrer
10222 // policy and already be stripped to the origin; thus this test case just
10223 // checks that this policy doesn't cause the referrer to change when following
10224 // a redirect.
10225 VerifyReferrerAfterRedirect(
10226 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10227 referrer.GetOrigin(), referrer.GetOrigin());
10228
10229 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410230}
10231
tommycli59a63432015-11-06 00:10:5510232TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
10233 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
10234 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:4010235 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410236
10237 VerifyReferrerAfterRedirect(
10238 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010239 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:5410240
10241 VerifyReferrerAfterRedirect(
10242 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010243 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:5410244
10245 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010246 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:5510247 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410248
estarkc8ccba82017-06-13 22:37:4010249 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10250 referrer);
10251
10252 // The original referrer set on the request is expected to obey the referrer
10253 // policy and already be stripped to the origin; thus this test case just
10254 // checks that this policy doesn't cause the referrer to change when following
10255 // a redirect.
10256 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10257 referrer.GetOrigin());
10258
10259 VerifyReferrerAfterRedirect(
10260 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10261
10262 // The original referrer set on the request is expected to obey the referrer
10263 // policy and already be stripped to the origin, though it should be
10264 // subsequently cleared during the downgrading redirect.
10265 VerifyReferrerAfterRedirect(
10266 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10267 referrer.GetOrigin(), GURL());
10268
10269 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410270}
10271
Gabriel Charette694c3c332019-08-19 14:53:0510272class HTTPSRequestTest : public TestWithTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:5010273 public:
fdorayf33fede2017-05-11 21:18:1010274 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:0910275 default_context_.set_network_delegate(&default_network_delegate_);
10276 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:5010277 }
Martijn Croonenb1383da2017-10-11 11:56:3510278 ~HTTPSRequestTest() override {
10279 SetTransportSecurityStateSourceForTesting(nullptr);
10280 }
[email protected]87a09a92011-07-14 15:50:5010281
10282 protected:
[email protected]ceefd7fd2012-11-29 00:36:2410283 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:0910284 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:4610285};
10286
[email protected]c044616e2013-02-20 02:01:2610287TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:5510288 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10289 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210290 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:1110291 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:4610292
[email protected]ea224582008-12-07 20:25:4610293 TestDelegate d;
10294 {
danakj8522a25b2016-04-16 00:17:3610295 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610296 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10297 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910298 r->Start();
10299 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:4610300
Wez2a31b222018-06-07 22:07:1510301 d.RunUntilComplete();
[email protected]ea224582008-12-07 20:25:4610302
10303 EXPECT_EQ(1, d.response_started_count());
10304 EXPECT_FALSE(d.received_data_before_response());
10305 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:1910306 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:1910307 EXPECT_EQ(test_server.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3710308 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
[email protected]6d81b482011-02-22 19:47:1910309 EXPECT_EQ(test_server.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3710310 r->GetResponseRemoteEndpoint().port());
[email protected]ea224582008-12-07 20:25:4610311 }
[email protected]ea224582008-12-07 20:25:4610312}
10313
[email protected]5774ada2010-07-15 06:30:5410314TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:5510315 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10316 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10317 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210318 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:1110319 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:3310320
10321 bool err_allowed = true;
10322 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
10323 TestDelegate d;
10324 {
10325 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:3610326 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610327 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10328 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:3310329
[email protected]f7022f32014-08-21 16:32:1910330 r->Start();
10331 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:3310332
Wez2a31b222018-06-07 22:07:1510333 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:3310334
10335 EXPECT_EQ(1, d.response_started_count());
10336 EXPECT_FALSE(d.received_data_before_response());
10337 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:1710338 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:3310339 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:1910340 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:1710341 } else {
[email protected]bacff652009-03-31 17:50:3310342 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:1710343 }
[email protected]bacff652009-03-31 17:50:3310344 }
10345 }
10346}
10347
[email protected]5774ada2010-07-15 06:30:5410348TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:5510349 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10350 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
10351 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210352 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:1110353 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:3310354
10355 // Iterate from false to true, just so that we do the opposite of the
10356 // previous test in order to increase test coverage.
10357 bool err_allowed = false;
10358 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
10359 TestDelegate d;
10360 {
10361 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:3610362 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610363 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10364 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:3310365
[email protected]f7022f32014-08-21 16:32:1910366 r->Start();
10367 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:3310368
Wez2a31b222018-06-07 22:07:1510369 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:3310370
10371 EXPECT_EQ(1, d.response_started_count());
10372 EXPECT_FALSE(d.received_data_before_response());
10373 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:1710374 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:3310375 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:1910376 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:1710377 } else {
[email protected]bacff652009-03-31 17:50:3310378 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:1710379 }
[email protected]bacff652009-03-31 17:50:3310380 }
10381 }
10382}
[email protected]73e0bba2009-02-19 22:57:0910383
Emily Stark79fba5842019-04-25 04:59:3610384// A TestDelegate used to test that an appropriate net error code is provided
10385// when an SSL certificate error occurs.
10386class SSLNetErrorTestDelegate : public TestDelegate {
10387 public:
10388 void OnSSLCertificateError(URLRequest* request,
10389 int net_error,
10390 const SSLInfo& ssl_info,
10391 bool fatal) override {
10392 net_error_ = net_error;
10393 on_ssl_certificate_error_called_ = true;
10394 TestDelegate::OnSSLCertificateError(request, net_error, ssl_info, fatal);
10395 }
10396
10397 bool on_ssl_certificate_error_called() {
10398 return on_ssl_certificate_error_called_;
10399 }
10400
10401 int net_error() { return net_error_; }
10402
10403 private:
10404 bool on_ssl_certificate_error_called_ = false;
10405 int net_error_ = net::OK;
10406};
10407
10408// Tests that the URLRequest::Delegate receives an appropriate net error code
10409// when an SSL certificate error occurs.
10410TEST_F(HTTPSRequestTest, SSLNetErrorReportedToDelegate) {
10411 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10412 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
10413 test_server.AddDefaultHandlers(
10414 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10415 ASSERT_TRUE(test_server.Start());
10416
10417 SSLNetErrorTestDelegate d;
10418 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10419 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10420 TRAFFIC_ANNOTATION_FOR_TESTS));
10421 r->Start();
10422 EXPECT_TRUE(r->is_pending());
10423 d.RunUntilComplete();
10424
10425 EXPECT_TRUE(d.on_ssl_certificate_error_called());
10426 EXPECT_EQ(net::ERR_CERT_DATE_INVALID, d.net_error());
10427}
10428
tommycli59a63432015-11-06 00:10:5510429// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
10430// security state. (see http://crbug.com/550977).
10431#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:3510432// This tests that a load of a domain with preloaded HSTS and HPKP with a
10433// certificate error sets the |certificate_errors_are_fatal| flag correctly.
10434// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:4410435TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:3510436 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
10437
tommycli59a63432015-11-06 00:10:5510438 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10439 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10440 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:4410441 ASSERT_TRUE(test_server.Start());
10442
Martijn Croonenb1383da2017-10-11 11:56:3510443 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
10444 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
10445 // means that we have to use a MockHostResolver in order to direct
10446 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
10447 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:4410448
10449 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:2410450 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:4410451 TestURLRequestContext context(true);
10452 context.set_network_delegate(&network_delegate);
10453 context.set_host_resolver(&host_resolver);
10454 TransportSecurityState transport_security_state;
10455 context.set_transport_security_state(&transport_security_state);
10456 context.Init();
10457
10458 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610459 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:3510460 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:3610461 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610462 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410463
[email protected]f7022f32014-08-21 16:32:1910464 r->Start();
10465 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410466
Wez2a31b222018-06-07 22:07:1510467 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410468
10469 EXPECT_EQ(1, d.response_started_count());
10470 EXPECT_FALSE(d.received_data_before_response());
10471 EXPECT_TRUE(d.have_certificate_errors());
10472 EXPECT_TRUE(d.certificate_errors_are_fatal());
10473}
10474
10475// This tests that cached HTTPS page loads do not cause any updates to the
10476// TransportSecurityState.
10477TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:3510478 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
10479
[email protected]316c1e5e2012-09-12 15:17:4410480 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
10481 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:5510482 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10483 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10484 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:4410485 ASSERT_TRUE(test_server.Start());
10486
Martijn Croonenb1383da2017-10-11 11:56:3510487 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
10488 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
10489 // means that we have to use a MockHostResolver in order to direct
10490 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
10491 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:4410492
10493 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:2410494 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:4410495 TestURLRequestContext context(true);
10496 context.set_network_delegate(&network_delegate);
10497 context.set_host_resolver(&host_resolver);
10498 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:2610499
martijnc0d6b622015-06-30 19:14:4010500 TransportSecurityState::STSState static_sts_state;
10501 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610502 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510503 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:4410504 context.set_transport_security_state(&transport_security_state);
10505 context.Init();
10506
martijnc0d6b622015-06-30 19:14:4010507 TransportSecurityState::STSState dynamic_sts_state;
10508 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:3510509 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
10510 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
10511 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
10512 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610513
[email protected]316c1e5e2012-09-12 15:17:4410514 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610515 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:3510516 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:3610517 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610518 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410519
[email protected]f7022f32014-08-21 16:32:1910520 r->Start();
10521 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410522
Wez2a31b222018-06-07 22:07:1510523 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410524
10525 EXPECT_EQ(1, d.response_started_count());
10526 EXPECT_FALSE(d.received_data_before_response());
10527 EXPECT_TRUE(d.have_certificate_errors());
10528 EXPECT_TRUE(d.certificate_errors_are_fatal());
10529
[email protected]9e6968d2014-05-07 21:46:2610530 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:4010531 TransportSecurityState::STSState new_static_sts_state;
10532 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610533 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510534 "hsts-hpkp-preloaded.test", &new_static_sts_state,
10535 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:4010536 TransportSecurityState::STSState new_dynamic_sts_state;
10537 TransportSecurityState::PKPState new_dynamic_pkp_state;
10538 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:3510539 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:4010540 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:3510541 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610542
martijnc0d6b622015-06-30 19:14:4010543 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
10544 EXPECT_EQ(new_static_sts_state.include_subdomains,
10545 static_sts_state.include_subdomains);
10546 EXPECT_EQ(new_static_pkp_state.include_subdomains,
10547 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:4810548 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
10549 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
10550 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:4410551}
10552
[email protected]8ccc69f2012-11-28 19:52:1410553// Make sure HSTS preserves a POST request's method and body.
10554TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
10555 static const char kData[] = "hello world";
10556
tommycli59a63432015-11-06 00:10:5510557 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10558 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210559 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:1410560 ASSERT_TRUE(test_server.Start());
10561
10562
10563 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10564 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:5510565 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:2210566 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:1410567 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:1410568
10569 // Force https for www.somewhere.com.
10570 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:2010571 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
10572 bool include_subdomains = false;
10573 transport_security_state.AddHSTS("www.somewhere.com", expiry,
10574 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:1410575
10576 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10577
10578 TestURLRequestContext context(true);
10579 context.set_host_resolver(&host_resolver);
10580 context.set_transport_security_state(&transport_security_state);
10581 context.set_network_delegate(&network_delegate);
10582 context.Init();
10583
10584 TestDelegate d;
10585 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
10586 // cause a certificate error. Ignore the error.
10587 d.set_allow_certificate_errors(true);
10588
danakj8522a25b2016-04-16 00:17:3610589 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:1910590 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:3610591 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610592 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910593 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:0710594 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:1410595
[email protected]f7022f32014-08-21 16:32:1910596 req->Start();
Wez2a31b222018-06-07 22:07:1510597 d.RunUntilComplete();
[email protected]8ccc69f2012-11-28 19:52:1410598
[email protected]f7022f32014-08-21 16:32:1910599 EXPECT_EQ("https", req->url().scheme());
10600 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:1410601 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:4010602
10603 LoadTimingInfo load_timing_info;
10604 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
10605 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
10606 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:1410607}
10608
rob4e0be1f2014-09-11 23:40:2210609// Make sure that the CORS headers are added to cross-origin HSTS redirects.
10610TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
10611 static const char kOriginHeaderValue[] = "http://www.example.com";
10612
tommycli59a63432015-11-06 00:10:5510613 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10614 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:2210615 ASSERT_TRUE(test_server.Start());
10616
10617 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10618 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:5510619 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
10620 // default.
rob4e0be1f2014-09-11 23:40:2210621 MockHostResolver host_resolver;
10622
10623 TransportSecurityState transport_security_state;
10624 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
10625 bool include_subdomains = false;
10626 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
10627
10628 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10629
10630 MockCertVerifier cert_verifier;
10631 cert_verifier.set_default_result(OK);
10632
10633 TestURLRequestContext context(true);
10634 context.set_host_resolver(&host_resolver);
10635 context.set_transport_security_state(&transport_security_state);
10636 context.set_network_delegate(&network_delegate);
10637 context.set_cert_verifier(&cert_verifier);
10638 context.Init();
10639
10640 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
10641 test_server.host_port_pair().port()));
10642 url::Replacements<char> replacements;
10643 const char kNewScheme[] = "https";
10644 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
10645 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
10646
10647 TestDelegate d;
rob4e0be1f2014-09-11 23:40:2210648
rhalavatib7bd7c792017-04-27 05:25:1610649 std::unique_ptr<URLRequest> req(context.CreateRequest(
10650 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:2210651 // Set Origin header to simulate a cross-origin request.
10652 HttpRequestHeaders request_headers;
10653 request_headers.SetHeader("Origin", kOriginHeaderValue);
10654 req->SetExtraRequestHeaders(request_headers);
10655
10656 req->Start();
Wez0e717112018-06-18 23:09:2210657 d.RunUntilRedirect();
rob4e0be1f2014-09-11 23:40:2210658
10659 EXPECT_EQ(1, d.received_redirect_count());
10660
10661 const HttpResponseHeaders* headers = req->response_headers();
10662 std::string redirect_location;
Raul Tambre94493c652019-03-11 17:18:3510663 EXPECT_TRUE(
10664 headers->EnumerateHeader(nullptr, "Location", &redirect_location));
rob4e0be1f2014-09-11 23:40:2210665 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
10666
10667 std::string received_cors_header;
Raul Tambre94493c652019-03-11 17:18:3510668 EXPECT_TRUE(headers->EnumerateHeader(nullptr, "Access-Control-Allow-Origin",
rob4e0be1f2014-09-11 23:40:2210669 &received_cors_header));
10670 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
10671}
10672
[email protected]316c1e5e2012-09-12 15:17:4410673namespace {
10674
10675class SSLClientAuthTestDelegate : public TestDelegate {
10676 public:
10677 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
Wez0e717112018-06-18 23:09:2210678 set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:4410679 }
dchengb03027d2014-10-21 12:00:2010680 void OnCertificateRequested(URLRequest* request,
10681 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:4410682 on_certificate_requested_count_++;
Wez0e717112018-06-18 23:09:2210683 std::move(on_certificate_requested_).Run();
10684 }
10685 void RunUntilCertificateRequested() {
10686 base::RunLoop run_loop;
10687 on_certificate_requested_ = run_loop.QuitClosure();
10688 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:4410689 }
10690 int on_certificate_requested_count() {
10691 return on_certificate_requested_count_;
10692 }
10693 private:
10694 int on_certificate_requested_count_;
Wez0e717112018-06-18 23:09:2210695 base::OnceClosure on_certificate_requested_;
[email protected]316c1e5e2012-09-12 15:17:4410696};
10697
David Benjamin76a40ad2018-02-24 22:22:0810698class TestSSLPrivateKey : public SSLPrivateKey {
10699 public:
10700 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
10701 : key_(std::move(key)) {}
10702
10703 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
10704 int sign_count() const { return sign_count_; }
10705
David Benjaminb65b0732018-11-09 20:33:5310706 std::string GetProviderName() override { return key_->GetProviderName(); }
David Benjamin76a40ad2018-02-24 22:22:0810707 std::vector<uint16_t> GetAlgorithmPreferences() override {
10708 return key_->GetAlgorithmPreferences();
10709 }
10710 void Sign(uint16_t algorithm,
10711 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:2610712 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:0810713 sign_count_++;
10714 if (fail_signing_) {
10715 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:2610716 FROM_HERE, base::BindOnce(std::move(callback),
10717 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
10718 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:0810719 } else {
David Benjamin8f2d2c12018-02-27 00:08:2610720 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:0810721 }
10722 }
10723
10724 private:
10725 ~TestSSLPrivateKey() override = default;
10726
10727 scoped_refptr<SSLPrivateKey> key_;
10728 bool fail_signing_ = false;
10729 int sign_count_ = 0;
10730};
10731
[email protected]316c1e5e2012-09-12 15:17:4410732} // namespace
10733
10734// TODO(davidben): Test the rest of the code. Specifically,
10735// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:4410736// - Getting a certificate request in an SSL renegotiation sending the
10737// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:0810738TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:5510739 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10740 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:1210741 ssl_config.client_cert_type =
10742 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:0810743 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:5510744 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210745 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410746 ASSERT_TRUE(test_server.Start());
10747
10748 SSLClientAuthTestDelegate d;
10749 {
danakj8522a25b2016-04-16 00:17:3610750 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610751 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10752 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410753
[email protected]f7022f32014-08-21 16:32:1910754 r->Start();
10755 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410756
Wez0e717112018-06-18 23:09:2210757 d.RunUntilCertificateRequested();
10758 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410759
10760 EXPECT_EQ(1, d.on_certificate_requested_count());
10761 EXPECT_FALSE(d.received_data_before_response());
10762 EXPECT_EQ(0, d.bytes_received());
10763
10764 // Send no certificate.
10765 // TODO(davidben): Get temporary client cert import (with keys) working on
10766 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:5410767 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:4410768
Wez2a31b222018-06-07 22:07:1510769 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410770
David Benjamin76a40ad2018-02-24 22:22:0810771 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:4410772 EXPECT_EQ(1, d.response_started_count());
10773 EXPECT_FALSE(d.received_data_before_response());
10774 EXPECT_NE(0, d.bytes_received());
10775 }
10776}
10777
David Benjamin76a40ad2018-02-24 22:22:0810778TEST_F(HTTPSRequestTest, ClientAuth) {
10779 std::unique_ptr<FakeClientCertIdentity> identity =
10780 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10781 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10782 ASSERT_TRUE(identity);
10783 scoped_refptr<TestSSLPrivateKey> private_key =
10784 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10785
10786 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10787 net::SSLServerConfig ssl_config;
10788 ssl_config.client_cert_type =
10789 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10790 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10791 test_server.AddDefaultHandlers(
10792 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10793 ASSERT_TRUE(test_server.Start());
10794
10795 {
10796 SSLClientAuthTestDelegate d;
10797 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10798 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10799 TRAFFIC_ANNOTATION_FOR_TESTS));
10800
10801 r->Start();
10802 EXPECT_TRUE(r->is_pending());
10803
Wez0e717112018-06-18 23:09:2210804 d.RunUntilCertificateRequested();
10805 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810806
10807 EXPECT_EQ(1, d.on_certificate_requested_count());
10808 EXPECT_FALSE(d.received_data_before_response());
10809 EXPECT_EQ(0, d.bytes_received());
10810
10811 // Send a certificate.
10812 r->ContinueWithCertificate(identity->certificate(), private_key);
10813
Wez2a31b222018-06-07 22:07:1510814 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810815
10816 EXPECT_EQ(OK, d.request_status());
10817 EXPECT_EQ(1, d.response_started_count());
10818 EXPECT_FALSE(d.received_data_before_response());
10819 EXPECT_NE(0, d.bytes_received());
10820
10821 // The private key should have been used.
10822 EXPECT_EQ(1, private_key->sign_count());
10823 }
10824
10825 // Close all connections and clear the session cache to force a new handshake.
10826 default_context_.http_transaction_factory()
10827 ->GetSession()
10828 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710829 default_context_.http_transaction_factory()
10830 ->GetSession()
10831 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810832
10833 // Connecting again should not call OnCertificateRequested. The identity is
10834 // taken from the client auth cache.
10835 {
10836 SSLClientAuthTestDelegate d;
10837 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10838 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10839 TRAFFIC_ANNOTATION_FOR_TESTS));
10840
10841 r->Start();
10842 EXPECT_TRUE(r->is_pending());
10843
Wez2a31b222018-06-07 22:07:1510844 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810845
10846 EXPECT_EQ(OK, d.request_status());
10847 EXPECT_EQ(0, d.on_certificate_requested_count());
10848 EXPECT_FALSE(d.received_data_before_response());
10849 EXPECT_EQ(1, d.response_started_count());
10850 EXPECT_FALSE(d.received_data_before_response());
10851 EXPECT_NE(0, d.bytes_received());
10852
10853 // The private key should have been used.
10854 EXPECT_EQ(2, private_key->sign_count());
10855 }
10856}
10857
10858// Test that private keys that fail to sign anything get evicted from the cache.
10859TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
10860 std::unique_ptr<FakeClientCertIdentity> identity =
10861 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10862 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10863 ASSERT_TRUE(identity);
10864 scoped_refptr<TestSSLPrivateKey> private_key =
10865 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10866 private_key->set_fail_signing(true);
10867
10868 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10869 net::SSLServerConfig ssl_config;
10870 ssl_config.client_cert_type =
10871 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10872 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10873 test_server.AddDefaultHandlers(
10874 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10875 ASSERT_TRUE(test_server.Start());
10876
10877 {
10878 SSLClientAuthTestDelegate d;
10879 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10880 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10881 TRAFFIC_ANNOTATION_FOR_TESTS));
10882
10883 r->Start();
10884 EXPECT_TRUE(r->is_pending());
Wez0e717112018-06-18 23:09:2210885
10886 d.RunUntilCertificateRequested();
10887 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810888
10889 EXPECT_EQ(1, d.on_certificate_requested_count());
10890 EXPECT_FALSE(d.received_data_before_response());
10891 EXPECT_EQ(0, d.bytes_received());
10892
10893 // Send a certificate.
10894 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510895 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810896
10897 // The private key cannot sign anything, so we report an error.
10898 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
10899 EXPECT_EQ(1, d.response_started_count());
10900 EXPECT_FALSE(d.received_data_before_response());
10901 EXPECT_EQ(0, d.bytes_received());
10902
10903 // The private key should have been used.
10904 EXPECT_EQ(1, private_key->sign_count());
10905 }
10906
10907 // Close all connections and clear the session cache to force a new handshake.
10908 default_context_.http_transaction_factory()
10909 ->GetSession()
10910 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710911 default_context_.http_transaction_factory()
10912 ->GetSession()
10913 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810914
10915 // The bad identity should have been evicted from the cache, so connecting
10916 // again should call OnCertificateRequested again.
10917 {
10918 SSLClientAuthTestDelegate d;
10919 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10920 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10921 TRAFFIC_ANNOTATION_FOR_TESTS));
10922
10923 r->Start();
10924 EXPECT_TRUE(r->is_pending());
10925
Wez0e717112018-06-18 23:09:2210926 d.RunUntilCertificateRequested();
10927 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810928
10929 EXPECT_EQ(1, d.on_certificate_requested_count());
10930 EXPECT_FALSE(d.received_data_before_response());
10931 EXPECT_EQ(0, d.bytes_received());
10932
10933 // There should have been no additional uses of the private key.
10934 EXPECT_EQ(1, private_key->sign_count());
10935 }
10936}
10937
10938// Test that cached private keys that fail to sign anything trigger a
10939// retry. This is so we handle unplugged smartcards
10940// gracefully. https://crbug.com/813022.
10941TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
10942 std::unique_ptr<FakeClientCertIdentity> identity =
10943 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10944 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10945 ASSERT_TRUE(identity);
10946 scoped_refptr<TestSSLPrivateKey> private_key =
10947 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10948
10949 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10950 net::SSLServerConfig ssl_config;
10951 ssl_config.client_cert_type =
10952 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10953 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10954 test_server.AddDefaultHandlers(
10955 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10956 ASSERT_TRUE(test_server.Start());
10957
10958 // Connect with a client certificate to put it in the client auth cache.
10959 {
10960 SSLClientAuthTestDelegate d;
10961 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10962 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10963 TRAFFIC_ANNOTATION_FOR_TESTS));
10964
10965 r->Start();
10966 EXPECT_TRUE(r->is_pending());
10967
Wez0e717112018-06-18 23:09:2210968 d.RunUntilCertificateRequested();
10969 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810970
10971 EXPECT_EQ(1, d.on_certificate_requested_count());
10972 EXPECT_FALSE(d.received_data_before_response());
10973 EXPECT_EQ(0, d.bytes_received());
10974
10975 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510976 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810977
10978 EXPECT_EQ(OK, d.request_status());
10979 EXPECT_EQ(1, d.response_started_count());
10980 EXPECT_FALSE(d.received_data_before_response());
10981 EXPECT_NE(0, d.bytes_received());
10982
10983 // The private key should have been used.
10984 EXPECT_EQ(1, private_key->sign_count());
10985 }
10986
10987 // Close all connections and clear the session cache to force a new handshake.
10988 default_context_.http_transaction_factory()
10989 ->GetSession()
10990 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710991 default_context_.http_transaction_factory()
10992 ->GetSession()
10993 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810994
10995 // Cause the private key to fail. Connecting again should attempt to use it,
10996 // notice the failure, and then request a new identity via
10997 // OnCertificateRequested.
10998 private_key->set_fail_signing(true);
10999
11000 {
11001 SSLClientAuthTestDelegate d;
11002 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11003 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11004 TRAFFIC_ANNOTATION_FOR_TESTS));
11005
11006 r->Start();
11007 EXPECT_TRUE(r->is_pending());
11008
Wez0e717112018-06-18 23:09:2211009 d.RunUntilCertificateRequested();
11010 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0811011
11012 // There was an additional signing call on the private key (the one which
11013 // failed).
11014 EXPECT_EQ(2, private_key->sign_count());
11015
11016 // That caused another OnCertificateRequested call.
11017 EXPECT_EQ(1, d.on_certificate_requested_count());
11018 EXPECT_FALSE(d.received_data_before_response());
11019 EXPECT_EQ(0, d.bytes_received());
11020 }
11021}
11022
[email protected]316c1e5e2012-09-12 15:17:4411023TEST_F(HTTPSRequestTest, ResumeTest) {
11024 // Test that we attempt a session resume when making two connections to the
11025 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:2211026 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4411027 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2211028 SpawnedTestServer test_server(
11029 SpawnedTestServer::TYPE_HTTPS,
11030 ssl_options,
11031 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4411032 ASSERT_TRUE(test_server.Start());
11033
Daniel McArdle3a663d62019-01-31 00:48:4711034 default_context_.http_transaction_factory()
11035 ->GetSession()
11036 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4411037
11038 {
11039 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611040 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611041 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
11042 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4411043
[email protected]f7022f32014-08-21 16:32:1911044 r->Start();
11045 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4411046
Wez2a31b222018-06-07 22:07:1511047 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4411048
11049 EXPECT_EQ(1, d.response_started_count());
11050 }
11051
11052 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
11053 CloseAllConnections();
11054
11055 {
11056 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611057 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611058 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
11059 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4411060
[email protected]f7022f32014-08-21 16:32:1911061 r->Start();
11062 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4411063
Wez2a31b222018-06-07 22:07:1511064 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4411065
11066 // The response will look like;
Steven Valdez0ef94d02018-11-19 23:28:1311067 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]316c1e5e2012-09-12 15:17:4411068 // insert abc
11069 // lookup abc
11070 // insert xyz
11071 //
11072 // With a newline at the end which makes the split think that there are
11073 // four lines.
11074
11075 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2911076 std::vector<std::string> lines = base::SplitString(
11077 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Steven Valdez0ef94d02018-11-19 23:28:1311078 ASSERT_EQ(5u, lines.size()) << d.data_received();
[email protected]316c1e5e2012-09-12 15:17:4411079
11080 std::string session_id;
11081
Steven Valdez0ef94d02018-11-19 23:28:1311082 for (size_t i = 0; i < 3; i++) {
brettw3a2c6902015-07-06 19:43:2911083 std::vector<std::string> parts = base::SplitString(
11084 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4411085 ASSERT_EQ(2u, parts.size());
Steven Valdez0ef94d02018-11-19 23:28:1311086 if (i % 2 == 1) {
[email protected]316c1e5e2012-09-12 15:17:4411087 EXPECT_EQ("insert", parts[0]);
11088 session_id = parts[1];
11089 } else {
11090 EXPECT_EQ("lookup", parts[0]);
Steven Valdez0ef94d02018-11-19 23:28:1311091 if (i != 0)
11092 EXPECT_EQ(session_id, parts[1]);
[email protected]316c1e5e2012-09-12 15:17:4411093 }
11094 }
11095 }
11096}
11097
11098TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
11099 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
11100 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2211101 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4411102 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2211103 SpawnedTestServer test_server(
11104 SpawnedTestServer::TYPE_HTTPS,
11105 ssl_options,
11106 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4411107 ASSERT_TRUE(test_server.Start());
11108
Daniel McArdle3a663d62019-01-31 00:48:4711109 default_context_.http_transaction_factory()
11110 ->GetSession()
11111 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4411112
11113 {
11114 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611115 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0411116 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1611117 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4411118
[email protected]f7022f32014-08-21 16:32:1911119 r->Start();
11120 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4411121
Wez2a31b222018-06-07 22:07:1511122 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4411123
11124 EXPECT_EQ(1, d.response_started_count());
11125 }
11126
11127 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4111128 HttpNetworkSession::Context session_context;
11129 session_context.host_resolver = default_context_.host_resolver();
11130 session_context.cert_verifier = default_context_.cert_verifier();
11131 session_context.transport_security_state =
11132 default_context_.transport_security_state();
11133 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2011134 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4111135 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5911136 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4111137 session_context.ssl_config_service = default_context_.ssl_config_service();
11138 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4411139 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4111140 session_context.http_server_properties =
11141 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4411142
mmenke6ddfbea2017-05-31 21:48:4111143 HttpNetworkSession network_session(HttpNetworkSession::Params(),
11144 session_context);
zhongyi4928bd52017-02-08 02:16:2711145 std::unique_ptr<HttpCache> cache(
11146 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
11147 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4411148
11149 default_context_.set_http_transaction_factory(cache.get());
11150
11151 {
11152 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611153 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611154 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
11155 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4411156
[email protected]f7022f32014-08-21 16:32:1911157 r->Start();
11158 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4411159
Wez2a31b222018-06-07 22:07:1511160 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4411161
[email protected]316c1e5e2012-09-12 15:17:4411162 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0411163 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]316c1e5e2012-09-12 15:17:4411164 }
11165}
11166
Daniel McArdleda3fa942019-02-15 16:41:2111167// Test that sessions started with privacy mode enabled cannot be resumed when
11168// it is disabled, and vice versa.
11169TEST_F(HTTPSRequestTest, NoSessionResumptionBetweenPrivacyModes) {
11170 // Start a server.
11171 SpawnedTestServer test_server(
11172 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(),
11173 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11174 ASSERT_TRUE(test_server.Start());
11175 const auto url = test_server.GetURL("/");
11176
11177 auto ConnectAndCheckHandshake = [this, url](bool allow_credentials,
11178 auto expected_handshake) {
11179 // Construct request and indirectly set the privacy mode.
11180 TestDelegate d;
11181 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11182 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11183 r->set_allow_credentials(allow_credentials);
11184
11185 // Start the request and check the SSL handshake type.
11186 r->Start();
11187 EXPECT_TRUE(r->is_pending());
11188 d.RunUntilComplete();
11189 EXPECT_EQ(1, d.response_started_count());
11190 EXPECT_EQ(expected_handshake, r->ssl_info().handshake_type);
11191 };
11192
11193 // Exhaustively check all pairs of privacy mode values. Note that we are using
11194 // allow_credentials to indirectly enable/disable privacy mode.
11195 const bool kAllowCredentialsValues[] = {false, true};
11196 for (const auto allow_creds_1 : kAllowCredentialsValues) {
11197 for (const auto allow_creds_2 : kAllowCredentialsValues) {
11198 SCOPED_TRACE(base::StringPrintf("allow_creds_1=%d, allow_creds_2=%d",
11199 allow_creds_1, allow_creds_2));
11200
11201 // The session cache starts off empty, so we expect a full handshake.
11202 ConnectAndCheckHandshake(allow_creds_1, SSLInfo::HANDSHAKE_FULL);
11203
11204 // The second handshake depends on whether we are using the same session
11205 // cache as the first request.
11206 ConnectAndCheckHandshake(allow_creds_2, allow_creds_1 == allow_creds_2
11207 ? SSLInfo::HANDSHAKE_RESUME
11208 : SSLInfo::HANDSHAKE_FULL);
11209 // Flush both session caches.
11210 auto* network_session =
11211 default_context_.http_transaction_factory()->GetSession();
11212 network_session->ClearSSLSessionCache();
11213 }
11214 }
11215}
11216
Gabriel Charette694c3c332019-08-19 14:53:0511217class HTTPSFallbackTest : public TestWithTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:5511218 public:
fdorayf33fede2017-05-11 21:18:1011219 HTTPSFallbackTest() : context_(true) {
David Benjamin151ec6b2019-08-02 19:38:5211220 ssl_config_service_ =
11221 std::make_unique<TestSSLConfigService>(SSLContextConfig());
davidben095ebb52017-04-12 22:23:3411222 context_.set_ssl_config_service(ssl_config_service_.get());
11223 }
Chris Watkins7a41d3552017-12-01 02:13:2711224 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5511225
11226 protected:
davidben095ebb52017-04-12 22:23:3411227 TestSSLConfigService* ssl_config_service() {
11228 return ssl_config_service_.get();
11229 }
11230
[email protected]48d2b7c52014-06-27 01:16:5511231 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
11232 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0011233 context_.Init();
11234 delegate_.set_allow_certificate_errors(true);
11235
[email protected]48d2b7c52014-06-27 01:16:5511236 SpawnedTestServer test_server(
11237 SpawnedTestServer::TYPE_HTTPS,
11238 ssl_options,
11239 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11240 ASSERT_TRUE(test_server.Start());
11241
tommycli59a63432015-11-06 00:10:5511242 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1611243 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5511244 request_->Start();
11245
Wez2a31b222018-06-07 22:07:1511246 delegate_.RunUntilComplete();
[email protected]48d2b7c52014-06-27 01:16:5511247 }
11248
davidben095ebb52017-04-12 22:23:3411249 void ExpectConnection(int version) {
11250 EXPECT_EQ(1, delegate_.response_started_count());
11251 EXPECT_NE(0, delegate_.bytes_received());
11252 EXPECT_EQ(version, SSLConnectionStatusToVersion(
11253 request_->ssl_info().connection_status));
11254 }
11255
[email protected]48d2b7c52014-06-27 01:16:5511256 void ExpectFailure(int error) {
11257 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5011258 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5511259 }
11260
11261 private:
Ryan Sleevib8449e02018-07-15 04:31:0711262 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5511263 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4711264 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3611265 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:5511266};
11267
davidbenb127ca82015-06-15 19:05:4211268// Tests the TLS 1.0 fallback doesn't happen.
11269TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5511270 SpawnedTestServer::SSLOptions ssl_options(
11271 SpawnedTestServer::SSLOptions::CERT_OK);
11272 ssl_options.tls_intolerant =
11273 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
11274
11275 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5511276 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4211277}
11278
davidben5a312152016-06-27 22:11:4711279// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5511280TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4211281 SpawnedTestServer::SSLOptions ssl_options(
11282 SpawnedTestServer::SSLOptions::CERT_OK);
11283 ssl_options.tls_intolerant =
11284 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
11285
11286 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5511287 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
11288}
11289
David Benjamind61bd532019-04-23 21:11:3711290// Tests the TLS 1.2 fallback doesn't happen.
11291TEST_F(HTTPSFallbackTest, TLSv1_2NoFallback) {
davidben095ebb52017-04-12 22:23:3411292 SpawnedTestServer::SSLOptions ssl_options(
11293 SpawnedTestServer::SSLOptions::CERT_OK);
11294 ssl_options.tls_intolerant =
11295 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
davidben095ebb52017-04-12 22:23:3411296
11297 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
David Benjamind61bd532019-04-23 21:11:3711298 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidben095ebb52017-04-12 22:23:3411299}
11300
Gabriel Charette694c3c332019-08-19 14:53:0511301class HTTPSSessionTest : public TestWithTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:2411302 public:
fdorayf33fede2017-05-11 21:18:1011303 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5911304 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2411305
11306 default_context_.set_network_delegate(&default_network_delegate_);
11307 default_context_.set_cert_verifier(&cert_verifier_);
11308 default_context_.Init();
11309 }
Chris Watkins7a41d3552017-12-01 02:13:2711310 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2411311
11312 protected:
11313 MockCertVerifier cert_verifier_;
11314 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
11315 TestURLRequestContext default_context_;
11316};
11317
11318// Tests that session resumption is not attempted if an invalid certificate
11319// is presented.
11320TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
11321 SpawnedTestServer::SSLOptions ssl_options;
11322 ssl_options.record_resume = true;
11323 SpawnedTestServer test_server(
11324 SpawnedTestServer::TYPE_HTTPS,
11325 ssl_options,
11326 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11327 ASSERT_TRUE(test_server.Start());
11328
Daniel McArdle3a663d62019-01-31 00:48:4711329 default_context_.http_transaction_factory()
11330 ->GetSession()
11331 ->ClearSSLSessionCache();
[email protected]a8fed1742013-12-27 02:14:2411332
11333 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5911334 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2411335 {
11336 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611337 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0411338 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1611339 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2411340
[email protected]f7022f32014-08-21 16:32:1911341 r->Start();
11342 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2411343
Wez2a31b222018-06-07 22:07:1511344 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2411345
11346 EXPECT_EQ(1, d.response_started_count());
11347 }
11348
11349 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
11350 CloseAllConnections();
11351
11352 // Now change the certificate to be acceptable (so that the response is
11353 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5911354 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2411355 {
11356 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611357 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611358 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
11359 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2411360
[email protected]f7022f32014-08-21 16:32:1911361 r->Start();
11362 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2411363
Wez2a31b222018-06-07 22:07:1511364 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2411365
[email protected]a8fed1742013-12-27 02:14:2411366 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0411367 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]a8fed1742013-12-27 02:14:2411368 }
11369}
11370
[email protected]dffe8242012-03-20 15:14:2711371// This the fingerprint of the "Testing CA" certificate used by the testserver.
11372// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5811373static const SHA256HashValue kOCSPTestCertFingerprint = {{
11374 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
11375 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
11376 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1511377}};
[email protected]dffe8242012-03-20 15:14:2711378
[email protected]51523f52013-07-31 21:57:2811379// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
11380// testserver.
mattm0b12a6f2016-11-29 19:57:1611381static const SHA256HashValue kOCSPTestCertSPKI = {{
11382 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
11383 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
11384 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
11385}};
[email protected]51523f52013-07-31 21:57:2811386
[email protected]dffe8242012-03-20 15:14:2711387// This is the policy OID contained in the certificates that testserver
11388// generates.
11389static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
11390
11391class HTTPSOCSPTest : public HTTPSRequestTest {
11392 public:
11393 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0911394 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0811395 ev_test_policy_(
11396 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
11397 kOCSPTestCertFingerprint,
11398 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0211399 }
11400
dcheng67be2b1f2014-10-27 21:47:2911401 void SetUp() override {
Matt Muellera4aaa9d2019-04-24 21:09:1411402 cert_net_fetcher_ = base::MakeRefCounted<CertNetFetcherImpl>();
11403 cert_verifier_ = CertVerifier::CreateDefault(cert_net_fetcher_);
11404 context_.set_cert_verifier(cert_verifier_.get());
Ryan Sleevi8a9c9c12018-05-09 02:36:2311405 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
[email protected]ef2bf422012-05-11 03:27:0911406 context_.Init();
[email protected]dffe8242012-03-20 15:14:2711407
Matt Muellera4aaa9d2019-04-24 21:09:1411408 cert_net_fetcher_->SetURLRequestContext(&context_);
Ryan Sleevi24fe2682018-08-16 21:33:4611409 context_.cert_verifier()->SetConfig(GetCertVerifierConfig());
11410
[email protected]cba24642014-08-15 20:49:5911411 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2011412 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
Matt Mueller09c8fd9a2019-05-04 00:37:2411413 ASSERT_TRUE(root_cert);
[email protected]90499482013-06-01 00:39:5011414 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2711415
svaldez2135be52016-04-20 16:34:5311416#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0911417 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2711418#endif
11419 }
11420
dadrian612337a2016-07-20 22:36:5811421 void DoConnectionWithDelegate(
11422 const SpawnedTestServer::SSLOptions& ssl_options,
11423 TestDelegate* delegate,
11424 SSLInfo* out_ssl_info) {
11425 // Always overwrite |out_ssl_info|.
11426 out_ssl_info->Reset();
11427
[email protected]ce7d0cbc2013-05-03 18:57:2211428 SpawnedTestServer test_server(
11429 SpawnedTestServer::TYPE_HTTPS,
11430 ssl_options,
11431 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2711432 ASSERT_TRUE(test_server.Start());
11433
dadrian612337a2016-07-20 22:36:5811434 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1611435 std::unique_ptr<URLRequest> r(
11436 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
11437 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911438 r->Start();
[email protected]dffe8242012-03-20 15:14:2711439
Wez2a31b222018-06-07 22:07:1511440 delegate->RunUntilComplete();
dadrian612337a2016-07-20 22:36:5811441 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2711442
dadrian612337a2016-07-20 22:36:5811443 *out_ssl_info = r->ssl_info();
11444 }
11445
11446 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
11447 CertStatus* out_cert_status) {
11448 // Always overwrite |out_cert_status|.
11449 *out_cert_status = 0;
11450
11451 TestDelegate d;
11452 SSLInfo ssl_info;
11453 ASSERT_NO_FATAL_FAILURE(
11454 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
11455
11456 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2711457 }
11458
dcheng67be2b1f2014-10-27 21:47:2911459 ~HTTPSOCSPTest() override {
Matt Muellera4aaa9d2019-04-24 21:09:1411460 cert_net_fetcher_->Shutdown();
svaldez2135be52016-04-20 16:34:5311461#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1811462 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2711463#endif
11464 }
11465
[email protected]a13234c2012-03-20 21:45:0211466 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611467 // GetCertVerifierConfig() configures the URLRequestContext that will be used
11468 // for making connections to the testserver. This can be overridden in test
11469 // subclasses for different behaviour.
11470 virtual CertVerifier::Config GetCertVerifierConfig() {
11471 CertVerifier::Config config;
11472 config.enable_rev_checking = true;
11473 return config;
[email protected]a13234c2012-03-20 21:45:0211474 }
11475
danakj8522a25b2016-04-16 00:17:3611476 std::unique_ptr<ScopedTestRoot> test_root_;
Ryan Sleevib8449e02018-07-15 04:31:0711477 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
Matt Muellera4aaa9d2019-04-24 21:09:1411478 scoped_refptr<CertNetFetcherImpl> cert_net_fetcher_;
11479 std::unique_ptr<CertVerifier> cert_verifier_;
[email protected]ef2bf422012-05-11 03:27:0911480 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3611481 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2711482};
11483
Matt Mueller36c3b102019-06-18 02:28:2011484static bool UsingBuiltinCertVerifier() {
11485#if defined(OS_FUCHSIA)
11486 return true;
11487#elif BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED)
11488 if (base::FeatureList::IsEnabled(features::kCertVerifierBuiltinFeature))
11489 return true;
11490#endif
11491 return false;
11492}
11493
[email protected]a13234c2012-03-20 21:45:0211494static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
Matt Mueller36c3b102019-06-18 02:28:2011495 if (UsingBuiltinCertVerifier())
11496 return 0;
mattmaf868e72016-09-23 23:25:2011497#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0211498 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
11499 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0411500 // TODO(eroman): Should this also be the return value for
11501 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0211502 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
11503#else
11504 return 0;
11505#endif
11506}
11507
[email protected]3a86a712013-07-30 07:16:2011508// SystemSupportsHardFailRevocationChecking returns true iff the current
11509// operating system supports revocation checking and can distinguish between
11510// situations where a given certificate lacks any revocation information (eg:
11511// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
11512// revocation information cannot be obtained (eg: the CRL was unreachable).
11513// If it does not, then tests which rely on 'hard fail' behaviour should be
11514// skipped.
11515static bool SystemSupportsHardFailRevocationChecking() {
Matt Mueller36c3b102019-06-18 02:28:2011516 if (UsingBuiltinCertVerifier())
11517 return true;
11518#if defined(OS_WIN) || defined(USE_NSS_CERTS)
[email protected]3a86a712013-07-30 07:16:2011519 return true;
11520#else
11521 return false;
11522#endif
11523}
11524
[email protected]a13234c2012-03-20 21:45:0211525// SystemUsesChromiumEVMetadata returns true iff the current operating system
11526// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
11527// several tests are effected because our testing EV certificate won't be
11528// recognised as EV.
11529static bool SystemUsesChromiumEVMetadata() {
Matt Mueller36c3b102019-06-18 02:28:2011530 if (UsingBuiltinCertVerifier())
11531 return true;
Eric Roman5f8d9d22017-10-17 02:32:5211532#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0111533 return true;
Eric Roman5f8d9d22017-10-17 02:32:5211534#else
11535 return false;
[email protected]05454a432012-03-20 20:04:0111536#endif
11537}
11538
mattmaf868e72016-09-23 23:25:2011539// Returns the expected CertStatus for tests that expect an online revocation
11540// check failure as a result of checking a test EV cert, which will not
11541// actually trigger an online revocation check on some platforms.
11542static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
11543 if (SystemUsesChromiumEVMetadata()) {
11544 return ExpectedCertStatusForFailedOnlineRevocationCheck();
11545 } else {
11546 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
11547 // be enabled, and thus there will not be a revocation check to fail.
11548 return 0u;
11549 }
11550}
11551
[email protected]b6f2de32012-08-17 04:35:0811552static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3911553#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0211554 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
11555 return false;
11556#else
11557 return true;
11558#endif
11559}
11560
davidbend1fb2f12014-11-08 02:51:0011561static bool SystemSupportsOCSPStapling() {
Matt Mueller36c3b102019-06-18 02:28:2011562 if (UsingBuiltinCertVerifier())
11563 return true;
Matt Mueller7f60dc42019-04-26 22:47:1011564#if defined(OS_ANDROID)
mathpc992e602015-10-21 20:34:0311565 return false;
Matt Mueller7f60dc42019-04-26 22:47:1011566#elif defined(OS_MACOSX)
11567 // The SecTrustSetOCSPResponse function exists since macOS 10.9+, but does
11568 // not actually do anything until 10.12.
11569 if (base::mac::IsAtLeastOS10_12())
11570 return true;
11571 return false;
11572#else
11573 return true;
mathpc992e602015-10-21 20:34:0311574#endif
davidbend1fb2f12014-11-08 02:51:0011575}
11576
[email protected]dffe8242012-03-20 15:14:2711577TEST_F(HTTPSOCSPTest, Valid) {
11578 if (!SystemSupportsOCSP()) {
11579 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11580 return;
11581 }
11582
[email protected]ce7d0cbc2013-05-03 18:57:2211583 SpawnedTestServer::SSLOptions ssl_options(
11584 SpawnedTestServer::SSLOptions::CERT_AUTO);
11585 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2711586
[email protected]924e9f92012-12-16 22:00:5311587 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211588 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711589
11590 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11591
[email protected]a13234c2012-03-20 21:45:0211592 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11593 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2711594
11595 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11596}
11597
11598TEST_F(HTTPSOCSPTest, Revoked) {
11599 if (!SystemSupportsOCSP()) {
11600 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11601 return;
11602 }
11603
[email protected]ce7d0cbc2013-05-03 18:57:2211604 SpawnedTestServer::SSLOptions ssl_options(
11605 SpawnedTestServer::SSLOptions::CERT_AUTO);
11606 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2711607
11608 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211609 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711610
[email protected]dffe8242012-03-20 15:14:2711611 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2711612 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11613 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11614}
11615
11616TEST_F(HTTPSOCSPTest, Invalid) {
11617 if (!SystemSupportsOCSP()) {
11618 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11619 return;
11620 }
11621
[email protected]ce7d0cbc2013-05-03 18:57:2211622 SpawnedTestServer::SSLOptions ssl_options(
11623 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811624 ssl_options.ocsp_status =
11625 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2711626
[email protected]924e9f92012-12-16 22:00:5311627 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211628 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711629
Matt Mueller36c3b102019-06-18 02:28:2011630 if (UsingBuiltinCertVerifier()) {
11631 // TODO(649017): This test uses soft-fail revocation checking, but returns
11632 // an invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
11633 // doesn't consider this a candidate for soft-fail (only considers
11634 // network-level failures as skippable).
11635 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11636 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11637 } else {
11638 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
11639 cert_status & CERT_STATUS_ALL_ERRORS);
11640 }
[email protected]dffe8242012-03-20 15:14:2711641
11642 // Without a positive OCSP response, we shouldn't show the EV status.
11643 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11644 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11645}
[email protected]a13234c2012-03-20 21:45:0211646
Matt Mueller5339d862018-05-02 18:53:5711647TEST_F(HTTPSOCSPTest, IntermediateValid) {
11648 if (!SystemSupportsOCSP()) {
11649 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11650 return;
11651 }
11652
11653 SpawnedTestServer::SSLOptions ssl_options(
11654 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11655 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11656 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11657
11658 CertStatus cert_status;
11659 DoConnection(ssl_options, &cert_status);
11660
11661 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11662
11663 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11664 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11665
11666 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11667}
11668
11669TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
11670 if (!SystemSupportsOCSP()) {
11671 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11672 return;
11673 }
11674
11675 SpawnedTestServer::SSLOptions ssl_options(
11676 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11677 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11678 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11679 // Use an OCSP response for the intermediate that would be too old for a leaf
11680 // cert, but is still valid for an intermediate.
11681 ssl_options.ocsp_intermediate_date =
11682 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
11683
11684 CertStatus cert_status;
11685 DoConnection(ssl_options, &cert_status);
11686
11687 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11688
11689 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11690 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11691
11692 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11693}
11694
11695TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
11696 if (!SystemSupportsOCSP()) {
11697 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11698 return;
11699 }
11700
11701 SpawnedTestServer::SSLOptions ssl_options(
11702 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11703 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11704 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11705 ssl_options.ocsp_intermediate_date =
11706 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
11707
11708 CertStatus cert_status;
11709 DoConnection(ssl_options, &cert_status);
11710
Matt Mueller36c3b102019-06-18 02:28:2011711 if (UsingBuiltinCertVerifier()) {
11712 // The builtin verifier enforces the baseline requirements for max age of an
11713 // intermediate's OCSP response.
11714 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11715 cert_status & CERT_STATUS_ALL_ERRORS);
11716 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11717 } else {
11718 // The platform verifiers are more lenient.
11719 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11720 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11721 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11722 }
Matt Mueller5339d862018-05-02 18:53:5711723 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11724}
11725
11726TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
11727 if (!SystemSupportsOCSP()) {
11728 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11729 return;
11730 }
11731
11732 SpawnedTestServer::SSLOptions ssl_options(
11733 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11734 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11735 ssl_options.ocsp_intermediate_status =
11736 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11737
11738 CertStatus cert_status;
11739 DoConnection(ssl_options, &cert_status);
11740
11741#if defined(OS_WIN)
11742 // TODO(mattm): why does CertVerifyProcWin accept this?
11743 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11744#else
11745 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11746#endif
11747 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11748 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11749}
11750
davidbend1fb2f12014-11-08 02:51:0011751TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0311752 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011753 LOG(WARNING)
11754 << "Skipping test because system doesn't support OCSP stapling";
11755 return;
11756 }
11757
11758 SpawnedTestServer::SSLOptions ssl_options(
11759 SpawnedTestServer::SSLOptions::CERT_AUTO);
11760 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11761 ssl_options.staple_ocsp_response = true;
11762 ssl_options.ocsp_server_unavailable = true;
11763
11764 CertStatus cert_status;
11765 DoConnection(ssl_options, &cert_status);
11766
11767 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11768
11769 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11770 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11771
11772 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11773}
11774
davidben6c3191b2014-11-21 22:38:0411775// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4811776#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0411777#define MAYBE_RevokedStapled DISABLED_RevokedStapled
11778#else
11779#define MAYBE_RevokedStapled RevokedStapled
11780#endif
11781TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0311782 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011783 LOG(WARNING)
11784 << "Skipping test because system doesn't support OCSP stapling";
11785 return;
11786 }
11787
11788 SpawnedTestServer::SSLOptions ssl_options(
11789 SpawnedTestServer::SSLOptions::CERT_AUTO);
11790 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11791 ssl_options.staple_ocsp_response = true;
11792 ssl_options.ocsp_server_unavailable = true;
11793
11794 CertStatus cert_status;
11795 DoConnection(ssl_options, &cert_status);
11796
11797 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11798 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11799 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11800}
11801
dadrian612337a2016-07-20 22:36:5811802static const struct OCSPVerifyTestData {
11803 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
11804 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
11805 OCSPVerifyResult::ResponseStatus response_status;
11806 bool has_revocation_status;
11807 OCSPRevocationStatus cert_status;
11808} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3111809 // 0
dadrian612337a2016-07-20 22:36:5811810 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11811 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11812 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11813 OCSPVerifyResult::PROVIDED,
11814 true,
11815 OCSPRevocationStatus::GOOD},
11816
Eric Roman8673b812017-09-20 18:57:3111817 // 1
dadrian612337a2016-07-20 22:36:5811818 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11819 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11820 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11821 OCSPVerifyResult::INVALID_DATE,
11822 false,
11823 OCSPRevocationStatus::UNKNOWN},
11824
Eric Roman8673b812017-09-20 18:57:3111825 // 2
dadrian612337a2016-07-20 22:36:5811826 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11827 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11828 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11829 OCSPVerifyResult::INVALID_DATE,
11830 false,
11831 OCSPRevocationStatus::UNKNOWN},
11832
Eric Roman8673b812017-09-20 18:57:3111833 // 3
dadrian612337a2016-07-20 22:36:5811834 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11835 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11836 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11837 OCSPVerifyResult::INVALID_DATE,
11838 false,
11839 OCSPRevocationStatus::UNKNOWN},
11840
Eric Roman8673b812017-09-20 18:57:3111841 // 4
dadrian612337a2016-07-20 22:36:5811842 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11843 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11844 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11845 OCSPVerifyResult::INVALID_DATE,
11846 false,
11847 OCSPRevocationStatus::UNKNOWN},
11848
Eric Roman8673b812017-09-20 18:57:3111849 // 5
dadrian612337a2016-07-20 22:36:5811850 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
11851 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11852 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11853 OCSPVerifyResult::ERROR_RESPONSE,
11854 false,
11855 OCSPRevocationStatus::UNKNOWN},
11856
Eric Roman8673b812017-09-20 18:57:3111857 // 6
dadrian612337a2016-07-20 22:36:5811858 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
11859 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11860 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11861 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
11862 false,
11863 OCSPRevocationStatus::UNKNOWN},
11864
Eric Roman8673b812017-09-20 18:57:3111865 // 7
dadrian612337a2016-07-20 22:36:5811866 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
11867 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11868 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11869 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
11870 false,
11871 OCSPRevocationStatus::UNKNOWN},
11872
Eric Roman8673b812017-09-20 18:57:3111873 // 8
dadrian612337a2016-07-20 22:36:5811874 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11875 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11876 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11877 OCSPVerifyResult::INVALID_DATE,
11878 false,
11879 OCSPRevocationStatus::UNKNOWN},
11880
Eric Roman8673b812017-09-20 18:57:3111881 // 9
dadrian612337a2016-07-20 22:36:5811882 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11883 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11884 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11885 OCSPVerifyResult::PROVIDED,
11886 true,
11887 OCSPRevocationStatus::UNKNOWN},
11888
Eric Roman8673b812017-09-20 18:57:3111889 // 10
dadrian612337a2016-07-20 22:36:5811890 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11891 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11892 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11893 OCSPVerifyResult::INVALID_DATE,
11894 false,
11895 OCSPRevocationStatus::UNKNOWN},
11896
Eric Roman8673b812017-09-20 18:57:3111897 // 11
dadrian612337a2016-07-20 22:36:5811898 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11899 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11900 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11901 OCSPVerifyResult::INVALID_DATE,
11902 false,
11903 OCSPRevocationStatus::UNKNOWN},
11904
Eric Roman8673b812017-09-20 18:57:3111905 // 12
dadrian612337a2016-07-20 22:36:5811906 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11907 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11908 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
11909 OCSPVerifyResult::BAD_PRODUCED_AT,
11910 false,
11911 OCSPRevocationStatus::UNKNOWN},
11912
Eric Roman8673b812017-09-20 18:57:3111913 // 13
dadrian612337a2016-07-20 22:36:5811914 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11915 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11916 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11917 OCSPVerifyResult::BAD_PRODUCED_AT,
11918 false,
11919 OCSPRevocationStatus::UNKNOWN},
11920
Eric Roman8673b812017-09-20 18:57:3111921 // 14
dadrian612337a2016-07-20 22:36:5811922 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11923 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11924 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11925 OCSPVerifyResult::BAD_PRODUCED_AT,
11926 false,
11927 OCSPRevocationStatus::UNKNOWN},
11928
Eric Roman8673b812017-09-20 18:57:3111929 // 15
dadrian612337a2016-07-20 22:36:5811930 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11931 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11932 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11933 OCSPVerifyResult::PROVIDED,
11934 true,
11935 OCSPRevocationStatus::GOOD},
11936
Eric Roman8673b812017-09-20 18:57:3111937 // 16
dadrian612337a2016-07-20 22:36:5811938 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11939 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11940 {SpawnedTestServer::SSLOptions::OCSP_OK,
11941 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11942 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11943 OCSPVerifyResult::PROVIDED,
11944 true,
11945 OCSPRevocationStatus::GOOD},
11946
Eric Roman8673b812017-09-20 18:57:3111947 // 17
dadrian612337a2016-07-20 22:36:5811948 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11949 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11950 {SpawnedTestServer::SSLOptions::OCSP_OK,
11951 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11952 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11953 OCSPVerifyResult::PROVIDED,
11954 true,
11955 OCSPRevocationStatus::GOOD},
11956
Eric Roman8673b812017-09-20 18:57:3111957 // 18
dadrian612337a2016-07-20 22:36:5811958 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11959 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11960 {SpawnedTestServer::SSLOptions::OCSP_OK,
11961 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11962 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11963 OCSPVerifyResult::PROVIDED,
11964 true,
11965 OCSPRevocationStatus::GOOD},
11966
Eric Roman8673b812017-09-20 18:57:3111967 // 19
dadrian612337a2016-07-20 22:36:5811968 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11969 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11970 {SpawnedTestServer::SSLOptions::OCSP_OK,
11971 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11972 {SpawnedTestServer::SSLOptions::OCSP_OK,
11973 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11974 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11975 OCSPVerifyResult::INVALID_DATE,
11976 false,
11977 OCSPRevocationStatus::UNKNOWN},
11978
Eric Roman8673b812017-09-20 18:57:3111979 // 20
dadrian612337a2016-07-20 22:36:5811980 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11981 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11982 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11983 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11984 {SpawnedTestServer::SSLOptions::OCSP_OK,
11985 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11986 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11987 OCSPVerifyResult::PROVIDED,
11988 true,
11989 OCSPRevocationStatus::REVOKED},
11990
Eric Roman8673b812017-09-20 18:57:3111991 // 21
dadrian612337a2016-07-20 22:36:5811992 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11993 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11994 {SpawnedTestServer::SSLOptions::OCSP_OK,
11995 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11996 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11997 OCSPVerifyResult::PROVIDED,
11998 true,
11999 OCSPRevocationStatus::UNKNOWN},
12000
Eric Roman8673b812017-09-20 18:57:3112001 // 22
dadrian612337a2016-07-20 22:36:5812002 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
12003 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
12004 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
12005 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
12006 {SpawnedTestServer::SSLOptions::OCSP_OK,
12007 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
12008 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12009 OCSPVerifyResult::PROVIDED,
12010 true,
12011 OCSPRevocationStatus::UNKNOWN},
12012
Eric Roman8673b812017-09-20 18:57:3112013 // 23
dadrian612337a2016-07-20 22:36:5812014 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
12015 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
12016 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12017 OCSPVerifyResult::NO_MATCHING_RESPONSE,
12018 false,
12019 OCSPRevocationStatus::UNKNOWN},
12020
Eric Roman8673b812017-09-20 18:57:3112021 // 24
dadrian612337a2016-07-20 22:36:5812022 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
12023 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
12024 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12025 OCSPVerifyResult::NO_MATCHING_RESPONSE,
12026 false,
12027 OCSPRevocationStatus::UNKNOWN},
12028
Eric Roman8673b812017-09-20 18:57:3112029// These tests fail when using NSS for certificate verification, as NSS fails
12030// and doesn't return the partial path. As a result the OCSP checks being done
12031// at the CertVerifyProc layer cannot access the issuer certificate.
12032#if !defined(USE_NSS_CERTS)
12033 // 25
12034 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
12035 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
12036 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12037 OCSPVerifyResult::PROVIDED,
12038 true,
12039 OCSPRevocationStatus::REVOKED},
12040
12041 // 26
12042 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
12043 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
12044 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12045 OCSPVerifyResult::INVALID_DATE,
12046 false,
12047 OCSPRevocationStatus::UNKNOWN},
12048
12049 // 27
12050 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
12051 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
12052 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12053 OCSPVerifyResult::INVALID_DATE,
12054 false,
12055 OCSPRevocationStatus::UNKNOWN},
12056#endif
dadrian612337a2016-07-20 22:36:5812057};
12058
12059class HTTPSOCSPVerifyTest
12060 : public HTTPSOCSPTest,
12061 public testing::WithParamInterface<OCSPVerifyTestData> {};
12062
Christos Froussios09e6ac42019-04-05 14:08:2012063// TODO(crbug.com/949958): The test is flaky on Mac
12064#if defined(OS_MACOSX)
12065#define MAYBE_VerifyResult DISABLED_VerifyResult
12066#else
12067#define MAYBE_VerifyResult VerifyResult
12068#endif
12069TEST_P(HTTPSOCSPVerifyTest, MAYBE_VerifyResult) {
dadrian612337a2016-07-20 22:36:5812070 SpawnedTestServer::SSLOptions ssl_options(
12071 SpawnedTestServer::SSLOptions::CERT_AUTO);
12072 OCSPVerifyTestData test = GetParam();
12073
12074 ssl_options.ocsp_responses = test.ocsp_responses;
12075 ssl_options.ocsp_produced = test.ocsp_produced;
12076 ssl_options.staple_ocsp_response = true;
12077
12078 SSLInfo ssl_info;
12079 OCSPErrorTestDelegate delegate;
12080 ASSERT_NO_FATAL_FAILURE(
12081 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
12082
12083 // The SSLInfo must be extracted from |delegate| on error, due to how
12084 // URLRequest caches certificate errors.
12085 if (delegate.have_certificate_errors()) {
12086 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
12087 ssl_info = delegate.ssl_info();
12088 }
12089
12090 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
12091
12092 if (test.has_revocation_status)
12093 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
12094}
12095
Victor Costan8fb98f6f2019-02-01 17:08:2912096INSTANTIATE_TEST_SUITE_P(OCSPVerify,
12097 HTTPSOCSPVerifyTest,
12098 testing::ValuesIn(kOCSPVerifyData));
dadrian612337a2016-07-20 22:36:5812099
mattm0b12a6f2016-11-29 19:57:1612100class HTTPSAIATest : public HTTPSOCSPTest {
12101 public:
Ryan Sleevi24fe2682018-08-16 21:33:4612102 CertVerifier::Config GetCertVerifierConfig() override {
12103 CertVerifier::Config config;
12104 return config;
mattm0b12a6f2016-11-29 19:57:1612105 }
12106};
12107
12108TEST_F(HTTPSAIATest, AIAFetching) {
12109 SpawnedTestServer::SSLOptions ssl_options(
12110 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
12111 SpawnedTestServer test_server(
12112 SpawnedTestServer::TYPE_HTTPS, ssl_options,
12113 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
12114 ASSERT_TRUE(test_server.Start());
12115
Ryan Sleevi5b4702a2018-04-06 22:23:5612116 // Unmark the certificate's OID as EV, which will disable revocation
12117 // checking.
12118 ev_test_policy_.reset();
12119
mattm0b12a6f2016-11-29 19:57:1612120 TestDelegate d;
12121 d.set_allow_certificate_errors(true);
12122 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612123 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
12124 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1612125
12126 r->Start();
12127 EXPECT_TRUE(r->is_pending());
12128
Wez2a31b222018-06-07 22:07:1512129 d.RunUntilComplete();
mattm0b12a6f2016-11-29 19:57:1612130
12131 EXPECT_EQ(1, d.response_started_count());
12132
12133 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4812134 EXPECT_EQ(OK, d.request_status());
12135 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12136 ASSERT_TRUE(r->ssl_info().cert);
12137 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1612138 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3412139 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1612140}
12141
[email protected]3a86a712013-07-30 07:16:2012142class HTTPSHardFailTest : public HTTPSOCSPTest {
12143 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4612144 CertVerifier::Config GetCertVerifierConfig() override {
12145 CertVerifier::Config config;
12146 config.require_rev_checking_local_anchors = true;
12147 return config;
[email protected]3a86a712013-07-30 07:16:2012148 }
12149};
12150
[email protected]3a86a712013-07-30 07:16:2012151TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
12152 if (!SystemSupportsOCSP()) {
12153 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12154 return;
12155 }
12156
12157 if (!SystemSupportsHardFailRevocationChecking()) {
12158 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
12159 << "revocation checking";
12160 return;
12161 }
12162
12163 SpawnedTestServer::SSLOptions ssl_options(
12164 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812165 ssl_options.ocsp_status =
12166 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2012167
12168 CertStatus cert_status;
12169 DoConnection(ssl_options, &cert_status);
12170
Matt Mueller36c3b102019-06-18 02:28:2012171 if (UsingBuiltinCertVerifier()) {
12172 // TODO(crbug.com/649017): Should we consider invalid response as
12173 // affirmatively revoked?
12174 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
12175 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
12176 } else {
12177 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
12178 }
[email protected]3a86a712013-07-30 07:16:2012179
12180 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0412181 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2012182 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12183}
12184
[email protected]a13234c2012-03-20 21:45:0212185class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
12186 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4612187 CertVerifier::Config GetCertVerifierConfig() override {
12188 CertVerifier::Config config;
12189 return config;
[email protected]a13234c2012-03-20 21:45:0212190 }
12191};
12192
12193TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
12194 if (!SystemSupportsOCSP()) {
12195 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12196 return;
12197 }
12198
[email protected]ce7d0cbc2013-05-03 18:57:2212199 SpawnedTestServer::SSLOptions ssl_options(
12200 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812201 ssl_options.ocsp_status =
12202 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0212203
[email protected]924e9f92012-12-16 22:00:5312204 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212205 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212206
mattmaf868e72016-09-23 23:25:2012207 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0212208 cert_status & CERT_STATUS_ALL_ERRORS);
12209
12210 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0812211 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12212 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212213}
12214
[email protected]be0fff62013-08-29 23:37:4812215TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
12216 if (!SystemSupportsOCSP()) {
12217 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12218 return;
12219 }
12220
12221 SpawnedTestServer::SSLOptions ssl_options(
12222 SpawnedTestServer::SSLOptions::CERT_AUTO);
12223 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]be0fff62013-08-29 23:37:4812224
12225 CertStatus cert_status;
12226 DoConnection(ssl_options, &cert_status);
12227
Matt Mueller36c3b102019-06-18 02:28:2012228 // Currently only works for Windows and OS X. When using NSS, it's not
12229 // possible to determine whether the check failed because of actual
12230 // revocation or because there was an OCSP failure.
12231 if (UsingBuiltinCertVerifier()) {
12232 // TODO(https://crbug.com/410574): Handle this in builtin verifier too?
12233 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12234 } else {
mattm1a282f52016-11-10 21:49:4212235#if defined(OS_WIN) || defined(OS_MACOSX)
Matt Mueller36c3b102019-06-18 02:28:2012236 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]be0fff62013-08-29 23:37:4812237#else
Matt Mueller36c3b102019-06-18 02:28:2012238 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]be0fff62013-08-29 23:37:4812239#endif
Matt Mueller36c3b102019-06-18 02:28:2012240 }
[email protected]be0fff62013-08-29 23:37:4812241
12242 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12243 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12244 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
12245}
12246
[email protected]a13234c2012-03-20 21:45:0212247TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
12248 if (!SystemSupportsOCSP()) {
12249 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12250 return;
12251 }
12252
[email protected]ce7d0cbc2013-05-03 18:57:2212253 SpawnedTestServer::SSLOptions ssl_options(
12254 SpawnedTestServer::SSLOptions::CERT_AUTO);
12255 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0212256
12257 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212258 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212259
12260 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12261
12262 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12263 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0812264 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12265 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212266}
12267
12268TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
12269 if (!SystemSupportsOCSP()) {
12270 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12271 return;
12272 }
12273
[email protected]ce7d0cbc2013-05-03 18:57:2212274 SpawnedTestServer::SSLOptions ssl_options(
12275 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812276 ssl_options.ocsp_status =
12277 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212278 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12279 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
12280 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0212281
12282 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212283 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212284
mattmaf868e72016-09-23 23:25:2012285 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0212286 cert_status & CERT_STATUS_ALL_ERRORS);
12287
12288 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0812289 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12290 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212291}
12292
[email protected]51523f52013-07-31 21:57:2812293TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
12294 if (!SystemSupportsOCSP()) {
12295 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12296 return;
12297 }
12298
12299 SpawnedTestServer::SSLOptions ssl_options(
12300 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812301 ssl_options.ocsp_status =
12302 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212303 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12304 cert_verifier_config.crl_set =
12305 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {});
12306 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2812307
12308 CertStatus cert_status;
12309 DoConnection(ssl_options, &cert_status);
12310
12311 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
12312 // revocation check for EV.
12313 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12314 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12315 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
12316 EXPECT_FALSE(
12317 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
12318}
12319
12320TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
12321 if (!SystemSupportsOCSP()) {
12322 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12323 return;
12324 }
12325
[email protected]ce7d0cbc2013-05-03 18:57:2212326 SpawnedTestServer::SSLOptions ssl_options(
12327 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812328 ssl_options.ocsp_status =
12329 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212330 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12331 cert_verifier_config.crl_set = CRLSet::EmptyCRLSetForTesting();
12332 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0212333
[email protected]51523f52013-07-31 21:57:2812334 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1212335 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212336
[email protected]51523f52013-07-31 21:57:2812337 // Even with a fresh CRLSet, we should still do online revocation checks when
12338 // the certificate chain isn't covered by the CRLSet, which it isn't in this
12339 // test.
mattmaf868e72016-09-23 23:25:2012340 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2812341 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0212342
[email protected]51523f52013-07-31 21:57:2812343 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0212344 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2812345 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212346}
12347
12348class HTTPSCRLSetTest : public HTTPSOCSPTest {
12349 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4612350 CertVerifier::Config GetCertVerifierConfig() override {
12351 CertVerifier::Config config;
12352 return config;
Ryan Sleevi5b4702a2018-04-06 22:23:5612353 }
12354
12355 void SetUp() override {
12356 HTTPSOCSPTest::SetUp();
12357
12358 // Unmark the certificate's OID as EV, which should disable revocation
12359 // checking (as per the user preference).
12360 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0212361 }
12362};
12363
12364TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2212365 SpawnedTestServer::SSLOptions ssl_options(
12366 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812367 ssl_options.ocsp_status =
12368 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212369 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12370 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
12371 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0212372
[email protected]924e9f92012-12-16 22:00:5312373 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212374 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212375
12376 // If we're not trying EV verification then, even if the CRLSet has expired,
12377 // we don't fall back to online revocation checks.
12378 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12379 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12380 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12381}
[email protected]51523f52013-07-31 21:57:2812382
Ryan Sleevi5b4702a2018-04-06 22:23:5612383TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
12384 // Test that when online revocation checking is disabled, and the leaf
12385 // certificate is not EV, that no revocation checking actually happens.
12386 if (!SystemSupportsOCSP()) {
12387 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12388 return;
12389 }
12390
12391 SpawnedTestServer::SSLOptions ssl_options(
12392 SpawnedTestServer::SSLOptions::CERT_AUTO);
12393 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Ryan Sleevib369d712018-08-20 16:43:2212394
12395 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12396 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
12397 context_.cert_verifier()->SetConfig(cert_verifier_config);
Ryan Sleevi5b4702a2018-04-06 22:23:5612398
12399 CertStatus cert_status;
12400 DoConnection(ssl_options, &cert_status);
12401
12402 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12403
12404 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12405 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12406}
12407
[email protected]51523f52013-07-31 21:57:2812408TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2512409#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2812410 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12411 return;
12412#endif
12413
12414 SpawnedTestServer::SSLOptions ssl_options(
12415 SpawnedTestServer::SSLOptions::CERT_AUTO);
12416 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12417 ssl_options.cert_serial = 10;
Ryan Sleevib369d712018-08-20 16:43:2212418
12419 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12420 cert_verifier_config.crl_set =
12421 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {});
12422 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2812423
12424 CertStatus cert_status = 0;
12425 DoConnection(ssl_options, &cert_status);
12426
12427 // If the certificate is recorded as revoked in the CRLSet, that should be
12428 // reflected without online revocation checking.
12429 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12430 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612431 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2812432}
Adam Langleyea6d6782017-12-05 23:57:3312433
12434TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
12435#if defined(OS_ANDROID)
12436 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12437 return;
12438#endif
12439
12440 SpawnedTestServer::SSLOptions ssl_options(
12441 SpawnedTestServer::SSLOptions::CERT_AUTO);
12442 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12443 static const char kCommonName[] = "Test CN";
12444 ssl_options.cert_common_name = kCommonName;
12445
12446 {
Ryan Sleevib369d712018-08-20 16:43:2212447 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12448 cert_verifier_config.crl_set =
12449 CRLSet::ForTesting(false, nullptr, "", kCommonName, {});
12450 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3312451
12452 CertStatus cert_status = 0;
12453 DoConnection(ssl_options, &cert_status);
12454
12455 // If the certificate is recorded as revoked in the CRLSet, that should be
12456 // reflected without online revocation checking.
12457 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12458 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612459 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3312460 }
12461
12462 const uint8_t kTestServerSPKISHA256[32] = {
12463 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
12464 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
12465 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
12466 };
12467 const std::string spki_hash(
12468 reinterpret_cast<const char*>(kTestServerSPKISHA256),
12469 sizeof(kTestServerSPKISHA256));
12470
12471 {
Ryan Sleevib369d712018-08-20 16:43:2212472 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12473 cert_verifier_config.crl_set =
12474 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash});
12475 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3312476
12477 CertStatus cert_status = 0;
12478 DoConnection(ssl_options, &cert_status);
12479
12480 // When the correct SPKI hash is specified, the connection should succeed
12481 // even though the subject is listed in the CRLSet.
12482 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12483 }
12484}
[email protected]316c1e5e2012-09-12 15:17:4412485#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2712486
Sergey Ulanovc4580e72017-09-13 23:30:1112487#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
12488 !defined(OS_FUCHSIA)
12489// FTP uses a second TCP connection with the port number allocated dynamically
12490// on the server side, so it would be hard to make RemoteTestServer proxy FTP
12491// connections reliably. FTP tests are disabled on platforms that use
12492// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3112493class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1112494 public:
[email protected]d9fca99a2012-02-24 16:16:2012495 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0512496 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5512497 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4712498 // Can't use |default_context_|'s HostResolver to set up the
12499 // FTPTransactionFactory because it hasn't been created yet.
Ryan Sleevib8449e02018-07-15 04:31:0712500 default_context().set_host_resolver(&host_resolver_);
mmenke9f2ec60c2015-06-01 20:59:4712501 }
12502
12503 // URLRequestTest interface:
12504 void SetUpFactory() override {
12505 // Add FTP support to the default URLRequestContext.
12506 job_factory_impl_->SetProtocolHandler(
Emily Stark01227982019-06-06 18:45:5612507 "ftp", FtpProtocolHandler::Create(&host_resolver_, &ftp_auth_cache_));
mmenke9f2ec60c2015-06-01 20:59:4712508 }
12509
12510 std::string GetTestFileContents() {
12511 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1912512 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4712513 path = path.Append(kTestFilePath);
12514 path = path.AppendASCII(kFtpTestFile);
12515 std::string contents;
12516 EXPECT_TRUE(base::ReadFileToString(path, &contents));
12517 return contents;
[email protected]95409e12010-08-17 20:07:1112518 }
12519
[email protected]b89ca032009-08-31 21:41:3112520 protected:
mmenke9f2ec60c2015-06-01 20:59:4712521 MockHostResolver host_resolver_;
Emily Stark01227982019-06-06 18:45:5612522 FtpAuthCache ftp_auth_cache_;
mmenke9f2ec60c2015-06-01 20:59:4712523
tommycli59a63432015-11-06 00:10:5512524 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3112525};
12526
[email protected]d2a133182012-08-05 16:44:0812527// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0912528TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0812529 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0812530
12531 TestDelegate d;
12532 {
Ryan Sleevib8449e02018-07-15 04:31:0712533 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612534 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912535 r->Start();
12536 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0812537
Wez2a31b222018-06-07 22:07:1512538 d.RunUntilComplete();
[email protected]d2a133182012-08-05 16:44:0812539
[email protected]f7022f32014-08-21 16:32:1912540 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5012541 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0812542 }
12543}
12544
mmenke9f2ec60c2015-06-01 20:59:4712545TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5512546 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112547
[email protected]a25e90e2009-09-09 17:05:3712548 TestDelegate d;
12549 {
Ryan Sleevib8449e02018-07-15 04:31:0712550 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612551 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
12552 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912553 r->Start();
12554 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712555
Wez2a31b222018-06-07 22:07:1512556 d.RunUntilComplete();
[email protected]a25e90e2009-09-09 17:05:3712557
[email protected]f7022f32014-08-21 16:32:1912558 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712559 EXPECT_EQ(1, d.response_started_count());
12560 EXPECT_FALSE(d.received_data_before_response());
12561 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5512562 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712563 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512564 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712565 r->GetResponseRemoteEndpoint().port());
[email protected]a25e90e2009-09-09 17:05:3712566 }
12567}
12568
mmenke9f2ec60c2015-06-01 20:59:4712569TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5512570 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112571
[email protected]dd265012009-01-08 20:45:2712572 TestDelegate d;
12573 {
Ryan Sleevib8449e02018-07-15 04:31:0712574 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612575 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
12576 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912577 r->Start();
12578 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712579
Wez2a31b222018-06-07 22:07:1512580 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712581
[email protected]f7022f32014-08-21 16:32:1912582 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712583 EXPECT_EQ(1, d.response_started_count());
12584 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712585 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512586 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712587 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512588 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712589 r->GetResponseRemoteEndpoint().port());
[email protected]dd265012009-01-08 20:45:2712590 }
12591}
12592
Mike West80462a12018-11-27 16:05:0612593TEST_F(URLRequestTestFTP, FTPMimeType) {
12594 ASSERT_TRUE(ftp_test_server_.Start());
12595
12596 struct {
12597 const char* path;
12598 const char* mime;
12599 } test_cases[] = {
12600 {"/", "text/vnd.chromium.ftp-dir"},
12601 {kFtpTestFile, "application/octet-stream"},
12602 };
12603
12604 for (const auto test : test_cases) {
12605 TestDelegate d;
12606
12607 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
12608 ftp_test_server_.GetURL(test.path), DEFAULT_PRIORITY, &d,
12609 TRAFFIC_ANNOTATION_FOR_TESTS));
12610 r->Start();
12611 EXPECT_TRUE(r->is_pending());
12612
12613 d.RunUntilComplete();
12614
12615 std::string mime;
12616 r->GetMimeType(&mime);
12617 EXPECT_EQ(test.mime, mime);
12618 }
12619}
12620
mmenke9f2ec60c2015-06-01 20:59:4712621TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5512622 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112623
[email protected]dd265012009-01-08 20:45:2712624 TestDelegate d;
12625 {
Ryan Sleevib8449e02018-07-15 04:31:0712626 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512627 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12628 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612629 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912630 r->Start();
12631 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712632
Wez2a31b222018-06-07 22:07:1512633 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712634
[email protected]f7022f32014-08-21 16:32:1912635 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4712636 EXPECT_EQ(1, d.response_started_count());
12637 EXPECT_FALSE(d.received_data_before_response());
12638 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512639 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712640 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512641 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712642 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:2512643
12644 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1912645 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2512646 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2712647 }
12648}
12649
mmenke9f2ec60c2015-06-01 20:59:4712650TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5512651 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112652
[email protected]dd265012009-01-08 20:45:2712653 TestDelegate d;
12654 {
Ryan Sleevib8449e02018-07-15 04:31:0712655 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512656 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12657 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612658 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912659 r->Start();
12660 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712661
Wez2a31b222018-06-07 22:07:1512662 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712663
[email protected]f7022f32014-08-21 16:32:1912664 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712665 EXPECT_EQ(1, d.response_started_count());
12666 EXPECT_FALSE(d.received_data_before_response());
12667 EXPECT_EQ(d.bytes_received(), 0);
12668 }
12669}
12670
mmenke9f2ec60c2015-06-01 20:59:4712671TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5512672 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112673
[email protected]8b8a197d2009-08-26 15:57:5812674 TestDelegate d;
12675 // Set correct login credentials. The delegate will be asked for them when
12676 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812677 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812678 {
Ryan Sleevib8449e02018-07-15 04:31:0712679 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512680 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12681 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612682 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912683 r->Start();
12684 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812685
Wez2a31b222018-06-07 22:07:1512686 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812687
[email protected]f7022f32014-08-21 16:32:1912688 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812689 EXPECT_EQ(1, d.response_started_count());
12690 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712691 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812692 }
12693}
12694
mmenke9f2ec60c2015-06-01 20:59:4712695TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5512696 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112697
[email protected]dd265012009-01-08 20:45:2712698 TestDelegate d;
12699 {
Ryan Sleevib8449e02018-07-15 04:31:0712700 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512701 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12702 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612703 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912704 r->Start();
12705 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712706
Wez2a31b222018-06-07 22:07:1512707 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712708
[email protected]f7022f32014-08-21 16:32:1912709 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712710 EXPECT_EQ(1, d.response_started_count());
12711 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712712 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2712713 }
12714}
[email protected]8b8a197d2009-08-26 15:57:5812715
mmenke9f2ec60c2015-06-01 20:59:4712716TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5512717 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112718
[email protected]8b8a197d2009-08-26 15:57:5812719 TestDelegate d;
12720 // Set correct login credentials. The delegate will be asked for them when
12721 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812722 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812723 {
Ryan Sleevib8449e02018-07-15 04:31:0712724 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512725 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12726 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612727 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912728 r->Start();
12729 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812730
Wez2a31b222018-06-07 22:07:1512731 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812732
[email protected]f7022f32014-08-21 16:32:1912733 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812734 EXPECT_EQ(1, d.response_started_count());
12735 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712736 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812737 }
12738}
[email protected]60a3df52009-09-22 16:13:2412739
mmenke9f2ec60c2015-06-01 20:59:4712740TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5512741 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112742
danakj8522a25b2016-04-16 00:17:3612743 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412744 {
12745 // Pass correct login identity in the URL.
Ryan Sleevib8449e02018-07-15 04:31:0712746 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512747 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12748 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612749 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912750 r->Start();
12751 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412752
Wez2a31b222018-06-07 22:07:1512753 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412754
[email protected]f7022f32014-08-21 16:32:1912755 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412756 EXPECT_EQ(1, d->response_started_count());
12757 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712758 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412759 }
12760
12761 d.reset(new TestDelegate);
12762 {
12763 // This request should use cached identity from previous request.
Ryan Sleevib8449e02018-07-15 04:31:0712764 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612765 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12766 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912767 r->Start();
12768 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412769
Wez2a31b222018-06-07 22:07:1512770 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412771
[email protected]f7022f32014-08-21 16:32:1912772 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412773 EXPECT_EQ(1, d->response_started_count());
12774 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712775 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412776 }
12777}
12778
mmenke9f2ec60c2015-06-01 20:59:4712779TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5512780 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112781
danakj8522a25b2016-04-16 00:17:3612782 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412783 // Set correct login credentials. The delegate will be asked for them when
12784 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812785 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2412786 {
Ryan Sleevib8449e02018-07-15 04:31:0712787 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512788 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12789 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612790 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912791 r->Start();
12792 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412793
Wez2a31b222018-06-07 22:07:1512794 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412795
[email protected]f7022f32014-08-21 16:32:1912796 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412797 EXPECT_EQ(1, d->response_started_count());
12798 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712799 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412800 }
12801
12802 // Use a new delegate without explicit credentials. The cached ones should be
12803 // used.
12804 d.reset(new TestDelegate);
12805 {
12806 // Don't pass wrong credentials in the URL, they would override valid cached
12807 // ones.
Ryan Sleevib8449e02018-07-15 04:31:0712808 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612809 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12810 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912811 r->Start();
12812 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412813
Wez2a31b222018-06-07 22:07:1512814 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412815
[email protected]f7022f32014-08-21 16:32:1912816 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412817 EXPECT_EQ(1, d->response_started_count());
12818 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712819 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412820 }
12821}
ricea3a1c71f2016-06-17 10:05:2612822
12823TEST_F(URLRequestTestFTP, RawBodyBytes) {
12824 ASSERT_TRUE(ftp_test_server_.Start());
12825
12826 TestDelegate d;
12827 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612828 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12829 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2612830 req->Start();
Wez2a31b222018-06-07 22:07:1512831 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:2612832
12833 EXPECT_EQ(6, req->GetRawBodyBytes());
12834}
12835
Matt Menkebeb95e8a2019-07-15 06:04:0912836TEST_F(URLRequestTestFTP, FtpAuthCancellation) {
Emily Stark6668e092019-06-20 18:36:3812837 ftp_test_server_.set_no_anonymous_ftp_user(true);
12838 ASSERT_TRUE(ftp_test_server_.Start());
12839 TestDelegate d;
12840 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
12841 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12842 TRAFFIC_ANNOTATION_FOR_TESTS));
12843 req->Start();
12844 d.RunUntilComplete();
12845
12846 ASSERT_TRUE(d.auth_required_called());
Emily Stark89a3247d2019-06-26 18:07:4012847 EXPECT_EQ(OK, d.request_status());
Emily Stark6668e092019-06-20 18:36:3812848 EXPECT_TRUE(req->auth_challenge_info());
Emily Stark89a3247d2019-06-26 18:07:4012849 std::string mime_type;
12850 req->GetMimeType(&mime_type);
12851 EXPECT_EQ("text/plain", mime_type);
12852 EXPECT_EQ("", d.data_received());
12853 EXPECT_EQ(-1, req->GetExpectedContentSize());
Emily Stark6668e092019-06-20 18:36:3812854}
12855
Matt Menkef1b97e02019-05-13 23:52:4112856class URLRequestTestFTPOverHttpProxy : public URLRequestTestFTP {
12857 public:
12858 // Test interface:
12859 void SetUp() override {
12860 proxy_resolution_service_ = ProxyResolutionService::CreateFixed(
12861 "localhost", TRAFFIC_ANNOTATION_FOR_TESTS);
12862 default_context_->set_proxy_resolution_service(
12863 proxy_resolution_service_.get());
12864 URLRequestTestFTP::SetUp();
12865 }
12866
12867 private:
12868 std::unique_ptr<ProxyResolutionService> proxy_resolution_service_;
12869};
12870
12871// Check that FTP is not supported over an HTTP proxy.
12872TEST_F(URLRequestTestFTPOverHttpProxy, Fails) {
12873 TestDelegate delegate;
12874 std::unique_ptr<URLRequest> request(
12875 default_context_->CreateRequest(GURL("ftp://foo.test/"), DEFAULT_PRIORITY,
12876 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12877 request->Start();
12878 delegate.RunUntilComplete();
12879
12880 EXPECT_THAT(delegate.request_status(), IsError(ERR_NO_SUPPORTED_PROXIES));
12881}
12882
brettwa1228ebb2016-10-28 03:51:3412883#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5112884
ttuttlec0c828492015-05-15 01:25:5512885TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
12886 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712887 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612888 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512889
12890 EXPECT_FALSE(req->response_info().network_accessed);
12891
12892 req->Start();
Wez2a31b222018-06-07 22:07:1512893 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512894
12895 EXPECT_EQ(1, default_network_delegate_.completed_requests());
12896 EXPECT_FALSE(req->response_info().network_accessed);
12897}
12898
12899TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
12900 MockHostResolver host_resolver;
12901 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
12902 TestURLRequestContext context(true);
12903 context.set_network_delegate(&network_delegate);
12904 context.set_host_resolver(&host_resolver);
12905 host_resolver.rules()->AddSimulatedFailure("*");
12906 context.Init();
12907
12908 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612909 std::unique_ptr<URLRequest> req(
12910 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
12911 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512912
12913 EXPECT_FALSE(req->response_info().network_accessed);
12914
12915 req->Start();
Wez2a31b222018-06-07 22:07:1512916 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512917 EXPECT_TRUE(req->response_info().network_accessed);
12918}
12919
mmenkeed0498b2015-12-08 23:20:4212920// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2212921// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4212922TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2212923 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712924 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612925 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
12926 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2212927
danakj8522a25b2016-04-16 00:17:3612928 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2212929 req.get(), &default_network_delegate_,
12930 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4212931 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
12932 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2212933
12934 req->Start();
12935 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2212936 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5012937 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2212938 EXPECT_EQ(0, d.received_redirect_count());
12939}
12940
Andrey Kosyakov2e893e62017-08-31 17:00:5212941TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412942 ASSERT_TRUE(http_test_server()->Start());
12943 TestURLRequestContext context;
12944 GURL url(http_test_server()->GetURL("/cachetime"));
12945 TestDelegate delegate;
12946 HttpRequestHeaders extra_headers;
12947 extra_headers.SetHeader("X-Foo", "bar");
12948
12949 {
Andrey Kosyakov2e893e62017-08-31 17:00:5212950 HttpRawRequestHeaders raw_req_headers;
12951 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12952
Andrey Kosyakov83a6eee2017-08-14 19:20:0412953 std::unique_ptr<URLRequest> r(context.CreateRequest(
12954 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12955 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212956 r->SetRequestHeadersCallback(base::Bind(
12957 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
12958 r->SetResponseHeadersCallback(base::Bind(
12959 [](scoped_refptr<const HttpResponseHeaders>* left,
12960 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12961 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412962 r->Start();
12963 while (!delegate.response_started_count())
12964 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5212965 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412966 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212967 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412968 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212969 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412970 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212971 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
12972 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
12973 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
12974 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412975 }
12976 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412977 std::unique_ptr<URLRequest> r(context.CreateRequest(
12978 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12979 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212980 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412981 FAIL() << "Callback should not be called unless request is sent";
12982 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212983 r->SetResponseHeadersCallback(
12984 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
12985 FAIL() << "Callback should not be called unless request is sent";
12986 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412987 r->Start();
Wez2a31b222018-06-07 22:07:1512988 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412989 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412990 }
12991}
12992
Andrey Kosyakov2e893e62017-08-31 17:00:5212993TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412994 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5212995 HttpRawRequestHeaders raw_req_headers;
12996 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12997
Andrey Kosyakov83a6eee2017-08-14 19:20:0412998 TestURLRequestContext context;
12999 TestDelegate delegate;
13000 HttpRequestHeaders extra_headers;
13001 extra_headers.SetHeader("X-Foo", "bar");
Andrey Kosyakov83a6eee2017-08-14 19:20:0413002 GURL url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:0713003 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0413004 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
13005 r->SetExtraRequestHeaders(extra_headers);
13006 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5213007 base::Unretained(&raw_req_headers)));
13008 r->SetResponseHeadersCallback(base::Bind(
13009 [](scoped_refptr<const HttpResponseHeaders>* left,
13010 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
13011 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413012 r->Start();
Wez0e717112018-06-18 23:09:2213013 delegate.RunUntilRedirect();
Andrey Kosyakov83a6eee2017-08-14 19:20:0413014
13015 ASSERT_EQ(1, delegate.received_redirect_count());
13016 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5213017 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413018 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5213019 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413020 EXPECT_EQ("gzip, deflate", value);
13021 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5213022 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
13023 raw_req_headers.request_line());
13024 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
13025 EXPECT_EQ(302, raw_resp_headers->response_code());
13026 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0413027
Andrey Kosyakov2e893e62017-08-31 17:00:5213028 raw_req_headers = HttpRawRequestHeaders();
13029 raw_resp_headers = nullptr;
Arthur Sonzognib8465ff72019-01-04 18:44:3513030 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
13031 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:1513032 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5213033 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413034 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5213035 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413036 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5213037 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
13038 raw_req_headers.request_line());
13039 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0413040}
13041
Andrey Kosyakov2e893e62017-08-31 17:00:5213042TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0413043 TestDelegate request_delegate;
13044
Ryan Sleevib8449e02018-07-15 04:31:0713045 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0413046 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
13047 TRAFFIC_ANNOTATION_FOR_TESTS));
13048 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
13049 FAIL() << "Callback should not be called unless request is sent";
13050 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5213051 r->SetResponseHeadersCallback(
13052 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
13053 FAIL() << "Callback should not be called unless request is sent";
13054 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413055 r->Start();
Wez2a31b222018-06-07 22:07:1513056 request_delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0413057 EXPECT_FALSE(r->is_pending());
13058}
13059
Andrey Kosyakov2e893e62017-08-31 17:00:5213060TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0413061 ASSERT_TRUE(http_test_server()->Start());
13062 GURL url(http_test_server()->GetURL("/auth-basic"));
13063
13064 TestURLRequestContext context;
13065 TestDelegate delegate;
13066
13067 delegate.set_credentials(AuthCredentials(kUser, kSecret));
13068 HttpRequestHeaders extra_headers;
13069 extra_headers.SetHeader("X-Foo", "bar");
13070
Andrey Kosyakov2e893e62017-08-31 17:00:5213071 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
13072 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0413073
Andrey Kosyakov2e893e62017-08-31 17:00:5213074 using RespHeadersVector =
13075 std::vector<scoped_refptr<const HttpResponseHeaders>>;
13076 RespHeadersVector raw_resp_headers;
13077
13078 auto req_headers_callback = base::Bind(
13079 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
13080 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
13081 },
13082 &raw_req_headers);
13083 auto resp_headers_callback = base::Bind(
13084 [](RespHeadersVector* vec,
13085 scoped_refptr<const HttpResponseHeaders> headers) {
13086 vec->push_back(headers);
13087 },
13088 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0413089 std::unique_ptr<URLRequest> r(context.CreateRequest(
13090 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
13091 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5213092 r->SetRequestHeadersCallback(req_headers_callback);
13093 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0413094 r->Start();
Wez2a31b222018-06-07 22:07:1513095 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0413096 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5213097 ASSERT_EQ(raw_req_headers.size(), 2u);
13098 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0413099 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5213100 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
13101 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413102 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5213103 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
13104 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413105 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5213106 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
13107 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
13108 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
13109 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
13110
13111 std::unique_ptr<URLRequest> r2(context.CreateRequest(
13112 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
13113 r2->SetExtraRequestHeaders(extra_headers);
13114 r2->SetRequestHeadersCallback(req_headers_callback);
13115 r2->SetResponseHeadersCallback(resp_headers_callback);
13116 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
13117 r2->Start();
Wez2a31b222018-06-07 22:07:1513118 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5213119 EXPECT_FALSE(r2->is_pending());
13120 ASSERT_EQ(raw_req_headers.size(), 3u);
13121 ASSERT_EQ(raw_resp_headers.size(), 3u);
13122 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
13123 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
13124 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
13125 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0413126}
13127
Andrey Kosyakov2e893e62017-08-31 17:00:5213128TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0413129 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
13130 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0713131 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0413132 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13133 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5213134 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0413135 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5213136 r->SetResponseHeadersCallback(
13137 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
13138 FAIL() << "Callback should not be called for non-HTTP schemes";
13139 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413140 r->Start();
Wez2a31b222018-06-07 22:07:1513141 d.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0413142 EXPECT_FALSE(r->is_pending());
13143}
13144
Carlos ILaef65d62018-06-04 21:24:1313145TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
13146 TestDelegate d;
13147 BlockingNetworkDelegate network_delegate(
13148 BlockingNetworkDelegate::SYNCHRONOUS);
13149 const GURL kOriginalUrl("https://original.test");
13150 const GURL kRedirectUrl("http://redirect.test");
13151 network_delegate.set_redirect_url(kRedirectUrl);
13152 TestURLRequestContext context(true /* delay_initialization */);
13153 context.set_network_delegate(&network_delegate);
13154 context.Init();
13155
13156 std::unique_ptr<URLRequest> r(context.CreateRequest(
13157 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13158 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1313159 r->Start();
Wez0e717112018-06-18 23:09:2213160 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313161 GURL::Replacements replacements;
13162 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
13163 // was set.
13164 replacements.SetSchemeStr("https");
13165 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
13166 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4413167 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313168}
13169
13170TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
13171 TestDelegate d;
13172 BlockingNetworkDelegate network_delegate(
13173 BlockingNetworkDelegate::SYNCHRONOUS);
13174 const GURL kOriginalUrl("https://original.test");
13175 const GURL kRedirectUrl("http://redirect.test:80");
13176 network_delegate.set_redirect_url(kRedirectUrl);
13177 TestURLRequestContext context(true /* delay_initialization */);
13178 context.set_network_delegate(&network_delegate);
13179 context.Init();
13180
13181 std::unique_ptr<URLRequest> r(context.CreateRequest(
13182 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13183 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1313184 r->Start();
Wez0e717112018-06-18 23:09:2213185 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313186 GURL::Replacements replacements;
13187 // The URL host should have not been changed.
13188 EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
13189 // The scheme should now be https, and the effective port should now be 443.
13190 EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
13191 EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
Carlos IL0d67fc72018-06-22 17:18:4413192 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313193}
13194
13195TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
13196 TestDelegate d;
13197 BlockingNetworkDelegate network_delegate(
13198 BlockingNetworkDelegate::SYNCHRONOUS);
13199 const GURL kOriginalUrl("https://original.test");
13200 const GURL kRedirectUrl("http://redirect.test:1234");
13201 network_delegate.set_redirect_url(kRedirectUrl);
13202 TestURLRequestContext context(true /* delay_initialization */);
13203 context.set_network_delegate(&network_delegate);
13204 context.Init();
13205
13206 std::unique_ptr<URLRequest> r(context.CreateRequest(
13207 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13208 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1313209 r->Start();
Wez0e717112018-06-18 23:09:2213210 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313211 GURL::Replacements replacements;
13212 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
13213 // was set, nonstandard port should not have been modified.
13214 replacements.SetSchemeStr("https");
13215 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
13216 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4413217 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313218}
13219
13220TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
13221 TestDelegate d;
13222 BlockingNetworkDelegate network_delegate(
13223 BlockingNetworkDelegate::SYNCHRONOUS);
13224 const GURL kOriginalUrl("https://original.test");
13225 const GURL kRedirectUrl("http://redirect.test");
13226 network_delegate.set_redirect_url(kRedirectUrl);
13227 TestURLRequestContext context(true /* delay_initialization */);
13228 context.set_network_delegate(&network_delegate);
13229 context.Init();
13230 std::unique_ptr<URLRequest> r(context.CreateRequest(
13231 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13232 r->set_upgrade_if_insecure(false);
Carlos ILaef65d62018-06-04 21:24:1313233 r->Start();
Wez0e717112018-06-18 23:09:2213234 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313235 // The redirect URL should not be changed if the upgrade_if_insecure flag is
13236 // not set.
13237 EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4413238 EXPECT_FALSE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313239}
13240
Paul Jensen60e45532018-02-19 16:04:1813241// Test that URLRequests get properly tagged.
13242#if defined(OS_ANDROID)
13243TEST_F(URLRequestTestHTTP, TestTagging) {
Peter Collingbourne8ccab722019-02-12 18:10:4813244 if (!CanGetTaggedBytes()) {
13245 DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
13246 return;
13247 }
13248
Paul Jensen60e45532018-02-19 16:04:1813249 ASSERT_TRUE(http_test_server()->Start());
13250
13251 // The tag under which the system reports untagged traffic.
13252 static const int32_t UNTAGGED_TAG = 0;
13253
13254 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
13255
13256 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
13257 TestDelegate delegate;
Ryan Sleevib8449e02018-07-15 04:31:0713258 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Paul Jensen60e45532018-02-19 16:04:1813259 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
13260 TRAFFIC_ANNOTATION_FOR_TESTS));
13261 EXPECT_EQ(SocketTag(), req->socket_tag());
13262 req->Start();
Wez2a31b222018-06-07 22:07:1513263 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1813264
13265 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
13266
13267 int32_t tag_val1 = 0x12345678;
13268 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
13269 old_traffic = GetTaggedBytes(tag_val1);
13270
13271 // Test specific tag value.
Ryan Sleevib8449e02018-07-15 04:31:0713272 req = default_context().CreateRequest(http_test_server()->GetURL("/"),
13273 DEFAULT_PRIORITY, &delegate,
13274 TRAFFIC_ANNOTATION_FOR_TESTS);
Paul Jensen60e45532018-02-19 16:04:1813275 req->set_socket_tag(tag1);
13276 EXPECT_EQ(tag1, req->socket_tag());
13277 req->Start();
Wez2a31b222018-06-07 22:07:1513278 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1813279
13280 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
13281}
13282#endif
13283
Steven Valdez1c1859172019-04-10 15:33:2813284// Provides a response to the 0RTT request indicating whether it was received
13285// as early data, sending HTTP_TOO_EARLY if enabled.
13286class ZeroRTTResponse : public test_server::BasicHttpResponse {
13287 public:
13288 ZeroRTTResponse(bool zero_rtt, bool send_too_early)
13289 : zero_rtt_(zero_rtt), send_too_early_(send_too_early) {}
13290 ~ZeroRTTResponse() override {}
13291
13292 void SendResponse(const test_server::SendBytesCallback& send,
13293 const test_server::SendCompleteCallback& done) override {
13294 AddCustomHeader("Vary", "Early-Data");
13295 set_content_type("text/plain");
13296 AddCustomHeader("Cache-Control", "no-cache");
13297 if (zero_rtt_) {
13298 if (send_too_early_)
13299 set_code(HTTP_TOO_EARLY);
13300 set_content("1");
13301 } else {
13302 set_content("0");
13303 }
13304
13305 // Since the EmbeddedTestServer doesn't keep the socket open by default,
13306 // it is explicitly kept alive to allow the remaining leg of the 0RTT
13307 // handshake to be received after the early data.
13308 send.Run(ToResponseString(), base::DoNothing());
13309 }
13310
13311 private:
13312 bool zero_rtt_;
13313 bool send_too_early_;
13314
13315 DISALLOW_COPY_AND_ASSIGN(ZeroRTTResponse);
13316};
13317
13318std::unique_ptr<test_server::HttpResponse> HandleZeroRTTRequest(
13319 const test_server::HttpRequest& request) {
13320 if (request.GetURL().path() != "/zerortt")
13321 return nullptr;
13322 auto iter = request.headers.find("Early-Data");
13323 bool zero_rtt = iter != request.headers.end() && iter->second == "1";
13324 return std::make_unique<ZeroRTTResponse>(zero_rtt, false);
13325}
13326
Gabriel Charette694c3c332019-08-19 14:53:0513327class HTTPSEarlyDataTest : public TestWithTaskEnvironment {
Steven Valdez1c1859172019-04-10 15:33:2813328 public:
13329 HTTPSEarlyDataTest()
13330 : context_(true), test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
13331 auto params = std::make_unique<HttpNetworkSession::Params>();
13332 params->enable_early_data = true;
13333 context_.set_http_network_session_params(std::move(params));
13334
13335 context_.set_network_delegate(&network_delegate_);
13336 cert_verifier_.set_default_result(OK);
13337 context_.set_cert_verifier(&cert_verifier_);
13338
David Benjamin151ec6b2019-08-02 19:38:5213339 SSLContextConfig config;
13340 config.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
13341 ssl_config_service_ = std::make_unique<TestSSLConfigService>(config);
Steven Valdez1c1859172019-04-10 15:33:2813342 context_.set_ssl_config_service(ssl_config_service_.get());
13343
13344 context_.Init();
13345
13346 ssl_config_.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
13347 ssl_config_.early_data_enabled = true;
13348 test_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config_);
13349 test_server_.AddDefaultHandlers(
13350 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
13351 test_server_.RegisterRequestHandler(
13352 base::BindRepeating(&HandleZeroRTTRequest));
13353 }
13354
13355 ~HTTPSEarlyDataTest() override = default;
13356
13357 void ResetSSLConfig(net::EmbeddedTestServer::ServerCertificate cert,
13358 uint16_t version) {
13359 ssl_config_.version_max = version;
13360 test_server_.ResetSSLConfig(cert, ssl_config_);
13361 }
13362
13363 protected:
13364 MockCertVerifier cert_verifier_;
13365 TestNetworkDelegate network_delegate_; // Must outlive URLRequest.
13366 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
13367 TestURLRequestContext context_;
13368
13369 SSLServerConfig ssl_config_;
13370 EmbeddedTestServer test_server_;
13371};
13372
13373// TLSEarlyDataTest tests that we handle early data correctly.
13374TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTest) {
13375 ASSERT_TRUE(test_server_.Start());
13376 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13377
13378 {
13379 TestDelegate d;
13380 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13381 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13382 TRAFFIC_ANNOTATION_FOR_TESTS));
13383 r->Start();
13384 EXPECT_TRUE(r->is_pending());
13385
13386 base::RunLoop().Run();
13387
13388 EXPECT_EQ(1, d.response_started_count());
13389
13390 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13391 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13392 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13393 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13394 r->ssl_info().cert.get()));
13395
13396 // The Early-Data header should be omitted in the initial request, and the
13397 // handler should return "0".
13398 EXPECT_EQ("0", d.data_received());
13399 }
13400
13401 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13402
13403 {
13404 TestDelegate d;
13405 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13406 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13407 TRAFFIC_ANNOTATION_FOR_TESTS));
13408
13409 r->Start();
13410 EXPECT_TRUE(r->is_pending());
13411
13412 base::RunLoop().Run();
13413
13414 EXPECT_EQ(1, d.response_started_count());
13415
13416 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13417 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13418 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13419 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13420 r->ssl_info().cert.get()));
13421
13422 // The Early-Data header should be a single '1' in the resumed request, and
13423 // the handler should return "1".
13424 EXPECT_EQ("1", d.data_received());
13425 }
13426}
13427
13428// TLSEarlyDataTest tests that we handle early data correctly for POST.
13429TEST_F(HTTPSEarlyDataTest, TLSEarlyDataPOSTTest) {
13430 ASSERT_TRUE(test_server_.Start());
13431 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13432
13433 {
13434 TestDelegate d;
13435 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13436 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13437 TRAFFIC_ANNOTATION_FOR_TESTS));
13438 r->Start();
13439 EXPECT_TRUE(r->is_pending());
13440
13441 base::RunLoop().Run();
13442
13443 EXPECT_EQ(1, d.response_started_count());
13444
13445 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13446 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13447 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13448 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13449 r->ssl_info().cert.get()));
13450
13451 // The Early-Data header should be omitted in the initial request, and the
13452 // handler should return "0".
13453 EXPECT_EQ("0", d.data_received());
13454 }
13455
13456 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13457
13458 {
13459 TestDelegate d;
13460 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13461 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13462 TRAFFIC_ANNOTATION_FOR_TESTS));
13463 r->set_method("POST");
13464 r->Start();
13465 EXPECT_TRUE(r->is_pending());
13466
13467 base::RunLoop().Run();
13468
13469 EXPECT_EQ(1, d.response_started_count());
13470
13471 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13472 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13473 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13474 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13475 r->ssl_info().cert.get()));
13476
13477 // The Early-Data header should be omitted in the request, since we don't
13478 // send POSTs over early data, and the handler should return "0".
13479 EXPECT_EQ("0", d.data_received());
13480 }
13481}
13482
13483std::unique_ptr<test_server::HttpResponse> HandleTooEarly(
13484 bool* sent_425,
13485 const test_server::HttpRequest& request) {
13486 if (request.GetURL().path() != "/tooearly")
13487 return nullptr;
13488 auto iter = request.headers.find("Early-Data");
13489 bool zero_rtt = iter != request.headers.end() && iter->second == "1";
13490 if (zero_rtt)
13491 *sent_425 = true;
13492 return std::make_unique<ZeroRTTResponse>(zero_rtt, true);
13493}
13494
13495// Test that we handle 425 (Too Early) correctly.
13496TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTooEarlyTest) {
13497 bool sent_425 = false;
13498 test_server_.RegisterRequestHandler(
13499 base::BindRepeating(&HandleTooEarly, base::Unretained(&sent_425)));
13500 ASSERT_TRUE(test_server_.Start());
13501 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13502
13503 {
13504 TestDelegate d;
13505 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13506 test_server_.GetURL("/tooearly"), DEFAULT_PRIORITY, &d,
13507 TRAFFIC_ANNOTATION_FOR_TESTS));
13508 r->Start();
13509 EXPECT_TRUE(r->is_pending());
13510
13511 d.RunUntilComplete();
13512
13513 EXPECT_EQ(1, d.response_started_count());
13514
13515 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13516 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13517 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13518 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13519 r->ssl_info().cert.get()));
13520
13521 // The Early-Data header should be omitted in the initial request, and the
13522 // handler should return "0".
13523 EXPECT_EQ("0", d.data_received());
13524 EXPECT_FALSE(sent_425);
13525 }
13526
13527 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13528
13529 {
13530 TestDelegate d;
13531 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13532 test_server_.GetURL("/tooearly"), DEFAULT_PRIORITY, &d,
13533 TRAFFIC_ANNOTATION_FOR_TESTS));
13534
13535 r->Start();
13536 EXPECT_TRUE(r->is_pending());
13537
13538 d.RunUntilComplete();
13539
13540 EXPECT_EQ(1, d.response_started_count());
13541
13542 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13543 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13544 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13545 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13546 r->ssl_info().cert.get()));
13547
13548 // The resumption request will encounter a 425 error and retry without early
13549 // data, and the handler should return "0".
13550 EXPECT_EQ("0", d.data_received());
13551 EXPECT_TRUE(sent_425);
13552 }
13553}
13554
13555// TLSEarlyDataRejectTest tests that we gracefully handle an early data reject
13556// and retry without early data.
13557TEST_F(HTTPSEarlyDataTest, TLSEarlyDataRejectTest) {
13558 ASSERT_TRUE(test_server_.Start());
13559 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13560
13561 {
13562 TestDelegate d;
13563 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13564 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13565 TRAFFIC_ANNOTATION_FOR_TESTS));
13566
13567 r->Start();
13568 EXPECT_TRUE(r->is_pending());
13569
13570 d.RunUntilComplete();
13571
13572 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13573 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13574 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13575 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13576 r->ssl_info().cert.get()));
13577
13578 // The Early-Data header should be omitted in the initial request, and the
13579 // handler should return "0".
13580 EXPECT_EQ("0", d.data_received());
13581 }
13582
13583 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13584
13585 // The certificate in the resumption is changed to confirm that the
13586 // certificate change is observed.
13587 scoped_refptr<X509Certificate> old_cert = test_server_.GetCertificate();
13588 ResetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED,
13589 SSL_PROTOCOL_VERSION_TLS1_3);
13590
13591 {
13592 TestDelegate d;
13593 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13594 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13595 TRAFFIC_ANNOTATION_FOR_TESTS));
13596
13597 r->Start();
13598 EXPECT_TRUE(r->is_pending());
13599
13600 d.RunUntilComplete();
13601
13602 EXPECT_EQ(1, d.response_started_count());
13603
13604 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13605 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13606 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13607 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13608 r->ssl_info().cert.get()));
13609 EXPECT_FALSE(old_cert->EqualsIncludingChain(r->ssl_info().cert.get()));
13610
13611 // The Early-Data header should be omitted in the rejected request, and the
13612 // handler should return "0".
13613 EXPECT_EQ("0", d.data_received());
13614 }
13615}
13616
13617// TLSEarlyDataTLS12RejectTest tests that we gracefully handle an early data
13618// reject from a TLS 1.2 server and retry without early data.
13619TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTLS12RejectTest) {
13620 ASSERT_TRUE(test_server_.Start());
13621 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13622
13623 {
13624 TestDelegate d;
13625 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13626 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13627 TRAFFIC_ANNOTATION_FOR_TESTS));
13628
13629 r->Start();
13630 EXPECT_TRUE(r->is_pending());
13631
13632 d.RunUntilComplete();
13633
13634 EXPECT_EQ(1, d.response_started_count());
13635
13636 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13637 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13638 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13639 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13640 r->ssl_info().cert.get()));
13641
13642 // The Early-Data header should be omitted in the initial request, and the
13643 // handler should return "0".
13644 EXPECT_EQ("0", d.data_received());
13645 }
13646
13647 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13648
13649 // The certificate in the resumption is changed to confirm that the
13650 // certificate change is observed.
13651 scoped_refptr<X509Certificate> old_cert = test_server_.GetCertificate();
13652 ResetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED,
13653 SSL_PROTOCOL_VERSION_TLS1_2);
13654
13655 {
13656 TestDelegate d;
13657 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13658 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13659 TRAFFIC_ANNOTATION_FOR_TESTS));
13660
13661 r->Start();
13662 EXPECT_TRUE(r->is_pending());
13663
13664 d.RunUntilComplete();
13665
13666 EXPECT_EQ(1, d.response_started_count());
13667
13668 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_2,
13669 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13670 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13671 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13672 r->ssl_info().cert.get()));
13673 EXPECT_FALSE(old_cert->EqualsIncludingChain(r->ssl_info().cert.get()));
13674
13675 // The Early-Data header should be omitted in the rejected request, and the
13676 // handler should return "0".
13677 EXPECT_EQ("0", d.data_received());
13678 }
13679}
13680
Emily Stark08f6c972019-05-28 17:24:2713681// Tests that AuthChallengeInfo is available on the request.
13682TEST_F(URLRequestTestHTTP, AuthChallengeInfo) {
13683 ASSERT_TRUE(http_test_server()->Start());
13684 GURL url(http_test_server()->GetURL("/auth-basic"));
13685
13686 TestURLRequestContext context;
13687 TestDelegate delegate;
13688
13689 std::unique_ptr<URLRequest> r(context.CreateRequest(
13690 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
13691 r->Start();
13692 delegate.RunUntilComplete();
13693 ASSERT_TRUE(r->auth_challenge_info().has_value());
13694 EXPECT_FALSE(r->auth_challenge_info()->is_proxy);
13695 EXPECT_EQ(url::Origin::Create(url), r->auth_challenge_info()->challenger);
13696 EXPECT_EQ("basic", r->auth_challenge_info()->scheme);
13697 EXPECT_EQ("testrealm", r->auth_challenge_info()->realm);
13698 EXPECT_EQ("Basic realm=\"testrealm\"", r->auth_challenge_info()->challenge);
13699 EXPECT_EQ("/auth-basic", r->auth_challenge_info()->path);
13700}
13701
[email protected]7461a402011-03-24 23:19:5113702} // namespace net