blob: 7907e959a1aeff6f0c5657041be6de2ddcab70a8 [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.
Bence Béky98447b12018-05-08 03:14:01808class URLRequestTest : public PlatformTest, public WithScopedTaskEnvironment {
[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
2687 // SetCanonicalCookie (and therefore SetCookieWithOptions) fail.
2688 GURL::Replacements replace_scheme;
2689 replace_scheme.SetSchemeStr("https");
2690 GURL url = test_server.base_url().ReplaceComponents(replace_scheme);
2691
2692 delayed_cm->SetCookieWithOptionsAsync(url, "AlreadySetCookie=1;Secure",
2693 CookieOptions(),
2694 CookieStore::SetCookiesCallback());
2695 cm->SetCookieWithOptionsAsync(url, "AlreadySetCookie=1;Secure",
2696 CookieOptions(),
2697 CookieStore::SetCookiesCallback());
2698
2699 std::vector<std::string> cookie_lines(
Lily Chenf5732c82019-08-01 00:01:542700 {// Fails in SetCanonicalCookie for trying to set a secure cookie
Aaron Tagliaboschi028009e2019-03-07 16:28:062701 // on an insecure host.
2702 "CookieNotSet=1;Secure",
2703 // Fail in FilteringTestLayeredNetworkDelegate::CanGetCookie.
2704 "CookieBlockedOnCanGetCookie=1",
2705 // Fails in SetCanonicalCookie for trying to overwrite a secure cookie
2706 // with an insecure cookie.
2707 "AlreadySetCookie=1",
2708 // Succeeds and added cookie to store. Delayed (which makes the callback
2709 // run asynchronously) in DelayedCookieMonster.
2710 "CookieSet=1"});
2711
2712 for (auto first_cookie_line : cookie_lines) {
2713 for (auto second_cookie_line : cookie_lines) {
2714 // Run with the delayed cookie monster.
2715 std::unique_ptr<URLRequest> request = async_context.CreateRequest(
2716 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2717 second_cookie_line),
2718 DEFAULT_PRIORITY, &async_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2719
2720 request->Start();
2721 async_delegate.RunUntilComplete();
2722 EXPECT_THAT(async_delegate.request_status(), IsOk());
2723
2724 // Run with the regular cookie monster.
2725 request = sync_context.CreateRequest(
2726 test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
2727 second_cookie_line),
2728 DEFAULT_PRIORITY, &sync_delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
2729
2730 request->Start();
2731 sync_delegate.RunUntilComplete();
2732 EXPECT_THAT(sync_delegate.request_status(), IsOk());
2733
2734 int expected_set_cookie_count = 0;
2735 int expected_blocked_cookie_count = 0;
2736
Lily Chenf5732c82019-08-01 00:01:542737 // 2 calls to the delegate's OnCanSetCookie method are expected, even if
2738 // the cookies don't end up getting set.
2739 expected_set_cookie_count += 2;
Aaron Tagliaboschi028009e2019-03-07 16:28:062740
2741 if (first_cookie_line == "CookieBlockedOnCanGetCookie=1")
2742 ++expected_blocked_cookie_count;
2743 if (second_cookie_line == "CookieBlockedOnCanGetCookie=1")
2744 ++expected_blocked_cookie_count;
2745
2746 EXPECT_EQ(expected_set_cookie_count,
2747 async_filter_network_delegate.set_cookie_called_count());
2748 EXPECT_EQ(expected_blocked_cookie_count,
2749 async_filter_network_delegate.blocked_set_cookie_count());
2750
2751 EXPECT_EQ(expected_set_cookie_count,
2752 sync_filter_network_delegate.set_cookie_called_count());
2753 EXPECT_EQ(expected_blocked_cookie_count,
2754 sync_filter_network_delegate.blocked_set_cookie_count());
2755
2756 async_filter_network_delegate.ResetSetCookieCalledCount();
2757 async_filter_network_delegate.ResetBlockedSetCookieCount();
2758
2759 sync_filter_network_delegate.ResetSetCookieCalledCount();
2760 sync_filter_network_delegate.ResetBlockedSetCookieCount();
2761 }
2762 }
2763}
2764
[email protected]f2f31b32013-01-16 23:24:092765TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392766 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442767 ASSERT_TRUE(test_server.Start());
2768
2769 // Set up a cookie.
2770 {
2771 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072772 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442773 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072774 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552775 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162776 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192777 req->Start();
Wez2a31b222018-06-07 22:07:152778 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442779 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2780 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2781 }
2782
2783 // Verify that the cookie is set.
2784 {
2785 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072786 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442787 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072788 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162789 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2790 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192791 req->Start();
Wez2a31b222018-06-07 22:07:152792 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442793
2794 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2795 != std::string::npos);
2796 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2797 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2798 }
2799
2800 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2801 {
2802 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072803 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442804 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072805 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162806 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2807 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192808 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2809 req->Start();
Wez2a31b222018-06-07 22:07:152810 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442811
2812 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2813 == std::string::npos);
2814
2815 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2816 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2817 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2818 }
2819}
2820
2821TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392822 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442823 ASSERT_TRUE(test_server.Start());
2824
2825 // Set up a cookie.
2826 {
2827 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072828 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442829 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072830 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552831 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162832 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192833 req->Start();
Wez2a31b222018-06-07 22:07:152834 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442835
2836 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2837 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2838 EXPECT_EQ(1, network_delegate.set_cookie_count());
2839 }
2840
2841 // Try to set-up another cookie and update the previous cookie.
2842 {
2843 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072844 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442845 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072846 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552847 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162848 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192849 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2850 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442851
Wez2a31b222018-06-07 22:07:152852 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442853
2854 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2855 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2856 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2857 EXPECT_EQ(0, network_delegate.set_cookie_count());
2858 }
2859
2860 // Verify the cookies weren't saved or updated.
2861 {
2862 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072863 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442864 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072865 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162866 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2867 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192868 req->Start();
Wez2a31b222018-06-07 22:07:152869 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442870
2871 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2872 == std::string::npos);
2873 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2874 != std::string::npos);
2875
2876 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2877 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2878 EXPECT_EQ(0, network_delegate.set_cookie_count());
2879 }
2880}
2881
2882TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392883 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442884 ASSERT_TRUE(test_server.Start());
2885
2886 // Set up a cookie.
2887 {
2888 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072889 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442890 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072891 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552892 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162893 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192894 req->Start();
Wez2a31b222018-06-07 22:07:152895 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442896
2897 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2898 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2899 }
2900
2901 // Verify that the cookie is set.
2902 {
2903 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072904 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442905 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072906 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162907 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2908 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192909 req->Start();
Wez2a31b222018-06-07 22:07:152910 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442911
2912 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2913 != std::string::npos);
2914
2915 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2916 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Eric Roman79cc7552019-07-19 02:17:542917 auto entries = net_log_.GetEntries();
Helen Li830d5708d62018-08-22 16:29:182918 for (const auto& entry : entries) {
2919 EXPECT_NE(entry.type,
2920 NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE);
2921 }
[email protected]316c1e5e2012-09-12 15:17:442922 }
2923
2924 // Verify that the cookie isn't sent.
2925 {
2926 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072927 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442928 TestDelegate d;
2929 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:072930 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162931 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2932 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192933 req->Start();
Wez2a31b222018-06-07 22:07:152934 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442935
2936 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2937 == std::string::npos);
2938
[email protected]22e045f2013-09-20 03:54:032939 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442940 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Eric Roman79cc7552019-07-19 02:17:542941 auto entries = net_log_.GetEntries();
Helen Li830d5708d62018-08-22 16:29:182942 ExpectLogContainsSomewhereAfter(
2943 entries, 0, NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE,
2944 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442945 }
2946}
2947
marqf14fff8d2015-12-02 15:52:292948// TODO(crbug.com/564656) This test is flaky on iOS.
2949#if defined(OS_IOS)
2950#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2951#else
2952#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2953#endif
[email protected]316c1e5e2012-09-12 15:17:442954TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392955 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442956 ASSERT_TRUE(test_server.Start());
2957
2958 // Set up a cookie.
2959 {
2960 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072961 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442962 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072963 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552964 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162965 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192966 req->Start();
Wez2a31b222018-06-07 22:07:152967 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442968
2969 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2970 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Eric Roman79cc7552019-07-19 02:17:542971 auto entries = net_log_.GetEntries();
Helen Li830d5708d62018-08-22 16:29:182972 for (const auto& entry : entries) {
2973 EXPECT_NE(entry.type,
2974 NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE);
2975 }
[email protected]316c1e5e2012-09-12 15:17:442976 }
2977
2978 // Try to set-up another cookie and update the previous cookie.
2979 {
2980 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072981 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442982 TestDelegate d;
2983 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:072984 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552985 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162986 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192987 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442988
Wez2a31b222018-06-07 22:07:152989 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442990
2991 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2992 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
Eric Roman79cc7552019-07-19 02:17:542993 auto entries = net_log_.GetEntries();
Helen Li830d5708d62018-08-22 16:29:182994 ExpectLogContainsSomewhereAfter(
2995 entries, 0, NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE,
2996 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442997 }
2998
2999 // Verify the cookies weren't saved or updated.
3000 {
3001 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073002 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443003 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073004 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163005 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3006 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193007 req->Start();
Wez2a31b222018-06-07 22:07:153008 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443009
3010 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
3011 == std::string::npos);
3012 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
3013 != std::string::npos);
3014
3015 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3016 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3017 }
3018}
3019
3020TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:393021 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443022 ASSERT_TRUE(test_server.Start());
3023
3024 // Set up an empty cookie.
3025 {
3026 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073027 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443028 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073029 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163030 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
3031 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193032 req->Start();
Wez2a31b222018-06-07 22:07:153033 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443034
3035 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3036 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3037 EXPECT_EQ(0, network_delegate.set_cookie_count());
3038 }
3039}
3040
3041TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393042 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443043 ASSERT_TRUE(test_server.Start());
3044
3045 // Set up a cookie.
3046 {
3047 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073048 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443049 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073050 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553051 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163052 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193053 req->Start();
Wez2a31b222018-06-07 22:07:153054 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443055
3056 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3057 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3058 }
3059
3060 // Verify that the cookie is set.
3061 {
3062 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073063 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443064 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073065 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163066 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3067 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193068 req->Start();
Wez2a31b222018-06-07 22:07:153069 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443070
3071 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
3072 != std::string::npos);
3073
3074 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3075 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3076 }
3077
3078 // Verify that the cookie isn't sent.
3079 {
3080 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073081 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443082 TestDelegate d;
3083 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:073084 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163085 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3086 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193087 req->Start();
Wez2a31b222018-06-07 22:07:153088 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443089
3090 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
3091 == std::string::npos);
3092
[email protected]22e045f2013-09-20 03:54:033093 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:443094 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3095 }
3096}
3097
3098TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:393099 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443100 ASSERT_TRUE(test_server.Start());
3101
3102 // Set up a cookie.
3103 {
3104 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073105 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443106 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073107 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553108 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:163109 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193110 req->Start();
Wez2a31b222018-06-07 22:07:153111 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443112
3113 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3114 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3115 }
3116
3117 // Try to set-up another cookie and update the previous cookie.
3118 {
3119 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073120 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443121 TestDelegate d;
3122 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:073123 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:553124 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:163125 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193126 req->Start();
[email protected]316c1e5e2012-09-12 15:17:443127
Wez2a31b222018-06-07 22:07:153128 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443129
3130 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3131 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
3132 }
3133
3134 // Verify the cookies weren't saved or updated.
3135 {
3136 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073137 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:443138 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073139 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163140 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3141 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193142 req->Start();
Wez2a31b222018-06-07 22:07:153143 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443144
3145 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
3146 == std::string::npos);
3147 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
3148 != std::string::npos);
3149
3150 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3151 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3152 }
3153}
3154
mkwstc5fa7762016-03-28 09:28:233155TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:393156 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:263157 ASSERT_TRUE(test_server.Start());
3158
mkwst202534e32016-01-15 16:07:153159 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073160 default_context().set_network_delegate(&network_delegate);
mkwst202534e32016-01-15 16:07:153161
mkwstf71d0bd2016-03-21 14:15:243162 const std::string kHost = "example.test";
3163 const std::string kSubHost = "subdomain.example.test";
3164 const std::string kCrossHost = "cross-origin.test";
3165
3166 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:263167 {
mkwst3f3daac2015-02-26 20:15:263168 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073169 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
mkwstf71d0bd2016-03-21 14:15:243170 test_server.GetURL(kHost,
3171 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
3172 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:163173 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Maks Orlovich8a3e4132019-04-23 16:59:243174 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3175 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263176 req->Start();
Wez2a31b222018-06-07 22:07:153177 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263178 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3179 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:243180 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:263181 }
3182
mkwstf71d0bd2016-03-21 14:15:243183 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:263184 {
mkwst3f3daac2015-02-26 20:15:263185 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073186 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163187 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3188 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463189 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463190 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263191 req->Start();
Wez2a31b222018-06-07 22:07:153192 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263193
mkwstf71d0bd2016-03-21 14:15:243194 EXPECT_NE(std::string::npos,
3195 d.data_received().find("StrictSameSiteCookie=1"));
3196 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263197 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3198 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3199 }
3200
clamyfd58ca072016-12-21 17:18:323201 // Verify that both cookies are sent when the request has no initiator (can
3202 // happen for main frame browser-initiated navigations).
3203 {
3204 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073205 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163206 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3207 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463208 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:323209 req->Start();
Wez2a31b222018-06-07 22:07:153210 d.RunUntilComplete();
clamyfd58ca072016-12-21 17:18:323211
3212 EXPECT_NE(std::string::npos,
3213 d.data_received().find("StrictSameSiteCookie=1"));
3214 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3215 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3216 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3217 }
3218
mkwstf71d0bd2016-03-21 14:15:243219 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263220 {
mkwst3f3daac2015-02-26 20:15:263221 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073222 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163223 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3224 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463225 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463226 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153227 req->Start();
Wez2a31b222018-06-07 22:07:153228 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153229
mkwstf71d0bd2016-03-21 14:15:243230 EXPECT_NE(std::string::npos,
3231 d.data_received().find("StrictSameSiteCookie=1"));
3232 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153233 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3234 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3235 }
3236
mkwstf71d0bd2016-03-21 14:15:243237 // Verify that neither cookie is not sent for cross-site requests.
3238 {
3239 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073240 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163241 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3242 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463243 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463244 req->set_initiator(
3245 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243246 req->Start();
Wez2a31b222018-06-07 22:07:153247 d.RunUntilComplete();
mkwstf71d0bd2016-03-21 14:15:243248
3249 EXPECT_EQ(std::string::npos,
3250 d.data_received().find("StrictSameSiteCookie=1"));
3251 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3252 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3253 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3254 }
3255
3256 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153257 // method is "safe".
3258 {
3259 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073260 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163261 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3262 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463263 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463264 req->set_initiator(
3265 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243266 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153267 req->Start();
Wez2a31b222018-06-07 22:07:153268 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153269
mkwstf71d0bd2016-03-21 14:15:243270 EXPECT_EQ(std::string::npos,
3271 d.data_received().find("StrictSameSiteCookie=1"));
3272 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153273 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3274 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3275 }
3276
mkwstf71d0bd2016-03-21 14:15:243277 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153278 // method is unsafe (e.g. POST).
3279 {
3280 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073281 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163282 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3283 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463284 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463285 req->set_initiator(
3286 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153287 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263288 req->Start();
Wez2a31b222018-06-07 22:07:153289 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263290
mkwstf71d0bd2016-03-21 14:15:243291 EXPECT_EQ(std::string::npos,
3292 d.data_received().find("StrictSameSiteCookie=1"));
3293 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263294 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3295 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3296 }
3297}
3298
Maks Orlovich8a3e4132019-04-23 16:59:243299TEST_F(URLRequestTest, SettingSameSiteCookies) {
3300 HttpTestServer test_server;
3301 ASSERT_TRUE(test_server.Start());
3302
3303 TestNetworkDelegate network_delegate;
3304 default_context().set_network_delegate(&network_delegate);
3305
3306 const std::string kHost = "example.test";
3307 const std::string kSubHost = "subdomain.example.test";
3308 const std::string kCrossHost = "cross-origin.test";
3309
3310 int expected_cookies = 0;
3311
3312 {
3313 TestDelegate d;
3314 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3315 test_server.GetURL(kHost,
Lily Chenf5732c82019-08-01 00:01:543316 "/set-cookie?Strict1=1;SameSite=Strict&"
3317 "Lax1=1;SameSite=Lax"),
Maks Orlovich8a3e4132019-04-23 16:59:243318 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3319 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3320 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
3321
3322 // 'SameSite' cookies are settable from strict same-site contexts
3323 // (same-origin site_for_cookies, same-origin initiator), so this request
Lily Chenf5732c82019-08-01 00:01:543324 // should result in two cookies being set.
Maks Orlovich8a3e4132019-04-23 16:59:243325 expected_cookies += 2;
3326
3327 req->Start();
3328 d.RunUntilComplete();
Lily Chenf5732c82019-08-01 00:01:543329 EXPECT_EQ(expected_cookies,
3330 static_cast<int>(GetAllCookies(&default_context()).size()));
Maks Orlovich8a3e4132019-04-23 16:59:243331 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3332 }
3333
3334 {
3335 TestDelegate d;
3336 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3337 test_server.GetURL(kHost,
Lily Chenf5732c82019-08-01 00:01:543338 "/set-cookie?Strict2=1;SameSite=Strict&"
3339 "Lax2=1;SameSite=Lax"),
Maks Orlovich8a3e4132019-04-23 16:59:243340 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3341 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
3342 req->set_initiator(
3343 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3344
3345 // 'SameSite' cookies are settable from lax same-site contexts (same-origin
3346 // site_for_cookies, cross-site initiator), so this request should result in
Lily Chenf5732c82019-08-01 00:01:543347 // two cookies being set.
Maks Orlovich8a3e4132019-04-23 16:59:243348 expected_cookies += 2;
3349
3350 req->Start();
3351 d.RunUntilComplete();
Lily Chenf5732c82019-08-01 00:01:543352 EXPECT_EQ(expected_cookies,
3353 static_cast<int>(GetAllCookies(&default_context()).size()));
Maks Orlovich8a3e4132019-04-23 16:59:243354 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3355 }
3356
3357 {
3358 TestDelegate d;
3359 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3360 test_server.GetURL(kHost,
Lily Chenf5732c82019-08-01 00:01:543361 "/set-cookie?Strict3=1;SameSite=Strict&"
3362 "Lax3=1;SameSite=Lax"),
Maks Orlovich8a3e4132019-04-23 16:59:243363 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3364 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
3365 req->set_initiator(
3366 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3367
3368 // 'SameSite' cookies are settable from lax same-site contexts (same-site
3369 // site_for_cookies, cross-site initiator), so this request should result in
Lily Chenf5732c82019-08-01 00:01:543370 // two cookies being set.
Maks Orlovich8a3e4132019-04-23 16:59:243371 expected_cookies += 2;
3372
3373 req->Start();
3374 d.RunUntilComplete();
Lily Chenf5732c82019-08-01 00:01:543375 EXPECT_EQ(expected_cookies,
3376 static_cast<int>(GetAllCookies(&default_context()).size()));
Maks Orlovich8a3e4132019-04-23 16:59:243377 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3378 }
3379
3380 {
3381 TestDelegate d;
3382 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3383 test_server.GetURL(kHost,
Lily Chenf5732c82019-08-01 00:01:543384 "/set-cookie?Strict4=1;SameSite=Strict&"
3385 "Lax4=1;SameSite=Lax"),
Maks Orlovich8a3e4132019-04-23 16:59:243386 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3387 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
3388
3389 // 'SameSite' cookies are settable from strict same-site contexts (same-site
3390 // site_for_cookies, no initiator), so this request should result in two
Lily Chenf5732c82019-08-01 00:01:543391 // cookies being set.
Maks Orlovich8a3e4132019-04-23 16:59:243392 expected_cookies += 2;
3393
3394 req->Start();
3395 d.RunUntilComplete();
Lily Chenf5732c82019-08-01 00:01:543396 EXPECT_EQ(expected_cookies,
3397 static_cast<int>(GetAllCookies(&default_context()).size()));
Maks Orlovich8a3e4132019-04-23 16:59:243398 EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count());
3399 }
3400
3401 {
3402 TestDelegate d;
3403 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
3404 test_server.GetURL(kHost,
Lily Chenf5732c82019-08-01 00:01:543405 "/set-cookie?Strict5=1;SameSite=Strict&"
3406 "Lax5=1;SameSite=Lax"),
Maks Orlovich8a3e4132019-04-23 16:59:243407 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3408 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
3409 req->set_initiator(
3410 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
3411
3412 // 'SameSite' cookies are not settable from cross-site contexts, so this
Lily Chenf5732c82019-08-01 00:01:543413 // should not result in any new cookies being set.
Maks Orlovich8a3e4132019-04-23 16:59:243414 expected_cookies += 0;
3415
3416 req->Start();
3417 d.RunUntilComplete();
Lily Chenf5732c82019-08-01 00:01:543418 // This counts the number of cookies actually set.
3419 EXPECT_EQ(expected_cookies,
3420 static_cast<int>(GetAllCookies(&default_context()).size()));
3421 // This counts the number of successful calls to CanSetCookie() when
3422 // attempting to set a cookie. The two cookies above were created and
3423 // attempted to be set, and were not rejected by the NetworkDelegate, so the
3424 // count here is 2 more than the number of cookies actually set.
3425 EXPECT_EQ(expected_cookies + 2, network_delegate.set_cookie_count());
Maks Orlovich8a3e4132019-04-23 16:59:243426 }
3427}
3428
estark557a5eb82015-12-01 22:57:103429// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363430TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553431 EmbeddedTestServer http_server;
3432 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363433 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553434 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3435 https_server.AddDefaultHandlers(
3436 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3437 ASSERT_TRUE(http_server.Start());
3438 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363439
estarkb15166b2015-12-18 16:56:383440 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363441 TestURLRequestContext context(true);
3442 context.set_network_delegate(&network_delegate);
3443 context.Init();
3444
estarkb15166b2015-12-18 16:56:383445 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363446 {
3447 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363448 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103449 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163450 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363451 req->Start();
Wez2a31b222018-06-07 22:07:153452 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363453 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3454 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3455 }
3456
3457 // Verify that the cookie is not set.
3458 {
3459 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363460 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163461 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3462 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363463 req->Start();
Wez2a31b222018-06-07 22:07:153464 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363465
jww79aceda2015-12-07 01:56:343466 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3467 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363468 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3469 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3470 }
3471}
3472
estarkb15166b2015-12-18 16:56:383473TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553474 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3475 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363476 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553477 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363478
3479 TestNetworkDelegate network_delegate;
3480 TestURLRequestContext context(true);
3481 context.set_network_delegate(&network_delegate);
3482 context.Init();
3483
estarkb15166b2015-12-18 16:56:383484 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363485 {
3486 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163487 std::unique_ptr<URLRequest> req(context.CreateRequest(
3488 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3489 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363490 req->Start();
Wez2a31b222018-06-07 22:07:153491 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583492 EXPECT_EQ(0, network_delegate.set_cookie_count());
estarkcd39c11f2015-10-19 19:46:363493 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3494 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3495 }
3496
3497 // Verify that the cookie is not set.
3498 {
3499 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363500 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163501 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3502 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363503 req->Start();
Wez2a31b222018-06-07 22:07:153504 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363505
jww79aceda2015-12-07 01:56:343506 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363507 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3508 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3509 }
3510}
3511
estarkb15166b2015-12-18 16:56:383512TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553513 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3514 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363515 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553516 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363517
estarkb15166b2015-12-18 16:56:383518 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363519 TestURLRequestContext context(true);
3520 context.set_network_delegate(&network_delegate);
3521 context.Init();
3522
estarkb15166b2015-12-18 16:56:383523 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363524 {
3525 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363526 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103527 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163528 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363529 req->Start();
Wez2a31b222018-06-07 22:07:153530 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363531 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3532 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3533 }
3534
3535 // Verify that the cookie is set.
3536 {
3537 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363538 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163539 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3540 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363541 req->Start();
Wez2a31b222018-06-07 22:07:153542 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363543
jww79aceda2015-12-07 01:56:343544 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3545 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3546 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3547 }
3548}
3549
3550// Tests that secure cookies can't be set on non-secure origins if strict secure
3551// cookies are enabled.
3552TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3553 EmbeddedTestServer http_server;
3554 http_server.AddDefaultHandlers(
3555 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3556 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3557 https_server.AddDefaultHandlers(
3558 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3559 ASSERT_TRUE(http_server.Start());
3560 ASSERT_TRUE(https_server.Start());
3561
Matt Menkebe9b6eb2018-10-18 12:11:443562 TestNetworkDelegate network_delegate;
jww79aceda2015-12-07 01:56:343563 TestURLRequestContext context(true);
3564 context.set_network_delegate(&network_delegate);
3565 context.Init();
3566
3567 // Try to set a Secure cookie, with experimental features enabled.
3568 {
3569 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363570 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343571 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163572 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343573 req->Start();
Wez2a31b222018-06-07 22:07:153574 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343575 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3576 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3577 }
3578
3579 // Verify that the cookie is not set.
3580 {
3581 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363582 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163583 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3584 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343585 req->Start();
Wez2a31b222018-06-07 22:07:153586 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343587
3588 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3589 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3590 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3591 }
3592}
3593
Thiemo Nagel0793b9c532018-04-18 16:57:583594// The parameter is true for same-site and false for cross-site requests.
3595class URLRequestTestParameterizedSameSite
3596 : public URLRequestTest,
3597 public ::testing::WithParamInterface<bool> {
3598 protected:
3599 URLRequestTestParameterizedSameSite() {
3600 auto params = std::make_unique<HttpNetworkSession::Params>();
3601 params->ignore_certificate_errors = true;
3602 context_.set_http_network_session_params(std::move(params));
3603 context_.set_network_delegate(&network_delegate_);
3604 https_server_.AddDefaultHandlers(
3605 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3606 EXPECT_TRUE(https_server_.Start());
3607 }
3608
3609 // To be called after configuration of |context_| has been finalized.
3610 void InitContext() { context_.Init(); }
3611
3612 const std::string kHost_ = "example.test";
3613 const std::string kCrossHost_ = "cross-site.test";
3614 TestURLRequestContext context_{true};
3615 TestNetworkDelegate network_delegate_;
3616 base::HistogramTester histograms_;
3617 EmbeddedTestServer https_server_{EmbeddedTestServer::TYPE_HTTPS};
3618};
3619
Victor Costan8fb98f6f2019-02-01 17:08:293620INSTANTIATE_TEST_SUITE_P(URLRequestTest,
3621 URLRequestTestParameterizedSameSite,
3622 ::testing::Bool());
Thiemo Nagel0793b9c532018-04-18 16:57:583623
3624TEST_P(URLRequestTestParameterizedSameSite, CookieAgeMetrics) {
3625 const bool same_site = GetParam();
3626 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3627 InitContext();
3628
Mike West86149882017-07-28 10:41:493629 EmbeddedTestServer http_server;
3630 http_server.AddDefaultHandlers(
3631 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
Thiemo Nagel23e0b322018-04-18 12:46:543632 ASSERT_TRUE(http_server.Start());
3633
Thiemo Nagel0793b9c532018-04-18 16:57:583634 // Set two test cookies.
Thiemo Nagel23e0b322018-04-18 12:46:543635 {
3636 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583637 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3638 http_server.GetURL(kHost_, "/set-cookie?cookie=value&cookie2=value2"),
Thiemo Nagel23e0b322018-04-18 12:46:543639 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3640 req->Start();
Wez2a31b222018-06-07 22:07:153641 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583642 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3643 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3644 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3645 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3646 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 0);
3647 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3648 0);
3649 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3650 0);
3651 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3652 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 0);
Thiemo Nagel23e0b322018-04-18 12:46:543653 }
3654
Thiemo Nagel0793b9c532018-04-18 16:57:583655 // Make a secure request.
Thiemo Nagel23e0b322018-04-18 12:46:543656 {
3657 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583658 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3659 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3660 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3661 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103662 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583663 url::Origin::Create(https_server_.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103664 req->Start();
Wez2a31b222018-06-07 22:07:153665 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583666 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3667 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3668 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3669 !same_site);
3670 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3671 same_site);
3672 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3673 0);
3674 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3675 0);
3676 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3677 same_site ? 0 : 2);
3678 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3679 same_site ? 2 : 0);
3680 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3681 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
Mohsen Izadiad6f7592018-04-18 15:57:103682 }
3683
Thiemo Nagel0793b9c532018-04-18 16:57:583684 // Make a non-secure request.
Mohsen Izadiad6f7592018-04-18 15:57:103685 {
3686 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583687 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3688 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
Mohsen Izadiad6f7592018-04-18 15:57:103689 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel0793b9c532018-04-18 16:57:583690 req->set_site_for_cookies(http_server.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103691 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583692 url::Origin::Create(http_server.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103693 req->Start();
Wez2a31b222018-06-07 22:07:153694 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583695 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest",
3696 !same_site);
3697 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest",
3698 same_site);
3699 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3700 !same_site);
3701 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3702 same_site);
3703 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3704 same_site ? 0 : 2);
3705 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3706 same_site ? 2 : 0);
3707 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3708 same_site ? 0 : 2);
3709 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3710 same_site ? 2 : 0);
3711 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3712 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
3713 }
3714}
3715
3716// Cookies with secure attribute (no HSTS) --> k1pSecureAttribute
3717TEST_P(URLRequestTestParameterizedSameSite,
3718 CookieNetworkSecurityMetricSecureAttribute) {
3719 const bool same_site = GetParam();
3720 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3721 InitContext();
3722
3723 // Set cookies.
3724 {
3725 TestDelegate d;
3726 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3727 https_server_.GetURL(kHost_,
3728 "/set-cookie?session-cookie=value;Secure&"
3729 "longlived-cookie=value;Secure;domain=" +
3730 kHost_ + ";Max-Age=360000"),
3731 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3732 req->Start();
Wez2a31b222018-06-07 22:07:153733 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583734 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3735 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3736 }
3737
3738 // Verify that the cookies fall into the correct metrics bucket.
3739 {
3740 TestDelegate d;
3741 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3742 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3743 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3744 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3745 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3746 req->Start();
Wez2a31b222018-06-07 22:07:153747 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583748 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3749 // Static cast of boolean required for MSVC 1911.
3750 histograms_.ExpectBucketCount(
3751 "Cookie.NetworkSecurity",
3752 static_cast<int>(CookieNetworkSecurity::k1pSecureAttribute) |
3753 static_cast<int>(!same_site),
3754 2);
3755 }
3756}
3757
3758// Short-lived host cookie --> k1pHSTSHostCookie
3759TEST_P(URLRequestTestParameterizedSameSite,
3760 CookieNetworkSecurityMetricShortlivedHostCookie) {
3761 const bool same_site = GetParam();
3762 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3763
3764 TransportSecurityState transport_security_state;
3765 transport_security_state.AddHSTS(
3766 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3767 false /* include_subdomains */);
3768 context_.set_transport_security_state(&transport_security_state);
3769 InitContext();
3770
3771 // Set cookie.
3772 {
3773 TestDelegate d;
3774 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3775 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;Max-Age=3600"),
3776 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3777 req->Start();
Wez2a31b222018-06-07 22:07:153778 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583779 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3780 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3781 }
3782
3783 // Verify that the cookie falls into the correct metrics bucket.
3784 {
3785 TestDelegate d;
3786 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3787 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3788 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3789 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3790 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3791 req->Start();
Wez2a31b222018-06-07 22:07:153792 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583793 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3794 // Static cast of boolean required for MSVC 1911.
3795 histograms_.ExpectBucketCount(
3796 "Cookie.NetworkSecurity",
3797 static_cast<int>(CookieNetworkSecurity::k1pHSTSHostCookie) |
3798 static_cast<int>(!same_site),
3799 1);
3800 }
3801}
3802
3803// Long-lived (either due to expiry or due to being a session cookie) host
3804// cookies --> k1pExpiringHSTSHostCookie
3805TEST_P(URLRequestTestParameterizedSameSite,
3806 CookieNetworkSecurityMetricLonglivedHostCookie) {
3807 const bool same_site = GetParam();
3808 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3809
3810 TransportSecurityState transport_security_state;
3811 transport_security_state.AddHSTS(
3812 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3813 false /* include_subdomains */);
3814 context_.set_transport_security_state(&transport_security_state);
3815 InitContext();
3816
3817 // Set cookies.
3818 {
3819 TestDelegate d;
3820 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3821 https_server_.GetURL(kHost_,
3822 "/set-cookie?session-cookie=value&"
3823 "longlived-cookie=value;Max-Age=360000"),
3824 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3825 req->Start();
Wez2a31b222018-06-07 22:07:153826 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583827 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3828 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3829 }
3830
3831 // Verify that the cookies fall into the correct metrics bucket.
3832 {
3833 TestDelegate d;
3834 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3835 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3836 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3837 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3838 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3839 req->Start();
Wez2a31b222018-06-07 22:07:153840 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583841 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3842 // Static cast of boolean required for MSVC 1911.
3843 histograms_.ExpectBucketCount(
3844 "Cookie.NetworkSecurity",
3845 static_cast<int>(CookieNetworkSecurity::k1pExpiringHSTSHostCookie) |
3846 static_cast<int>(!same_site),
3847 2);
3848 }
3849}
3850
3851// Domain cookie with HSTS subdomains with cookie expiry before HSTS expiry -->
3852// k1pHSTSSubdomainsIncluded
3853TEST_P(URLRequestTestParameterizedSameSite,
3854 CookieNetworkSecurityMetricShortlivedDomainCookie) {
3855 const bool same_site = GetParam();
3856 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3857
3858 TransportSecurityState transport_security_state;
3859 transport_security_state.AddHSTS(
3860 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3861 true /* include_subdomains */);
3862 context_.set_transport_security_state(&transport_security_state);
3863 InitContext();
3864
3865 // Set cookie.
3866 {
3867 TestDelegate d;
3868 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3869 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3870 kHost_ + ";Max-Age=3600"),
3871 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3872 req->Start();
Wez2a31b222018-06-07 22:07:153873 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583874 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3875 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3876 }
3877
3878 // Verify that the cookie falls into the correct metrics bucket.
3879 {
3880 TestDelegate d;
3881 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3882 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3883 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3884 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3885 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3886 req->Start();
Wez2a31b222018-06-07 22:07:153887 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583888 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3889 // Static cast of boolean required for MSVC 1911.
3890 histograms_.ExpectBucketCount(
3891 "Cookie.NetworkSecurity",
3892 static_cast<int>(CookieNetworkSecurity::k1pHSTSSubdomainsIncluded) |
3893 static_cast<int>(!same_site),
3894 1);
3895 }
3896}
3897
3898// Long-lived (either due to expiry or due to being a session cookie) domain
3899// cookies with HSTS subdomains --> k1pExpiringHSTSSubdomainsIncluded
3900TEST_P(URLRequestTestParameterizedSameSite,
3901 CookieNetworkSecurityMetricLonglivedDomainCookie) {
3902 const bool same_site = GetParam();
3903 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3904
3905 TransportSecurityState transport_security_state;
3906 transport_security_state.AddHSTS(
3907 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3908 true /* include_subdomains */);
3909 context_.set_transport_security_state(&transport_security_state);
3910 InitContext();
3911
3912 // Set cookies.
3913 {
3914 TestDelegate d;
3915 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3916 https_server_.GetURL(
3917 kHost_, "/set-cookie?session-cookie=value;domain=" + kHost_ + "&" +
3918 "longlived-cookie=value;domain=" + kHost_ +
3919 ";Max-Age=360000"),
3920 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3921 req->Start();
Wez2a31b222018-06-07 22:07:153922 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583923 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3924 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3925 }
3926
3927 // Verify that the cookies fall into the correct metrics bucket.
3928 {
3929 TestDelegate d;
3930 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3931 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3932 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3933 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3934 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3935 req->Start();
Wez2a31b222018-06-07 22:07:153936 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583937 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3938 // Static cast of boolean required for MSVC 1911.
3939 histograms_.ExpectBucketCount(
3940 "Cookie.NetworkSecurity",
3941 static_cast<int>(
3942 CookieNetworkSecurity::k1pExpiringHSTSSubdomainsIncluded) |
3943 static_cast<int>(!same_site),
3944 2);
3945 }
3946}
3947
3948// Domain cookie with HSTS subdomains not included --> k1pHSTSSpoofable
3949TEST_P(URLRequestTestParameterizedSameSite,
3950 CookieNetworkSecurityMetricSpoofableDomainCookie) {
3951 const bool same_site = GetParam();
3952 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3953
3954 TransportSecurityState transport_security_state;
3955 transport_security_state.AddHSTS(
3956 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3957 false /* include_subdomains */);
3958 context_.set_transport_security_state(&transport_security_state);
3959 InitContext();
3960
3961 // Set cookie.
3962 {
3963 TestDelegate d;
3964 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3965 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3966 kHost_ + ";Max-Age=3600"),
3967 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3968 req->Start();
Wez2a31b222018-06-07 22:07:153969 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583970 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3971 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3972 }
3973
3974 // Verify that the cookie falls into the correct metrics bucket.
3975 {
3976 TestDelegate d;
3977 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3978 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3979 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3980 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3981 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3982 req->Start();
Wez2a31b222018-06-07 22:07:153983 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583984 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3985 // Static cast of boolean required for MSVC 1911.
3986 histograms_.ExpectBucketCount(
3987 "Cookie.NetworkSecurity",
3988 static_cast<int>(CookieNetworkSecurity::k1pHSTSSpoofable) |
3989 static_cast<int>(!same_site),
3990 1);
3991 }
3992}
3993
3994// Cookie without HSTS --> k1p(Non)SecureConnection
3995TEST_P(URLRequestTestParameterizedSameSite, CookieNetworkSecurityMetricNoHSTS) {
3996 const bool same_site = GetParam();
3997 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3998 InitContext();
3999
4000 EmbeddedTestServer http_server;
4001 http_server.AddDefaultHandlers(
4002 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
4003 ASSERT_TRUE(http_server.Start());
4004
4005 // Set cookies.
4006 {
4007 TestDelegate d;
4008 std::unique_ptr<URLRequest> req(context_.CreateRequest(
4009 https_server_.GetURL(kHost_,
4010 "/set-cookie?cookie=value;domain=" + kHost_ +
4011 ";Max-Age=3600&host-cookie=value"),
4012 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4013 req->Start();
Wez2a31b222018-06-07 22:07:154014 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:584015 ASSERT_EQ(2, network_delegate_.set_cookie_count());
4016 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
4017 }
4018
4019 // Verify that the cookie falls into the correct metrics bucket.
4020 {
4021 TestDelegate d;
4022 std::unique_ptr<URLRequest> req(context_.CreateRequest(
4023 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
4024 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4025 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
4026 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
4027 req->Start();
Wez2a31b222018-06-07 22:07:154028 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:584029 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
4030 // Static cast of boolean required for MSVC 1911.
4031 histograms_.ExpectBucketCount(
4032 "Cookie.NetworkSecurity",
4033 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
4034 static_cast<int>(!same_site),
4035 2);
4036 }
4037
4038 // Verify that the cookie falls into the correct metrics bucket.
4039 {
4040 TestDelegate d;
4041 std::unique_ptr<URLRequest> req(context_.CreateRequest(
4042 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4043 TRAFFIC_ANNOTATION_FOR_TESTS));
4044 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
4045 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
4046 req->Start();
Wez2a31b222018-06-07 22:07:154047 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:584048 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 4);
4049 // Static cast of boolean required for MSVC 1911.
4050 histograms_.ExpectBucketCount(
4051 "Cookie.NetworkSecurity",
4052 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
4053 static_cast<int>(!same_site),
4054 2);
4055 // Static cast of boolean required for MSVC 1911.
4056 histograms_.ExpectBucketCount(
4057 "Cookie.NetworkSecurity",
4058 static_cast<int>(CookieNetworkSecurity::k1pNonsecureConnection) |
4059 static_cast<int>(!same_site),
4060 2);
Mike West86149882017-07-28 10:41:494061 }
4062}
4063
[email protected]5095cd72012-11-01 10:29:164064// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
4065// value for the |fixed_date| argument given to the constructor.
4066class FixedDateNetworkDelegate : public TestNetworkDelegate {
4067 public:
4068 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
4069 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:274070 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:164071
[email protected]cba24642014-08-15 20:49:594072 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:204073 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:594074 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:204075 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:594076 const HttpResponseHeaders* original_response_headers,
4077 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134078 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:164079
4080 private:
4081 std::string fixed_date_;
4082
4083 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
4084};
4085
4086int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:594087 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:204088 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:594089 const HttpResponseHeaders* original_response_headers,
4090 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:164091 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:594092 HttpResponseHeaders* new_response_headers =
4093 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:164094
4095 new_response_headers->RemoveHeader("Date");
4096 new_response_headers->AddHeader("Date: " + fixed_date_);
4097
4098 *override_response_headers = new_response_headers;
David Benjamind1f287bf2018-06-12 01:57:204099 return TestNetworkDelegate::OnHeadersReceived(
4100 request, std::move(callback), original_response_headers,
4101 override_response_headers, allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:164102}
4103
4104// Test that cookie expiration times are adjusted for server/client clock
4105// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
4106// headers by defaulting to GMT. (crbug.com/135131)
4107TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:394108 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:164109 ASSERT_TRUE(test_server.Start());
4110
4111 // Set up an expired cookie.
4112 {
4113 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074114 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164115 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074116 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194117 test_server.GetURL(
tommycli59a63432015-11-06 00:10:554118 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:164119 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194120 req->Start();
Wez2a31b222018-06-07 22:07:154121 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164122 }
4123 // Verify that the cookie is not set.
4124 {
4125 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074126 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164127 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074128 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164129 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4130 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194131 req->Start();
Wez2a31b222018-06-07 22:07:154132 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164133
4134 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
4135 }
4136 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
4137 {
4138 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
Ryan Sleevib8449e02018-07-15 04:31:074139 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164140 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074141 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194142 test_server.GetURL(
tommycli59a63432015-11-06 00:10:554143 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:164144 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194145 req->Start();
Wez2a31b222018-06-07 22:07:154146 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164147 }
4148 // Verify that the cookie is set.
4149 {
4150 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:074151 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:164152 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074153 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164154 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
4155 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194156 req->Start();
Wez2a31b222018-06-07 22:07:154157 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:164158
4159 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
4160 }
4161}
4162
4163
[email protected]316c1e5e2012-09-12 15:17:444164// Check that it is impossible to change the referrer in the extra headers of
4165// an URLRequest.
4166TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:394167 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:444168 ASSERT_TRUE(test_server.Start());
4169
4170 // If extra headers contain referer and the request contains a referer,
4171 // only the latter shall be respected.
4172 {
4173 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074174 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164175 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4176 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194177 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:444178
4179 HttpRequestHeaders headers;
4180 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194181 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:444182
[email protected]f7022f32014-08-21 16:32:194183 req->Start();
Wez2a31b222018-06-07 22:07:154184 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444185
4186 EXPECT_EQ("http://foo.com/", d.data_received());
4187 }
4188
4189 // If extra headers contain a referer but the request does not, no referer
4190 // shall be sent in the header.
4191 {
4192 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074193 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164194 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
4195 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:444196
4197 HttpRequestHeaders headers;
4198 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:194199 req->SetExtraRequestHeaders(headers);
4200 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:444201
[email protected]f7022f32014-08-21 16:32:194202 req->Start();
Wez2a31b222018-06-07 22:07:154203 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:444204
4205 EXPECT_EQ("None", d.data_received());
4206 }
4207}
4208
[email protected]b89290212009-08-14 22:37:354209class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:114210 public:
mmenke9f2ec60c2015-06-01 20:59:474211 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:114212
[email protected]b89290212009-08-14 22:37:354213 protected:
[email protected]21184962011-10-26 00:50:304214 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
4215 // |request_method| is the method to use for the initial request.
4216 // |redirect_method| is the method that is expected to be used for the second
4217 // request, after redirection.
4218 // If |include_data| is true, data is uploaded with the request. The
4219 // response body is expected to match it exactly, if and only if
4220 // |request_method| == |redirect_method|.
4221 void HTTPRedirectMethodTest(const GURL& redirect_url,
4222 const std::string& request_method,
4223 const std::string& redirect_method,
4224 bool include_data) {
4225 static const char kData[] = "hello world";
4226 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074227 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164228 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194229 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:304230 if (include_data) {
mmenkecbc2b712014-10-09 20:29:074231 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:304232 HttpRequestHeaders headers;
4233 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244234 base::NumberToString(base::size(kData) - 1));
svaldez5b3a8972015-10-09 23:23:544235 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:194236 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:304237 }
[email protected]f7022f32014-08-21 16:32:194238 req->Start();
Wez2a31b222018-06-07 22:07:154239 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194240 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:504241 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:304242 if (include_data) {
4243 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:544244 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4245 HttpRequestHeaders::kContentLength));
4246 EXPECT_TRUE(req->extra_request_headers().HasHeader(
4247 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304248 EXPECT_EQ(kData, d.data_received());
4249 } else {
svaldez5b3a8972015-10-09 23:23:544250 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4251 HttpRequestHeaders::kContentLength));
4252 EXPECT_FALSE(req->extra_request_headers().HasHeader(
4253 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:304254 EXPECT_NE(kData, d.data_received());
4255 }
4256 }
4257 if (HasFailure())
4258 LOG(WARNING) << "Request method was: " << request_method;
4259 }
4260
Alex Clarke1e08882b32017-10-06 14:22:404261 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
4262 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:514263 // |request_method| is the method to use for the initial request.
4264 // |redirect_method| is the method that is expected to be used for the second
4265 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:404266 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:514267 // redirection. If empty, expects that there will be no Origin header.
4268 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
4269 const std::string& request_method,
4270 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:404271 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:514272 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074273 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164274 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:514275 req->set_method(request_method);
4276 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
4277 redirect_url.GetOrigin().spec(), false);
4278 req->Start();
4279
Wez2a31b222018-06-07 22:07:154280 d.RunUntilComplete();
jww5fe460ff2015-03-28 00:22:514281
4282 EXPECT_EQ(redirect_method, req->method());
4283 // Note that there is no check for request success here because, for
4284 // purposes of testing, the request very well may fail. For example, if the
4285 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
4286 // origin, there is not an HTTPS server in this unit test framework, so the
4287 // request would fail. However, that's fine, as long as the request headers
4288 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:404289 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:514290 EXPECT_FALSE(
4291 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
4292 } else {
4293 std::string origin_header;
4294 EXPECT_TRUE(req->extra_request_headers().GetHeader(
4295 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:404296 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:514297 }
4298 }
4299
[email protected]762d2db2010-01-11 19:03:014300 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:014301 const int kMsgSize = 20000; // multiple of 10
4302 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:484303 char* uploadBytes = new char[kMsgSize+1];
4304 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:014305 char marker = 'a';
4306 for (int idx = 0; idx < kMsgSize/10; idx++) {
4307 memcpy(ptr, "----------", 10);
4308 ptr += 10;
4309 if (idx % 100 == 0) {
4310 ptr--;
4311 *ptr++ = marker;
4312 if (++marker > 'z')
4313 marker = 'a';
4314 }
4315 }
4316 uploadBytes[kMsgSize] = '\0';
4317
[email protected]762d2db2010-01-11 19:03:014318 for (int i = 0; i < kIterations; ++i) {
4319 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074320 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164321 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
4322 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194323 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:014324
mmenkecbc2b712014-10-09 20:29:074325 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:014326
[email protected]f7022f32014-08-21 16:32:194327 r->Start();
4328 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:014329
Wez2a31b222018-06-07 22:07:154330 d.RunUntilComplete();
[email protected]762d2db2010-01-11 19:03:014331
maksim.sisovb53724b52016-09-16 05:30:504332 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
4333 << d.request_status();
[email protected]762d2db2010-01-11 19:03:014334
4335 EXPECT_FALSE(d.received_data_before_response());
4336 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:014337 }
4338 delete[] uploadBytes;
4339 }
4340
[email protected]ede03212012-09-07 12:52:264341 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:344342 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074343 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:554344 test_server_.GetURL("/set-many-cookies?" +
Raul Tambre8c1981d2019-02-08 02:22:264345 base::NumberToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:164346 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:344347
[email protected]f7022f32014-08-21 16:32:194348 r->Start();
4349 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:344350
Wez2a31b222018-06-07 22:07:154351 d.RunUntilComplete();
[email protected]263163f2012-06-14 22:40:344352
maksim.sisovb53724b52016-09-16 05:30:504353 if (d.request_status() != OK) {
4354 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
4355 return false;
4356 }
[email protected]263163f2012-06-14 22:40:344357
maksim.sisovb53724b52016-09-16 05:30:504358 return true;
[email protected]263163f2012-06-14 22:40:344359 }
4360
David Benjamin42116f62017-11-20 21:45:394361 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:504362
tommycli59a63432015-11-06 00:10:554363 private:
David Benjamin42116f62017-11-20 21:45:394364 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:354365};
4366
tommycli59a63432015-11-06 00:10:554367namespace {
4368
danakj8522a25b2016-04-16 00:17:364369std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:554370 const test_server::HttpRequest& request) {
4371 if (request.headers.find("Host") == request.headers.end() ||
4372 request.headers.at("Host") != "www.redirect.com" ||
4373 request.method != test_server::METHOD_CONNECT) {
4374 return nullptr;
4375 }
4376
danakj8522a25b2016-04-16 00:17:364377 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554378 new test_server::BasicHttpResponse);
4379 http_response->set_code(HTTP_FOUND);
4380 http_response->AddCustomHeader("Location",
4381 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:484382 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554383}
4384
Nick Harper89bc7212018-07-31 19:07:574385} // namespace
4386
nharperb7441ef2016-01-25 23:54:144387// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114388// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:554389// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:114390// follow.
[email protected]f2f31b32013-01-16 23:24:094391TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:554392 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124393 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:554394 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114395
[email protected]ceefd7fd2012-11-29 00:36:244396 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044397 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554398 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504399
[email protected]d1ec59082009-02-11 02:48:154400 TestDelegate d;
4401 {
danakj8522a25b2016-04-16 00:17:364402 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164403 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4404 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194405 r->Start();
4406 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:154407
Wez2a31b222018-06-07 22:07:154408 d.RunUntilComplete();
[email protected]d1ec59082009-02-11 02:48:154409
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:224410 // The proxy server should be set before failure.
4411 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4412 http_test_server()->host_port_pair()),
4413 r->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:504414 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084415 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:154416 // We should not have followed the redirect.
4417 EXPECT_EQ(0, d.received_redirect_count());
4418 }
4419}
4420
[email protected]8202d0c2011-02-23 08:31:144421// This is the same as the previous test, but checks that the network delegate
4422// registers the error.
[email protected]c044616e2013-02-20 02:01:264423TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554424 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144425
[email protected]ceefd7fd2012-11-29 00:36:244426 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044427 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554428 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504429
[email protected]8202d0c2011-02-23 08:31:144430 TestDelegate d;
4431 {
danakj8522a25b2016-04-16 00:17:364432 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164433 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4434 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194435 r->Start();
4436 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144437
Wez2a31b222018-06-07 22:07:154438 d.RunUntilComplete();
[email protected]8202d0c2011-02-23 08:31:144439
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:224440 // The proxy server should be set before failure.
4441 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4442 http_test_server()->host_port_pair()),
4443 r->proxy_server());
[email protected]8202d0c2011-02-23 08:31:144444 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504445 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144446 // We should not have followed the redirect.
4447 EXPECT_EQ(0, d.received_redirect_count());
4448
4449 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014450 EXPECT_THAT(network_delegate.last_error(),
4451 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144452 }
4453}
4454
[email protected]dc5a5cf2012-09-26 02:49:304455// Tests that we can block and asynchronously return OK in various stages.
4456TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4457 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4458 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4459 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4460 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4461 };
Avi Drissman4365a4782018-12-28 19:26:244462 static const size_t blocking_stages_length = base::size(blocking_stages);
[email protected]dc5a5cf2012-09-26 02:49:304463
tommycli59a63432015-11-06 00:10:554464 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304465
4466 TestDelegate d;
4467 BlockingNetworkDelegate network_delegate(
4468 BlockingNetworkDelegate::USER_CALLBACK);
4469 network_delegate.set_block_on(
4470 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4471 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4472 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4473
4474 TestURLRequestContext context(true);
4475 context.set_network_delegate(&network_delegate);
4476 context.Init();
4477
4478 {
danakj8522a25b2016-04-16 00:17:364479 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164480 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4481 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304482
[email protected]f7022f32014-08-21 16:32:194483 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304484 for (size_t i = 0; i < blocking_stages_length; ++i) {
Wez2a31b222018-06-07 22:07:154485 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304486 EXPECT_EQ(blocking_stages[i],
4487 network_delegate.stage_blocked_for_callback());
4488 network_delegate.DoCallback(OK);
4489 }
Wez2a31b222018-06-07 22:07:154490 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194491 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504492 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304493 EXPECT_EQ(1, network_delegate.created_requests());
4494 EXPECT_EQ(0, network_delegate.destroyed_requests());
4495 }
4496 EXPECT_EQ(1, network_delegate.destroyed_requests());
4497}
4498
[email protected]4c76d7c2011-04-15 19:14:124499// Tests that the network delegate can block and cancel a request.
4500TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554501 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124502
4503 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304504 BlockingNetworkDelegate network_delegate(
4505 BlockingNetworkDelegate::AUTO_CALLBACK);
4506 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4507 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124508
[email protected]d5a4dd62012-05-23 01:41:044509 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554510 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504511
[email protected]4c76d7c2011-04-15 19:14:124512 {
rhalavatib7bd7c792017-04-27 05:25:164513 std::unique_ptr<URLRequest> r(
4514 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4515 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124516
[email protected]f7022f32014-08-21 16:32:194517 r->Start();
Wez2a31b222018-06-07 22:07:154518 d.RunUntilComplete();
[email protected]4c76d7c2011-04-15 19:14:124519
[email protected]d8fc4722014-06-13 13:17:154520 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474521 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504522 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124523 EXPECT_EQ(1, network_delegate.created_requests());
4524 EXPECT_EQ(0, network_delegate.destroyed_requests());
4525 }
4526 EXPECT_EQ(1, network_delegate.destroyed_requests());
4527}
4528
[email protected]b4438d32012-09-27 06:15:304529// Helper function for NetworkDelegateCancelRequestAsynchronously and
4530// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4531// delegate operating in |block_mode| and a request for |url|. It blocks the
4532// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4533void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4534 BlockingNetworkDelegate::Stage stage,
4535 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364536 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304537 BlockingNetworkDelegate network_delegate(block_mode);
4538 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4539 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364540
[email protected]b4438d32012-09-27 06:15:304541 TestURLRequestContext context(true);
4542 context.set_network_delegate(&network_delegate);
4543 context.Init();
[email protected]3cd384c602011-08-31 16:12:364544
4545 {
rhalavatib7bd7c792017-04-27 05:25:164546 std::unique_ptr<URLRequest> r(context.CreateRequest(
4547 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364548
[email protected]f7022f32014-08-21 16:32:194549 r->Start();
Wez2a31b222018-06-07 22:07:154550 d.RunUntilComplete();
[email protected]3cd384c602011-08-31 16:12:364551
[email protected]d8fc4722014-06-13 13:17:154552 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474553 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4554 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4555 EXPECT_FALSE(r->proxy_server().is_valid());
4556 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4557 EXPECT_TRUE(r->proxy_server().is_direct());
4558 } else {
4559 NOTREACHED();
4560 }
maksim.sisovb53724b52016-09-16 05:30:504561 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364562 EXPECT_EQ(1, network_delegate.created_requests());
4563 EXPECT_EQ(0, network_delegate.destroyed_requests());
4564 }
4565 EXPECT_EQ(1, network_delegate.destroyed_requests());
4566}
4567
[email protected]b4438d32012-09-27 06:15:304568// The following 3 tests check that the network delegate can cancel a request
4569// synchronously in various stages of the request.
4570TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554571 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304572 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4573 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554574 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304575}
4576
4577TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554578 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304579 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4580 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554581 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304582}
4583
4584TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554585 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304586 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4587 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554588 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304589}
4590
4591// The following 3 tests check that the network delegate can cancel a request
4592// asynchronously in various stages of the request.
4593TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554594 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304595 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4596 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554597 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304598}
4599
4600TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554601 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304602 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4603 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554604 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304605}
4606
4607TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554608 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304609 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4610 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554611 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304612}
4613
[email protected]4c76d7c2011-04-15 19:14:124614// Tests that the network delegate can block and redirect a request to a new
4615// URL.
4616TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554617 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124618
4619 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304620 BlockingNetworkDelegate network_delegate(
4621 BlockingNetworkDelegate::AUTO_CALLBACK);
4622 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
Eric Romanda790f92018-11-07 19:17:154623 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]4c76d7c2011-04-15 19:14:124624 network_delegate.set_redirect_url(redirect_url);
4625
[email protected]d5a4dd62012-05-23 01:41:044626 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554627 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504628
[email protected]4c76d7c2011-04-15 19:14:124629 {
Eric Romanda790f92018-11-07 19:17:154630 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164631 std::unique_ptr<URLRequest> r(context.CreateRequest(
4632 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124633
[email protected]6be6fa92014-08-06 23:44:564634 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194635 r->Start();
Wez0e717112018-06-18 23:09:224636 d.RunUntilRedirect();
[email protected]4c76d7c2011-04-15 19:14:124637
[email protected]6be6fa92014-08-06 23:44:564638 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194639 EXPECT_EQ(307, r->GetResponseCode());
4640 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564641 std::string location;
Raul Tambre94493c652019-03-11 17:18:354642 ASSERT_TRUE(
4643 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564644 EXPECT_EQ(redirect_url, GURL(location));
4645
4646 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354647 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4648 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154649 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:504650 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474651 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4652 http_test_server()->host_port_pair()),
4653 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094654 // before_send_headers_with_proxy_count only increments for headers sent
4655 // through an untunneled proxy.
4656 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554657 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4658 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274659
maksim.sisovb53724b52016-09-16 05:30:504660 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194661 EXPECT_EQ(redirect_url, r->url());
4662 EXPECT_EQ(original_url, r->original_url());
4663 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124664 EXPECT_EQ(1, network_delegate.created_requests());
4665 EXPECT_EQ(0, network_delegate.destroyed_requests());
4666 }
4667 EXPECT_EQ(1, network_delegate.destroyed_requests());
4668}
4669
[email protected]b813ed72012-04-05 08:21:364670// Tests that the network delegate can block and redirect a request to a new
4671// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4672TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554673 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364674
4675 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304676 BlockingNetworkDelegate network_delegate(
4677 BlockingNetworkDelegate::SYNCHRONOUS);
Eric Romanda790f92018-11-07 19:17:154678 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]b813ed72012-04-05 08:21:364679 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364680
[email protected]d5a4dd62012-05-23 01:41:044681 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554682 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364683
4684 {
Eric Romanda790f92018-11-07 19:17:154685 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164686 std::unique_ptr<URLRequest> r(context.CreateRequest(
4687 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364688
[email protected]6be6fa92014-08-06 23:44:564689 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194690 r->Start();
Wez0e717112018-06-18 23:09:224691 d.RunUntilRedirect();
[email protected]b813ed72012-04-05 08:21:364692
[email protected]6be6fa92014-08-06 23:44:564693 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194694 EXPECT_EQ(307, r->GetResponseCode());
4695 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564696 std::string location;
Raul Tambre94493c652019-03-11 17:18:354697 ASSERT_TRUE(
4698 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564699 EXPECT_EQ(redirect_url, GURL(location));
4700
4701 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354702 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4703 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154704 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564705
maksim.sisovb53724b52016-09-16 05:30:504706 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474707 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4708 http_test_server()->host_port_pair()),
4709 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094710 // before_send_headers_with_proxy_count only increments for headers sent
4711 // through an untunneled proxy.
4712 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554713 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4714 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504715 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194716 EXPECT_EQ(redirect_url, r->url());
4717 EXPECT_EQ(original_url, r->original_url());
4718 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364719 EXPECT_EQ(1, network_delegate.created_requests());
4720 EXPECT_EQ(0, network_delegate.destroyed_requests());
4721 }
4722 EXPECT_EQ(1, network_delegate.destroyed_requests());
4723}
4724
[email protected]3c5ca8c2011-09-29 01:14:514725// Tests that redirects caused by the network delegate preserve POST data.
4726TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554727 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514728
4729 const char kData[] = "hello world";
4730
4731 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304732 BlockingNetworkDelegate network_delegate(
4733 BlockingNetworkDelegate::AUTO_CALLBACK);
4734 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554735 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514736 network_delegate.set_redirect_url(redirect_url);
4737
[email protected]ef2bf422012-05-11 03:27:094738 TestURLRequestContext context(true);
4739 context.set_network_delegate(&network_delegate);
4740 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514741
4742 {
tommycli59a63432015-11-06 00:10:554743 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164744 std::unique_ptr<URLRequest> r(context.CreateRequest(
4745 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194746 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074747 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514748 HttpRequestHeaders headers;
4749 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:244750 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194751 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564752
4753 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194754 r->Start();
Wez0e717112018-06-18 23:09:224755 d.RunUntilRedirect();
[email protected]3c5ca8c2011-09-29 01:14:514756
[email protected]6be6fa92014-08-06 23:44:564757 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194758 EXPECT_EQ(307, r->GetResponseCode());
4759 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564760 std::string location;
Raul Tambre94493c652019-03-11 17:18:354761 ASSERT_TRUE(
4762 r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
[email protected]6be6fa92014-08-06 23:44:564763 EXPECT_EQ(redirect_url, GURL(location));
4764
4765 // Let the request finish.
Arthur Sonzognib8465ff72019-01-04 18:44:354766 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
4767 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:154768 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564769
maksim.sisovb53724b52016-09-16 05:30:504770 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194771 EXPECT_EQ(redirect_url, r->url());
4772 EXPECT_EQ(original_url, r->original_url());
4773 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514774 EXPECT_EQ(1, network_delegate.created_requests());
4775 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194776 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514777 EXPECT_EQ(kData, d.data_received());
4778 }
4779 EXPECT_EQ(1, network_delegate.destroyed_requests());
4780}
4781
[email protected]5f714132014-03-26 10:41:164782// Tests that the network delegate can block and redirect a request to a new
4783// URL during OnHeadersReceived.
4784TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554785 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164786
4787 TestDelegate d;
4788 BlockingNetworkDelegate network_delegate(
4789 BlockingNetworkDelegate::AUTO_CALLBACK);
4790 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
Eric Romanda790f92018-11-07 19:17:154791 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]5f714132014-03-26 10:41:164792 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4793
4794 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554795 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164796
4797 {
Eric Romanda790f92018-11-07 19:17:154798 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164799 std::unique_ptr<URLRequest> r(context.CreateRequest(
4800 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164801
[email protected]f7022f32014-08-21 16:32:194802 r->Start();
Wez2a31b222018-06-07 22:07:154803 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:164804
maksim.sisovb53724b52016-09-16 05:30:504805 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474806 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4807 http_test_server()->host_port_pair()),
4808 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094809 // before_send_headers_with_proxy_count only increments for headers sent
4810 // through an untunneled proxy.
4811 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554812 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4813 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194814
maksim.sisovb53724b52016-09-16 05:30:504815 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194816 EXPECT_EQ(redirect_url, r->url());
4817 EXPECT_EQ(original_url, r->original_url());
4818 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164819 EXPECT_EQ(2, network_delegate.created_requests());
4820 EXPECT_EQ(0, network_delegate.destroyed_requests());
4821 }
4822 EXPECT_EQ(1, network_delegate.destroyed_requests());
4823}
4824
[email protected]c2911d72011-10-03 22:16:364825// Tests that the network delegate can synchronously complete OnAuthRequired
4826// by taking no action. This indicates that the NetworkDelegate does not want to
4827// handle the challenge, and is passing the buck along to the
4828// URLRequest::Delegate.
4829TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554830 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364831
4832 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304833 BlockingNetworkDelegate network_delegate(
4834 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364835
[email protected]ef2bf422012-05-11 03:27:094836 TestURLRequestContext context(true);
4837 context.set_network_delegate(&network_delegate);
4838 context.Init();
[email protected]c2911d72011-10-03 22:16:364839
[email protected]f3cf9802011-10-28 18:44:584840 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364841
4842 {
tommycli59a63432015-11-06 00:10:554843 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164844 std::unique_ptr<URLRequest> r(context.CreateRequest(
4845 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194846 r->Start();
[email protected]79e1fd62013-06-20 06:50:044847
Wez2a31b222018-06-07 22:07:154848 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044849
maksim.sisovb53724b52016-09-16 05:30:504850 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194851 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044852 EXPECT_TRUE(d.auth_required_called());
4853 EXPECT_EQ(1, network_delegate.created_requests());
4854 EXPECT_EQ(0, network_delegate.destroyed_requests());
4855 }
4856 EXPECT_EQ(1, network_delegate.destroyed_requests());
4857}
4858
4859TEST_F(URLRequestTestHTTP,
4860 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554861 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044862
4863 TestDelegate d;
4864 BlockingNetworkDelegate network_delegate(
4865 BlockingNetworkDelegate::SYNCHRONOUS);
4866
4867 TestURLRequestContext context(true);
4868 context.set_network_delegate(&network_delegate);
4869 context.Init();
4870
4871 d.set_credentials(AuthCredentials(kUser, kSecret));
4872
4873 {
tommycli59a63432015-11-06 00:10:554874 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164875 std::unique_ptr<URLRequest> r(context.CreateRequest(
4876 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194877 r->Start();
[email protected]79e1fd62013-06-20 06:50:044878
Wez2a31b222018-06-07 22:07:154879 d.RunUntilComplete();
shivanisha8061c4202017-06-13 23:35:524880
[email protected]79e1fd62013-06-20 06:50:044881 {
4882 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194883 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524884 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044885 }
4886
maksim.sisovb53724b52016-09-16 05:30:504887 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194888 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364889 EXPECT_TRUE(d.auth_required_called());
4890 EXPECT_EQ(1, network_delegate.created_requests());
4891 EXPECT_EQ(0, network_delegate.destroyed_requests());
4892 }
4893 EXPECT_EQ(1, network_delegate.destroyed_requests());
4894}
4895
4896// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404897// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364898TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554899 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364900
4901 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304902 BlockingNetworkDelegate network_delegate(
4903 BlockingNetworkDelegate::SYNCHRONOUS);
4904 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364905 network_delegate.set_auth_retval(
4906 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4907
[email protected]f3cf9802011-10-28 18:44:584908 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364909
[email protected]ef2bf422012-05-11 03:27:094910 TestURLRequestContext context(true);
4911 context.set_network_delegate(&network_delegate);
4912 context.Init();
[email protected]c2911d72011-10-03 22:16:364913
4914 {
tommycli59a63432015-11-06 00:10:554915 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164916 std::unique_ptr<URLRequest> r(context.CreateRequest(
4917 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194918 r->Start();
Wez2a31b222018-06-07 22:07:154919 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364920
maksim.sisovb53724b52016-09-16 05:30:504921 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194922 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364923 EXPECT_FALSE(d.auth_required_called());
4924 EXPECT_EQ(1, network_delegate.created_requests());
4925 EXPECT_EQ(0, network_delegate.destroyed_requests());
4926 }
4927 EXPECT_EQ(1, network_delegate.destroyed_requests());
4928}
4929
[email protected]79e1fd62013-06-20 06:50:044930// Same as above, but also tests that GetFullRequestHeaders returns the proper
4931// headers (for the first or second request) when called at the proper times.
4932TEST_F(URLRequestTestHTTP,
4933 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554934 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044935
4936 TestDelegate d;
4937 BlockingNetworkDelegate network_delegate(
4938 BlockingNetworkDelegate::SYNCHRONOUS);
4939 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4940 network_delegate.set_auth_retval(
4941 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4942
4943 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4944
4945 TestURLRequestContext context(true);
4946 context.set_network_delegate(&network_delegate);
4947 context.Init();
4948
4949 {
tommycli59a63432015-11-06 00:10:554950 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164951 std::unique_ptr<URLRequest> r(context.CreateRequest(
4952 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194953 r->Start();
Wez2a31b222018-06-07 22:07:154954 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044955
maksim.sisovb53724b52016-09-16 05:30:504956 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194957 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044958 EXPECT_FALSE(d.auth_required_called());
4959 EXPECT_EQ(1, network_delegate.created_requests());
4960 EXPECT_EQ(0, network_delegate.destroyed_requests());
4961
4962 {
4963 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194964 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044965 EXPECT_TRUE(headers.HasHeader("Authorization"));
4966 }
4967 }
4968 EXPECT_EQ(1, network_delegate.destroyed_requests());
4969}
4970
[email protected]c2911d72011-10-03 22:16:364971// Tests that the network delegate can synchronously complete OnAuthRequired
4972// by cancelling authentication.
4973TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554974 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364975
4976 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304977 BlockingNetworkDelegate network_delegate(
4978 BlockingNetworkDelegate::SYNCHRONOUS);
4979 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364980 network_delegate.set_auth_retval(
4981 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4982
[email protected]ef2bf422012-05-11 03:27:094983 TestURLRequestContext context(true);
4984 context.set_network_delegate(&network_delegate);
4985 context.Init();
[email protected]c2911d72011-10-03 22:16:364986
4987 {
tommycli59a63432015-11-06 00:10:554988 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164989 std::unique_ptr<URLRequest> r(context.CreateRequest(
4990 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194991 r->Start();
Wez2a31b222018-06-07 22:07:154992 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364993
maksim.sisovb53724b52016-09-16 05:30:504994 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194995 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364996 EXPECT_FALSE(d.auth_required_called());
4997 EXPECT_EQ(1, network_delegate.created_requests());
4998 EXPECT_EQ(0, network_delegate.destroyed_requests());
4999 }
5000 EXPECT_EQ(1, network_delegate.destroyed_requests());
5001}
5002
5003// Tests that the network delegate can asynchronously complete OnAuthRequired
5004// by taking no action. This indicates that the NetworkDelegate does not want
5005// to handle the challenge, and is passing the buck along to the
5006// URLRequest::Delegate.
5007TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:555008 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365009
5010 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305011 BlockingNetworkDelegate network_delegate(
5012 BlockingNetworkDelegate::AUTO_CALLBACK);
5013 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365014
[email protected]ef2bf422012-05-11 03:27:095015 TestURLRequestContext context(true);
5016 context.set_network_delegate(&network_delegate);
5017 context.Init();
[email protected]c2911d72011-10-03 22:16:365018
[email protected]f3cf9802011-10-28 18:44:585019 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:365020
5021 {
tommycli59a63432015-11-06 00:10:555022 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165023 std::unique_ptr<URLRequest> r(context.CreateRequest(
5024 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195025 r->Start();
Wez2a31b222018-06-07 22:07:155026 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365027
maksim.sisovb53724b52016-09-16 05:30:505028 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195029 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365030 EXPECT_TRUE(d.auth_required_called());
5031 EXPECT_EQ(1, network_delegate.created_requests());
5032 EXPECT_EQ(0, network_delegate.destroyed_requests());
5033 }
5034 EXPECT_EQ(1, network_delegate.destroyed_requests());
5035}
5036
5037// Tests that the network delegate can asynchronously complete OnAuthRequired
5038// by setting credentials.
5039TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:555040 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365041
5042 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305043 BlockingNetworkDelegate network_delegate(
5044 BlockingNetworkDelegate::AUTO_CALLBACK);
5045 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365046 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365047 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5048
[email protected]f3cf9802011-10-28 18:44:585049 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:365050 network_delegate.set_auth_credentials(auth_credentials);
5051
[email protected]ef2bf422012-05-11 03:27:095052 TestURLRequestContext context(true);
5053 context.set_network_delegate(&network_delegate);
5054 context.Init();
[email protected]c2911d72011-10-03 22:16:365055
5056 {
tommycli59a63432015-11-06 00:10:555057 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165058 std::unique_ptr<URLRequest> r(context.CreateRequest(
5059 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195060 r->Start();
Wez2a31b222018-06-07 22:07:155061 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365062
maksim.sisovb53724b52016-09-16 05:30:505063 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195064 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365065 EXPECT_FALSE(d.auth_required_called());
5066 EXPECT_EQ(1, network_delegate.created_requests());
5067 EXPECT_EQ(0, network_delegate.destroyed_requests());
5068 }
5069 EXPECT_EQ(1, network_delegate.destroyed_requests());
5070}
5071
5072// Tests that the network delegate can asynchronously complete OnAuthRequired
5073// by cancelling authentication.
5074TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:555075 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365076
5077 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305078 BlockingNetworkDelegate network_delegate(
5079 BlockingNetworkDelegate::AUTO_CALLBACK);
5080 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365081 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365082 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
5083
[email protected]ef2bf422012-05-11 03:27:095084 TestURLRequestContext context(true);
5085 context.set_network_delegate(&network_delegate);
5086 context.Init();
[email protected]c2911d72011-10-03 22:16:365087
5088 {
tommycli59a63432015-11-06 00:10:555089 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165090 std::unique_ptr<URLRequest> r(context.CreateRequest(
5091 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195092 r->Start();
Wez2a31b222018-06-07 22:07:155093 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365094
maksim.sisovb53724b52016-09-16 05:30:505095 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195096 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365097 EXPECT_FALSE(d.auth_required_called());
5098 EXPECT_EQ(1, network_delegate.created_requests());
5099 EXPECT_EQ(0, network_delegate.destroyed_requests());
5100 }
5101 EXPECT_EQ(1, network_delegate.destroyed_requests());
5102}
5103
David Benjamin0bda12f2018-02-07 19:58:455104// Tests that NetworkDelegate header overrides from the 401 response do not
5105// affect the 200 response. This is a regression test for
5106// https://crbug.com/801237.
5107TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
5108 ASSERT_TRUE(http_test_server()->Start());
5109
5110 TestDelegate d;
5111 d.set_credentials(AuthCredentials(kUser, kSecret));
5112 default_network_delegate_.set_add_header_to_first_response(true);
5113
5114 {
5115 GURL url(http_test_server()->GetURL("/auth-basic"));
Ryan Sleevib8449e02018-07-15 04:31:075116 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455117 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5118 r->Start();
5119
Wez2a31b222018-06-07 22:07:155120 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455121
5122 EXPECT_EQ(OK, d.request_status());
5123 EXPECT_EQ(200, r->GetResponseCode());
5124 EXPECT_TRUE(d.auth_required_called());
5125 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
5126 }
5127
5128 {
5129 GURL url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075130 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:455131 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5132 r->Start();
5133
Wez2a31b222018-06-07 22:07:155134 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455135
5136 // Check that set_add_header_to_first_response normally adds a header.
5137 EXPECT_EQ(OK, d.request_status());
5138 EXPECT_EQ(200, r->GetResponseCode());
5139 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
5140 }
5141}
5142
[email protected]9045b8822012-01-13 20:35:355143// Tests that we can handle when a network request was canceled while we were
5144// waiting for the network delegate.
5145// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
5146TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:555147 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355148
5149 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305150 BlockingNetworkDelegate network_delegate(
5151 BlockingNetworkDelegate::USER_CALLBACK);
5152 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:355153
[email protected]ef2bf422012-05-11 03:27:095154 TestURLRequestContext context(true);
5155 context.set_network_delegate(&network_delegate);
5156 context.Init();
[email protected]9045b8822012-01-13 20:35:355157
5158 {
rhalavatib7bd7c792017-04-27 05:25:165159 std::unique_ptr<URLRequest> r(
5160 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5161 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355162
[email protected]f7022f32014-08-21 16:32:195163 r->Start();
Wez2a31b222018-06-07 22:07:155164 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305165 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
5166 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355167 EXPECT_EQ(0, network_delegate.completed_requests());
5168 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195169 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355170 // Ensure that network delegate is notified.
5171 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505172 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355173 EXPECT_EQ(1, network_delegate.created_requests());
5174 EXPECT_EQ(0, network_delegate.destroyed_requests());
5175 }
5176 EXPECT_EQ(1, network_delegate.destroyed_requests());
5177}
5178
5179// Tests that we can handle when a network request was canceled while we were
5180// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:005181// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
5182// callback.
[email protected]9045b8822012-01-13 20:35:355183TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:555184 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355185
5186 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305187 BlockingNetworkDelegate network_delegate(
5188 BlockingNetworkDelegate::USER_CALLBACK);
5189 network_delegate.set_block_on(
5190 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:355191
[email protected]ef2bf422012-05-11 03:27:095192 TestURLRequestContext context(true);
5193 context.set_network_delegate(&network_delegate);
5194 context.Init();
[email protected]9045b8822012-01-13 20:35:355195
5196 {
rhalavatib7bd7c792017-04-27 05:25:165197 std::unique_ptr<URLRequest> r(
5198 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5199 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355200
[email protected]f7022f32014-08-21 16:32:195201 r->Start();
Wez2a31b222018-06-07 22:07:155202 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305203 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
5204 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355205 EXPECT_EQ(0, network_delegate.completed_requests());
5206 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195207 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355208 // Ensure that network delegate is notified.
5209 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505210 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355211 EXPECT_EQ(1, network_delegate.created_requests());
5212 EXPECT_EQ(0, network_delegate.destroyed_requests());
5213 }
5214 EXPECT_EQ(1, network_delegate.destroyed_requests());
5215}
5216
5217// Tests that we can handle when a network request was canceled while we were
5218// waiting for the network delegate.
5219// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
5220TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:555221 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355222
5223 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305224 BlockingNetworkDelegate network_delegate(
5225 BlockingNetworkDelegate::USER_CALLBACK);
5226 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:355227
[email protected]ef2bf422012-05-11 03:27:095228 TestURLRequestContext context(true);
5229 context.set_network_delegate(&network_delegate);
5230 context.Init();
[email protected]9045b8822012-01-13 20:35:355231
5232 {
rhalavatib7bd7c792017-04-27 05:25:165233 std::unique_ptr<URLRequest> r(
5234 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5235 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355236
[email protected]f7022f32014-08-21 16:32:195237 r->Start();
Wez2a31b222018-06-07 22:07:155238 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305239 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
5240 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355241 EXPECT_EQ(0, network_delegate.completed_requests());
5242 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195243 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355244 // Ensure that network delegate is notified.
5245 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505246 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355247 EXPECT_EQ(1, network_delegate.created_requests());
5248 EXPECT_EQ(0, network_delegate.destroyed_requests());
5249 }
5250 EXPECT_EQ(1, network_delegate.destroyed_requests());
5251}
5252
5253// Tests that we can handle when a network request was canceled while we were
5254// waiting for the network delegate.
5255// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:025256TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:555257 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355258
5259 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305260 BlockingNetworkDelegate network_delegate(
5261 BlockingNetworkDelegate::USER_CALLBACK);
5262 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:355263
[email protected]ef2bf422012-05-11 03:27:095264 TestURLRequestContext context(true);
5265 context.set_network_delegate(&network_delegate);
5266 context.Init();
[email protected]9045b8822012-01-13 20:35:355267
5268 {
danakj8522a25b2016-04-16 00:17:365269 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165270 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
5271 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355272
[email protected]f7022f32014-08-21 16:32:195273 r->Start();
Wez2a31b222018-06-07 22:07:155274 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305275 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
5276 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355277 EXPECT_EQ(0, network_delegate.completed_requests());
5278 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195279 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355280 // Ensure that network delegate is notified.
5281 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505282 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355283 EXPECT_EQ(1, network_delegate.created_requests());
5284 EXPECT_EQ(0, network_delegate.destroyed_requests());
5285 }
5286 EXPECT_EQ(1, network_delegate.destroyed_requests());
5287}
5288
tommycli59a63432015-11-06 00:10:555289namespace {
5290
danakj8522a25b2016-04-16 00:17:365291std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:555292 const test_server::HttpRequest& request) {
5293 if (request.headers.find("Host") == request.headers.end() ||
5294 request.headers.at("Host") != "www.server-auth.com" ||
5295 request.method != test_server::METHOD_CONNECT) {
5296 return nullptr;
5297 }
5298
danakj8522a25b2016-04-16 00:17:365299 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:555300 new test_server::BasicHttpResponse);
5301 http_response->set_code(HTTP_UNAUTHORIZED);
5302 http_response->AddCustomHeader("WWW-Authenticate",
5303 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:485304 return std::move(http_response);
tommycli59a63432015-11-06 00:10:555305}
5306
5307} // namespace
5308
5309// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:115310// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:555311// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:355312TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:555313 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:125314 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:555315 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115316
[email protected]ceefd7fd2012-11-29 00:36:245317 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:045318 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:555319 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:505320
[email protected]dc651782009-02-14 01:45:085321 TestDelegate d;
5322 {
danakj8522a25b2016-04-16 00:17:365323 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165324 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
5325 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:085326
[email protected]f7022f32014-08-21 16:32:195327 r->Start();
5328 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:085329
Wez2a31b222018-06-07 22:07:155330 d.RunUntilComplete();
[email protected]dc651782009-02-14 01:45:085331
Wojciech Dzierżanowskiabdeeaf2019-04-01 20:16:225332 // The proxy server should be set before failure.
5333 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
5334 http_test_server()->host_port_pair()),
5335 r->proxy_server());
maksim.sisovb53724b52016-09-16 05:30:505336 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:085337 }
5338}
5339
[email protected]b89290212009-08-14 22:37:355340TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:555341 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115342
initial.commit586acc5fe2008-07-26 22:42:525343 TestDelegate d;
5344 {
Ryan Sleevib8449e02018-07-15 04:31:075345 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165346 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5347 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525348
[email protected]f7022f32014-08-21 16:32:195349 r->Start();
5350 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525351
Wez2a31b222018-06-07 22:07:155352 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525353
5354 EXPECT_EQ(1, d.response_started_count());
5355 EXPECT_FALSE(d.received_data_before_response());
5356 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555357 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375358 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555359 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375360 r->GetResponseRemoteEndpoint().port());
[email protected]c31a54592009-09-04 02:36:165361
[email protected]9e743cd2010-03-16 07:03:535362 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:525363 }
initial.commit586acc5fe2008-07-26 22:42:525364}
5365
[email protected]263163f2012-06-14 22:40:345366// This test has the server send a large number of cookies to the client.
5367// To ensure that no number of cookies causes a crash, a galloping binary
5368// search is used to estimate that maximum number of cookies that are accepted
5369// by the browser. Beyond the maximum number, the request will fail with
5370// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:315371#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:305372// http://crbug.com/177916
5373#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
5374#else
5375#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
5376#endif // defined(OS_WIN)
5377TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:555378 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:345379
5380 int lower_bound = 0;
5381 int upper_bound = 1;
5382
5383 // Double the number of cookies until the response header limits are
5384 // exceeded.
5385 while (DoManyCookiesRequest(upper_bound)) {
5386 lower_bound = upper_bound;
5387 upper_bound *= 2;
5388 ASSERT_LT(upper_bound, 1000000);
5389 }
5390
pkasting6b68a162014-12-01 22:10:295391 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:345392 if (tolerance < 2)
5393 tolerance = 2;
5394
5395 // Perform a binary search to find the highest possible number of cookies,
5396 // within the desired tolerance.
5397 while (upper_bound - lower_bound >= tolerance) {
5398 int num_cookies = (lower_bound + upper_bound) / 2;
5399
5400 if (DoManyCookiesRequest(num_cookies))
5401 lower_bound = num_cookies;
5402 else
5403 upper_bound = num_cookies;
5404 }
5405 // Success: the test did not crash.
5406}
5407
[email protected]b89290212009-08-14 22:37:355408TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:555409 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115410
initial.commit586acc5fe2008-07-26 22:42:525411 TestDelegate d;
5412 {
Ryan Sleevib8449e02018-07-15 04:31:075413 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165414 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5415 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525416
[email protected]f7022f32014-08-21 16:32:195417 r->Start();
5418 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525419
Wez2a31b222018-06-07 22:07:155420 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525421
5422 EXPECT_EQ(1, d.response_started_count());
5423 EXPECT_FALSE(d.received_data_before_response());
5424 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555425 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375426 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555427 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375428 r->GetResponseRemoteEndpoint().port());
initial.commit586acc5fe2008-07-26 22:42:525429 }
[email protected]5d7b373e2009-09-02 07:19:035430}
5431
[email protected]79e1fd62013-06-20 06:50:045432TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555433 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045434
5435 TestDelegate d;
5436 {
tommycli59a63432015-11-06 00:10:555437 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075438 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165439 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045440
5441 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195442 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045443
[email protected]f7022f32014-08-21 16:32:195444 r->Start();
5445 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045446
Wez2a31b222018-06-07 22:07:155447 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:045448
5449 EXPECT_EQ(1, d.response_started_count());
5450 EXPECT_FALSE(d.received_data_before_response());
5451 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555452 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375453 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555454 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375455 r->GetResponseRemoteEndpoint().port());
[email protected]79e1fd62013-06-20 06:50:045456
5457 EXPECT_TRUE(d.have_full_request_headers());
5458 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5459 }
5460}
5461
[email protected]58e32bb2013-01-21 18:23:255462TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555463 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255464
5465 TestDelegate d;
5466 {
Ryan Sleevib8449e02018-07-15 04:31:075467 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165468 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5469 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255470
[email protected]f7022f32014-08-21 16:32:195471 r->Start();
5472 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255473
Wez2a31b222018-06-07 22:07:155474 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255475
5476 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195477 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255478 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5479
5480 EXPECT_EQ(1, d.response_started_count());
5481 EXPECT_FALSE(d.received_data_before_response());
5482 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555483 EXPECT_EQ(http_test_server()->host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:375484 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:555485 EXPECT_EQ(http_test_server()->host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:375486 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:255487 }
5488}
5489
tommycli59a63432015-11-06 00:10:555490// TODO(svaldez): Update tests to use EmbeddedTestServer.
5491#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395492TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555493 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555494 base::FilePath(kTestFilePath));
5495
5496 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395497
5498 // Parameter that specifies the Content-Length field in the response:
5499 // C - Compressed length.
5500 // U - Uncompressed length.
5501 // L - Large length (larger than both C & U).
5502 // M - Medium length (between C & U).
5503 // S - Small length (smaller than both C & U).
5504 const char test_parameters[] = "CULMS";
Avi Drissman4365a4782018-12-28 19:26:245505 const int num_tests = base::size(test_parameters) - 1; // Skip NULL.
[email protected]aad63572011-05-24 20:14:395506 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445507 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395508 // S has too little data, but we seem to accept it.
5509 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375510 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395511
xunjielifb4da222016-07-14 18:38:595512 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:195513 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
xunjielifb4da222016-07-14 18:38:595514 file_path = file_path.Append(kTestFilePath);
5515 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5516 std::string expected_content;
5517 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5518
5519 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395520 TestDelegate d;
5521 {
tommycli59a63432015-11-06 00:10:555522 std::string test_file = base::StringPrintf(
5523 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395524
[email protected]ceefd7fd2012-11-29 00:36:245525 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095526 TestURLRequestContext context(true);
5527 context.set_network_delegate(&network_delegate);
5528 context.Init();
[email protected]87a09a92011-07-14 15:50:505529
rhalavatib7bd7c792017-04-27 05:25:165530 std::unique_ptr<URLRequest> r(
5531 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5532 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195533 r->Start();
5534 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395535
Wez2a31b222018-06-07 22:07:155536 d.RunUntilComplete();
[email protected]aad63572011-05-24 20:14:395537
5538 EXPECT_EQ(1, d.response_started_count());
5539 EXPECT_FALSE(d.received_data_before_response());
5540 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505541 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395542 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505543 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5544 << "\"";
xunjielifb4da222016-07-14 18:38:595545 if (test_parameters[i] == 'S') {
5546 // When content length is smaller than both compressed length and
5547 // uncompressed length, HttpStreamParser might not read the full
5548 // response body.
5549 continue;
5550 }
5551 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395552 } else {
maksim.sisovb53724b52016-09-16 05:30:505553 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395554 << " Parameter = \"" << test_file << "\"";
5555 }
5556 }
5557 }
5558}
tommycli59a63432015-11-06 00:10:555559#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395560
[email protected]58e32bb2013-01-21 18:23:255561TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555562 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255563
tommycli59a63432015-11-06 00:10:555564 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455565 GURL original_url =
tommycli59a63432015-11-06 00:10:555566 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255567 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075568 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165569 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195570 req->Start();
Wez2a31b222018-06-07 22:07:155571 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255572
5573 EXPECT_EQ(1, d.response_started_count());
5574 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195575 EXPECT_EQ(destination_url, req->url());
5576 EXPECT_EQ(original_url, req->original_url());
5577 ASSERT_EQ(2U, req->url_chain().size());
5578 EXPECT_EQ(original_url, req->url_chain()[0]);
5579 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255580
5581 LoadTimingInfo load_timing_info_before_redirect;
5582 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5583 &load_timing_info_before_redirect));
5584 TestLoadTimingNotReused(load_timing_info_before_redirect,
5585 CONNECT_TIMING_HAS_DNS_TIMES);
5586
5587 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195588 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255589 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5590
5591 // Check that a new socket was used on redirect, since the server does not
5592 // supposed keep-alive sockets, and that the times before the redirect are
5593 // before the ones recorded for the second request.
5594 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5595 load_timing_info.socket_log_id);
5596 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5597 load_timing_info.connect_timing.connect_start);
5598}
5599
[email protected]8f1ac082011-04-19 21:14:135600TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555601 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135602
tommycli59a63432015-11-06 00:10:555603 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455604 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555605 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5606 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5607 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135608 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075609 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165610 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195611 req->Start();
Wez2a31b222018-06-07 22:07:155612 d.RunUntilComplete();
[email protected]8f1ac082011-04-19 21:14:135613
5614 EXPECT_EQ(1, d.response_started_count());
5615 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195616 EXPECT_EQ(destination_url, req->url());
5617 EXPECT_EQ(original_url, req->original_url());
5618 ASSERT_EQ(3U, req->url_chain().size());
5619 EXPECT_EQ(original_url, req->url_chain()[0]);
5620 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5621 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135622}
5623
David Benjamina7fde612019-03-15 14:20:585624// This is a regression test for https://crbug.com/942073.
5625TEST_F(URLRequestTestHTTP, RedirectEscaping) {
5626 ASSERT_TRUE(http_test_server()->Start());
5627
5628 // Assemble the destination URL as a string so it is not escaped by GURL.
5629 GURL destination_base = http_test_server()->GetURL("/defaultresponse");
5630 // Add a URL fragment of U+2603 unescaped, U+2603 escaped, and then a UTF-8
5631 // encoding error.
5632 std::string destination_url =
5633 destination_base.spec() + "#\xE2\x98\x83_%E2%98%83_\xE0\xE0";
5634 // Redirect resolution should percent-escape bytes and preserve the UTF-8
5635 // error at the end.
5636 std::string destination_escaped =
5637 destination_base.spec() + "#%E2%98%83_%E2%98%83_%E0%E0";
5638 GURL original_url = http_test_server()->GetURL(
5639 "/server-redirect?" + EscapeQueryParamValue(destination_url, false));
5640 TestDelegate d;
5641 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
5642 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5643 req->Start();
5644 d.RunUntilComplete();
5645
5646 EXPECT_EQ(1, d.response_started_count());
5647 EXPECT_EQ(1, d.received_redirect_count());
5648 EXPECT_EQ(destination_escaped, req->url().spec());
5649 EXPECT_EQ(original_url, req->original_url());
5650 ASSERT_EQ(2U, req->url_chain().size());
5651 EXPECT_EQ(original_url, req->url_chain()[0]);
5652 EXPECT_EQ(destination_escaped, req->url_chain()[1].spec());
5653}
5654
[email protected]abe1c4a2013-10-25 19:28:515655// First and second pieces of information logged by delegates to URLRequests.
5656const char kFirstDelegateInfo[] = "Wonderful delegate";
5657const char kSecondDelegateInfo[] = "Exciting delegate";
5658
5659// Logs delegate information to a URLRequest. The first string is logged
5660// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5661// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5662// another asynchronous call is used to clear the delegate information
5663// before calling a callback. The object then deletes itself.
5664class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5665 public:
David Benjamind1f287bf2018-06-12 01:57:205666 using Callback = base::OnceCallback<void()>;
[email protected]abe1c4a2013-10-25 19:28:515667
5668 // Each time delegate information is added to the URLRequest, the resulting
5669 // load state is checked. The expected load state after each request is
5670 // passed in as an argument.
5671 static void Run(URLRequest* url_request,
5672 LoadState expected_first_load_state,
5673 LoadState expected_second_load_state,
5674 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205675 Callback callback) {
tzik38f920a2018-08-01 04:41:205676 // base::MakeRefCounted<AsyncDelegateLogger> is unavailable here, since the
5677 // constructor of AsyncDelegateLogger is private.
5678 auto logger = base::WrapRefCounted(new AsyncDelegateLogger(
David Benjamind1f287bf2018-06-12 01:57:205679 url_request, expected_first_load_state, expected_second_load_state,
tzik38f920a2018-08-01 04:41:205680 expected_third_load_state, std::move(callback)));
[email protected]abe1c4a2013-10-25 19:28:515681 logger->Start();
5682 }
5683
5684 // Checks that the log entries, starting with log_position, contain the
5685 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5686 // recorded. Returns the index of entry after the expected number of
5687 // events this logged, or entries.size() if there aren't enough entries.
Eric Roman79cc7552019-07-19 02:17:545688 static size_t CheckDelegateInfo(const std::vector<NetLogEntry>& entries,
vishal.b62985ca92015-04-17 08:45:515689 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515690 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5691 if (log_position + 3 >= entries.size()) {
5692 ADD_FAILURE() << "Not enough log entries";
5693 return entries.size();
5694 }
5695 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005696 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5697 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
Eric Roman79cc7552019-07-19 02:17:545698 EXPECT_EQ(
5699 kFirstDelegateInfo,
5700 GetStringValueFromParams(entries[log_position], "delegate_blocked_by"));
[email protected]abe1c4a2013-10-25 19:28:515701
5702 ++log_position;
mikecirone8b85c432016-09-08 19:11:005703 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5704 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515705
5706 ++log_position;
mikecirone8b85c432016-09-08 19:11:005707 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5708 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
Eric Roman79cc7552019-07-19 02:17:545709 EXPECT_EQ(
5710 kSecondDelegateInfo,
5711 GetStringValueFromParams(entries[log_position], "delegate_blocked_by"));
[email protected]abe1c4a2013-10-25 19:28:515712
5713 ++log_position;
mikecirone8b85c432016-09-08 19:11:005714 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5715 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515716
5717 return log_position + 1;
5718 }
5719
5720 private:
5721 friend class base::RefCounted<AsyncDelegateLogger>;
5722
5723 AsyncDelegateLogger(URLRequest* url_request,
5724 LoadState expected_first_load_state,
5725 LoadState expected_second_load_state,
5726 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205727 Callback callback)
[email protected]abe1c4a2013-10-25 19:28:515728 : url_request_(url_request),
5729 expected_first_load_state_(expected_first_load_state),
5730 expected_second_load_state_(expected_second_load_state),
5731 expected_third_load_state_(expected_third_load_state),
David Benjamind1f287bf2018-06-12 01:57:205732 callback_(std::move(callback)) {}
[email protected]abe1c4a2013-10-25 19:28:515733
Chris Watkins7a41d3552017-12-01 02:13:275734 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515735
5736 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535737 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515738 LoadStateWithParam load_state = url_request_->GetLoadState();
5739 EXPECT_EQ(expected_first_load_state_, load_state.state);
5740 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455741 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155742 FROM_HERE,
5743 base::BindOnce(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515744 }
5745
5746 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535747 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515748 LoadStateWithParam load_state = url_request_->GetLoadState();
5749 EXPECT_EQ(expected_second_load_state_, load_state.state);
5750 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5751 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5752 } else {
5753 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5754 }
skyostil4891b25b2015-06-11 11:43:455755 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155756 FROM_HERE, base::BindOnce(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515757 }
5758
5759 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535760 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515761 LoadStateWithParam load_state = url_request_->GetLoadState();
5762 EXPECT_EQ(expected_third_load_state_, load_state.state);
5763 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085764 EXPECT_EQ(base::string16(), load_state.param);
David Benjamind1f287bf2018-06-12 01:57:205765 std::move(callback_).Run();
[email protected]abe1c4a2013-10-25 19:28:515766 }
5767
5768 URLRequest* url_request_;
5769 const int expected_first_load_state_;
5770 const int expected_second_load_state_;
5771 const int expected_third_load_state_;
David Benjamind1f287bf2018-06-12 01:57:205772 Callback callback_;
[email protected]abe1c4a2013-10-25 19:28:515773
5774 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5775};
5776
5777// NetworkDelegate that logs delegate information before a request is started,
5778// before headers are sent, when headers are read, and when auth information
5779// is requested. Uses AsyncDelegateLogger.
5780class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5781 public:
Chris Watkins7a41d3552017-12-01 02:13:275782 AsyncLoggingNetworkDelegate() = default;
5783 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515784
5785 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205786 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205787 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:205788 GURL* new_url) override {
David Benjamind1f287bf2018-06-12 01:57:205789 // TestNetworkDelegate always completes synchronously.
5790 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
5791 request, base::NullCallback(), new_url));
5792 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515793 }
5794
ryansturm2343cb62016-06-15 01:09:005795 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205796 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:005797 HttpRequestHeaders* headers) override {
David Benjamind1f287bf2018-06-12 01:57:205798 // TestNetworkDelegate always completes synchronously.
5799 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
5800 request, base::NullCallback(), headers));
5801 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515802 }
5803
dchengb03027d2014-10-21 12:00:205804 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515805 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205806 CompletionOnceCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515807 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165808 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135809 GURL* allowed_unsafe_redirect_url) override {
David Benjamind1f287bf2018-06-12 01:57:205810 // TestNetworkDelegate always completes synchronously.
5811 CHECK_NE(ERR_IO_PENDING,
5812 TestNetworkDelegate::OnHeadersReceived(
5813 request, base::NullCallback(), original_response_headers,
5814 override_response_headers, allowed_unsafe_redirect_url));
5815 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515816 }
5817
dchengb03027d2014-10-21 12:00:205818 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515819 URLRequest* request,
5820 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:205821 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:135822 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515823 AsyncDelegateLogger::Run(
David Benjamind1f287bf2018-06-12 01:57:205824 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5825 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5826 base::BindOnce(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5827 std::move(callback), credentials));
[email protected]abe1c4a2013-10-25 19:28:515828 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5829 }
5830
5831 private:
David Benjamind1f287bf2018-06-12 01:57:205832 static int RunCallbackAsynchronously(URLRequest* request,
5833 CompletionOnceCallback callback) {
5834 AsyncDelegateLogger::Run(request, LOAD_STATE_WAITING_FOR_DELEGATE,
5835 LOAD_STATE_WAITING_FOR_DELEGATE,
5836 LOAD_STATE_WAITING_FOR_DELEGATE,
5837 base::BindOnce(std::move(callback), OK));
[email protected]abe1c4a2013-10-25 19:28:515838 return ERR_IO_PENDING;
5839 }
5840
David Benjamind1f287bf2018-06-12 01:57:205841 static void SetAuthAndResume(AuthCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515842 AuthCredentials* credentials) {
5843 *credentials = AuthCredentials(kUser, kSecret);
David Benjamind1f287bf2018-06-12 01:57:205844 std::move(callback).Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
[email protected]abe1c4a2013-10-25 19:28:515845 }
5846
5847 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5848};
5849
5850// URLRequest::Delegate that logs delegate information when the headers
5851// are received, when each read completes, and during redirects. Uses
5852// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5853//
5854// Inherits from TestDelegate to reuse the TestDelegate code to handle
5855// advancing to the next step in most cases, as well as cancellation.
5856class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5857 public:
5858 enum CancelStage {
5859 NO_CANCEL = 0,
5860 CANCEL_ON_RECEIVED_REDIRECT,
5861 CANCEL_ON_RESPONSE_STARTED,
5862 CANCEL_ON_READ_COMPLETED
5863 };
5864
5865 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5866 : cancel_stage_(cancel_stage) {
5867 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5868 set_cancel_in_received_redirect(true);
5869 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5870 set_cancel_in_response_started(true);
5871 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5872 set_cancel_in_received_data(true);
5873 }
Chris Watkins7a41d3552017-12-01 02:13:275874 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515875
5876 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205877 void OnReceivedRedirect(URLRequest* request,
5878 const RedirectInfo& redirect_info,
5879 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515880 *defer_redirect = true;
5881 AsyncDelegateLogger::Run(
5882 request,
5883 LOAD_STATE_WAITING_FOR_DELEGATE,
5884 LOAD_STATE_WAITING_FOR_DELEGATE,
5885 LOAD_STATE_WAITING_FOR_DELEGATE,
5886 base::Bind(
5887 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595888 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515889 }
5890
maksim.sisov0f4aa142016-09-05 05:55:285891 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515892 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285893 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5894 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5895 base::Bind(
5896 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5897 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515898 }
5899
dchengb03027d2014-10-21 12:00:205900 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515901 AsyncDelegateLogger::Run(
5902 request,
5903 LOAD_STATE_IDLE,
5904 LOAD_STATE_IDLE,
5905 LOAD_STATE_IDLE,
5906 base::Bind(
5907 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5908 base::Unretained(this), request, bytes_read));
5909 }
5910
5911 private:
5912 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595913 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515914 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595915 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515916 // FollowDeferredRedirect should not be called after cancellation.
5917 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5918 return;
Arthur Sonzognib8465ff72019-01-04 18:44:355919 if (!defer_redirect) {
5920 request->FollowDeferredRedirect(base::nullopt /* removed_headers */,
5921 base::nullopt /* modified_headers */);
5922 }
[email protected]abe1c4a2013-10-25 19:28:515923 }
5924
maksim.sisov0f4aa142016-09-05 05:55:285925 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515926 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285927 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515928 }
5929
5930 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5931 // The parent class continues the request.
5932 TestDelegate::OnReadCompleted(request, bytes_read);
5933 }
5934
5935 const CancelStage cancel_stage_;
5936
5937 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5938};
5939
5940// Tests handling of delegate info before a request starts.
5941TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555942 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515943
5944 TestDelegate request_delegate;
5945 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:355946 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:515947 context.set_net_log(&net_log_);
5948 context.Init();
5949
5950 {
rhalavatib7bd7c792017-04-27 05:25:165951 std::unique_ptr<URLRequest> r(context.CreateRequest(
5952 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5953 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195954 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515955 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085956 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515957
5958 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195959 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515960 LOAD_STATE_WAITING_FOR_DELEGATE,
5961 LOAD_STATE_WAITING_FOR_DELEGATE,
5962 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195963 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515964
Wez2a31b222018-06-07 22:07:155965 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515966
[email protected]f7022f32014-08-21 16:32:195967 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505968 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515969 }
5970
Eric Roman79cc7552019-07-19 02:17:545971 auto entries = net_log_.GetEntries();
[email protected]abe1c4a2013-10-25 19:28:515972 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005973 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515974
5975 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5976
5977 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005978 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5979 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515980}
5981
5982// Tests handling of delegate info from a network delegate.
5983TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555984 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515985
5986 TestDelegate request_delegate;
5987 AsyncLoggingNetworkDelegate network_delegate;
5988 TestURLRequestContext context(true);
5989 context.set_network_delegate(&network_delegate);
5990 context.set_net_log(&net_log_);
5991 context.Init();
5992
5993 {
rhalavatib7bd7c792017-04-27 05:25:165994 std::unique_ptr<URLRequest> r(context.CreateRequest(
5995 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
5996 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195997 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515998 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085999 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516000
[email protected]f7022f32014-08-21 16:32:196001 r->Start();
Wez2a31b222018-06-07 22:07:156002 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516003
[email protected]f7022f32014-08-21 16:32:196004 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506005 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516006 EXPECT_EQ(1, network_delegate.created_requests());
6007 EXPECT_EQ(0, network_delegate.destroyed_requests());
6008 }
6009 EXPECT_EQ(1, network_delegate.destroyed_requests());
6010
6011 size_t log_position = 0;
Eric Roman79cc7552019-07-19 02:17:546012 auto entries = net_log_.GetEntries();
David Benjamin9776ca22018-06-13 00:00:156013 static const NetLogEventType kExpectedEvents[] = {
6014 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6015 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6016 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6017 };
6018 for (NetLogEventType event : kExpectedEvents) {
6019 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516020 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156021 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516022
6023 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6024 log_position + 1);
6025
6026 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156027 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006028 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516029 }
6030
mikecirone8b85c432016-09-08 19:11:006031 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6032 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516033}
6034
6035// Tests handling of delegate info from a network delegate in the case of an
6036// HTTP redirect.
6037TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:556038 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516039
6040 TestDelegate request_delegate;
6041 AsyncLoggingNetworkDelegate network_delegate;
6042 TestURLRequestContext context(true);
6043 context.set_network_delegate(&network_delegate);
6044 context.set_net_log(&net_log_);
6045 context.Init();
6046
6047 {
danakj8522a25b2016-04-16 00:17:366048 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556049 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166050 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196051 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516052 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086053 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516054
[email protected]f7022f32014-08-21 16:32:196055 r->Start();
Wez2a31b222018-06-07 22:07:156056 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516057
[email protected]f7022f32014-08-21 16:32:196058 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506059 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516060 EXPECT_EQ(2, network_delegate.created_requests());
6061 EXPECT_EQ(0, network_delegate.destroyed_requests());
6062 }
6063 EXPECT_EQ(1, network_delegate.destroyed_requests());
6064
6065 size_t log_position = 0;
Eric Roman79cc7552019-07-19 02:17:546066 auto entries = net_log_.GetEntries();
David Benjamin9776ca22018-06-13 00:00:156067 static const NetLogEventType kExpectedEvents[] = {
6068 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6069 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6070 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6071 };
6072 for (NetLogEventType event : kExpectedEvents) {
6073 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516074 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156075 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516076
David Benjamin9776ca22018-06-13 00:00:156077 log_position =
6078 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516079
6080 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156081 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006082 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516083 }
6084
6085 // The URLRequest::Delegate then gets informed about the redirect.
6086 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156087 entries, log_position + 1,
6088 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
mikecirone8b85c432016-09-08 19:11:006089 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516090
6091 // The NetworkDelegate logged information in the same three events as before.
David Benjamin9776ca22018-06-13 00:00:156092 for (NetLogEventType event : kExpectedEvents) {
6093 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516094 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156095 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516096
6097 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6098 log_position + 1);
6099
6100 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156101 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006102 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516103 }
6104
mikecirone8b85c432016-09-08 19:11:006105 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6106 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516107}
6108
6109// Tests handling of delegate info from a network delegate in the case of HTTP
6110// AUTH.
6111TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:556112 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516113
6114 TestDelegate request_delegate;
6115 AsyncLoggingNetworkDelegate network_delegate;
6116 TestURLRequestContext context(true);
6117 context.set_network_delegate(&network_delegate);
6118 context.set_net_log(&net_log_);
6119 context.Init();
6120
6121 {
rhalavatib7bd7c792017-04-27 05:25:166122 std::unique_ptr<URLRequest> r(context.CreateRequest(
6123 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
6124 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196125 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516126 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086127 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516128
[email protected]f7022f32014-08-21 16:32:196129 r->Start();
Wez2a31b222018-06-07 22:07:156130 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516131
[email protected]f7022f32014-08-21 16:32:196132 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506133 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516134 EXPECT_EQ(1, network_delegate.created_requests());
6135 EXPECT_EQ(0, network_delegate.destroyed_requests());
6136 }
6137 EXPECT_EQ(1, network_delegate.destroyed_requests());
6138
6139 size_t log_position = 0;
Eric Roman79cc7552019-07-19 02:17:546140 auto entries = net_log_.GetEntries();
David Benjamin9776ca22018-06-13 00:00:156141 static const NetLogEventType kExpectedEvents[] = {
6142 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6143 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6144 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6145 NetLogEventType::NETWORK_DELEGATE_AUTH_REQUIRED,
6146 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6147 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6148 };
6149 for (NetLogEventType event : kExpectedEvents) {
6150 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516151 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156152 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516153
David Benjamin9776ca22018-06-13 00:00:156154 log_position =
6155 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516156
6157 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156158 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006159 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516160 }
6161
mikecirone8b85c432016-09-08 19:11:006162 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6163 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516164}
6165
tommycli59a63432015-11-06 00:10:556166// TODO(svaldez): Update tests to use EmbeddedTestServer.
6167#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516168// Tests handling of delegate info from a URLRequest::Delegate.
6169TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:556170 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:556171 base::FilePath(kTestFilePath));
6172
6173 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:516174
6175 AsyncLoggingUrlRequestDelegate request_delegate(
6176 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6177 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356178 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516179 context.set_net_log(&net_log_);
6180 context.Init();
6181
6182 {
6183 // A chunked response with delays between chunks is used to make sure that
6184 // attempts by the URLRequest delegate to log information while reading the
6185 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:486186 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:516187 // that it occurs.
danakj8522a25b2016-04-16 00:17:366188 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556189 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166190 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196191 LoadStateWithParam load_state = r->GetLoadState();
6192 r->Start();
Wez2a31b222018-06-07 22:07:156193 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516194
[email protected]f7022f32014-08-21 16:32:196195 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506196 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516197 }
6198
Eric Roman79cc7552019-07-19 02:17:546199 auto entries = net_log_.GetEntries();
[email protected]abe1c4a2013-10-25 19:28:516200
[email protected]1826a402014-01-08 15:40:486201 size_t log_position = 0;
6202
[email protected]abe1c4a2013-10-25 19:28:516203 // The delegate info should only have been logged on header complete. Other
6204 // times it should silently be ignored.
David Benjamin9776ca22018-06-13 00:00:156205 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
6206 entries, 0, NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST));
mikecirone8b85c432016-09-08 19:11:006207 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156208 entries, log_position + 1,
6209 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
mikecirone8b85c432016-09-08 19:11:006210 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516211
David Benjamin9776ca22018-06-13 00:00:156212 log_position =
6213 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516214
6215 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156216 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6217 entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006218 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516219
mikecirone8b85c432016-09-08 19:11:006220 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6221 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516222 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
David Benjamin9776ca22018-06-13 00:00:156223 entries, log_position + 1,
6224 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED));
[email protected]abe1c4a2013-10-25 19:28:516225}
tommycli59a63432015-11-06 00:10:556226#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516227
6228// Tests handling of delegate info from a URLRequest::Delegate in the case of
6229// an HTTP redirect.
6230TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:556231 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516232
6233 AsyncLoggingUrlRequestDelegate request_delegate(
6234 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6235 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356236 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516237 context.set_net_log(&net_log_);
6238 context.Init();
6239
6240 {
danakj8522a25b2016-04-16 00:17:366241 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556242 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166243 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196244 LoadStateWithParam load_state = r->GetLoadState();
6245 r->Start();
Wez2a31b222018-06-07 22:07:156246 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516247
[email protected]f7022f32014-08-21 16:32:196248 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506249 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516250 }
6251
Eric Roman79cc7552019-07-19 02:17:546252 auto entries = net_log_.GetEntries();
[email protected]abe1c4a2013-10-25 19:28:516253
6254 // Delegate info should only have been logged in OnReceivedRedirect and
6255 // OnResponseStarted.
6256 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156257 static const NetLogEventType kExpectedEvents[] = {
6258 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6259 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6260 };
6261 for (NetLogEventType event : kExpectedEvents) {
6262 SCOPED_TRACE(NetLog::EventTypeToString(event));
6263 log_position = ExpectLogContainsSomewhereAfter(entries, log_position, event,
6264 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516265
David Benjamin9776ca22018-06-13 00:00:156266 log_position =
6267 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516268
6269 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156270 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006271 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516272 }
6273
mikecirone8b85c432016-09-08 19:11:006274 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6275 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516276}
6277
6278// Tests handling of delegate info from a URLRequest::Delegate in the case of
6279// an HTTP redirect, with cancellation at various points.
6280TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:556281 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516282
6283 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
6284 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
6285 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
6286 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
6287 };
6288
David Benjamin9776ca22018-06-13 00:00:156289 for (auto cancel_stage : kCancelStages) {
6290 AsyncLoggingUrlRequestDelegate request_delegate(cancel_stage);
vishal.b62985ca92015-04-17 08:45:516291 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046292 TestURLRequestContext context(true);
Raul Tambre94493c652019-03-11 17:18:356293 context.set_network_delegate(nullptr);
[email protected]abe1c4a2013-10-25 19:28:516294 context.set_net_log(&net_log);
6295 context.Init();
6296
6297 {
danakj8522a25b2016-04-16 00:17:366298 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556299 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166300 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196301 LoadStateWithParam load_state = r->GetLoadState();
6302 r->Start();
Wez2a31b222018-06-07 22:07:156303 request_delegate.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506304 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
Wez2a31b222018-06-07 22:07:156305
6306 // Spin the message loop to run AsyncDelegateLogger task(s) posted after
6307 // the |request_delegate| completion task.
6308 base::RunLoop().RunUntilIdle();
[email protected]abe1c4a2013-10-25 19:28:516309 }
6310
Eric Roman79cc7552019-07-19 02:17:546311 auto entries = net_log.GetEntries();
[email protected]abe1c4a2013-10-25 19:28:516312
6313 // Delegate info is always logged in both OnReceivedRedirect and
6314 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6315 // OnResponseStarted delegate call is after cancellation, but logging is
6316 // still currently supported in that call.
6317 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156318 static const NetLogEventType kExpectedEvents[] = {
6319 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6320 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6321 };
6322 for (NetLogEventType event : kExpectedEvents) {
6323 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516324 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156325 entries, log_position, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516326
David Benjamin9776ca22018-06-13 00:00:156327 log_position =
6328 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516329
6330 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156331 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006332 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516333 }
6334
mikecirone8b85c432016-09-08 19:11:006335 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6336 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516337 }
6338}
6339
[email protected]847c0fa92012-11-06 16:37:426340namespace {
6341
6342const char kExtraHeader[] = "Allow-Snafu";
6343const char kExtraValue[] = "fubar";
6344
6345class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206346 void OnReceivedRedirect(URLRequest* request,
6347 const RedirectInfo& redirect_info,
6348 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596349 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426350 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6351 }
6352};
6353
6354} // namespace
6355
6356TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556357 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426358
tommycli59a63432015-11-06 00:10:556359 GURL destination_url =
6360 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6361 GURL original_url =
6362 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426363 RedirectWithAdditionalHeadersDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076364 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166365 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196366 req->Start();
Wez2a31b222018-06-07 22:07:156367 d.RunUntilComplete();
[email protected]847c0fa92012-11-06 16:37:426368
6369 std::string value;
[email protected]f7022f32014-08-21 16:32:196370 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426371 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6372 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196373 EXPECT_FALSE(req->is_pending());
6374 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426375 EXPECT_EQ(kExtraValue, d.data_received());
6376}
6377
[email protected]251a1b92012-11-13 11:01:096378namespace {
6379
6380const char kExtraHeaderToRemove[] = "To-Be-Removed";
6381
6382class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206383 void OnReceivedRedirect(URLRequest* request,
6384 const RedirectInfo& redirect_info,
6385 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596386 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096387 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6388 }
6389};
6390
6391} // namespace
6392
6393TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556394 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096395
tommycli59a63432015-11-06 00:10:556396 GURL destination_url = http_test_server()->GetURL(
6397 "/echoheader?" + std::string(kExtraHeaderToRemove));
6398 GURL original_url =
6399 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096400 RedirectWithHeaderRemovalDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076401 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166402 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196403 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6404 req->Start();
Wez2a31b222018-06-07 22:07:156405 d.RunUntilComplete();
[email protected]251a1b92012-11-13 11:01:096406
6407 std::string value;
[email protected]f7022f32014-08-21 16:32:196408 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096409 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196410 EXPECT_FALSE(req->is_pending());
6411 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096412 EXPECT_EQ("None", d.data_received());
6413}
6414
mmenke94f1bd92016-12-07 21:13:056415TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446416 TestDelegate d;
6417 {
Ryan Sleevib8449e02018-07-15 04:31:076418 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166419 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6420 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446421
[email protected]f7022f32014-08-21 16:32:196422 r->Start();
6423 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446424
[email protected]f7022f32014-08-21 16:32:196425 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446426
Wez2a31b222018-06-07 22:07:156427 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446428
6429 // We expect to receive OnResponseStarted even though the request has been
6430 // cancelled.
6431 EXPECT_EQ(1, d.response_started_count());
6432 EXPECT_EQ(0, d.bytes_received());
6433 EXPECT_FALSE(d.received_data_before_response());
6434 }
6435}
6436
mmenke94f1bd92016-12-07 21:13:056437TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556438 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446439
6440 TestDelegate d;
6441 {
Ryan Sleevib8449e02018-07-15 04:31:076442 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166443 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6444 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446445
6446 d.set_cancel_in_response_started(true);
6447
[email protected]f7022f32014-08-21 16:32:196448 r->Start();
6449 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446450
Wez2a31b222018-06-07 22:07:156451 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446452
6453 EXPECT_EQ(1, d.response_started_count());
6454 EXPECT_EQ(0, d.bytes_received());
6455 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506456 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446457 }
6458}
6459
mmenke94f1bd92016-12-07 21:13:056460TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556461 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446462
6463 TestDelegate d;
6464 {
Ryan Sleevib8449e02018-07-15 04:31:076465 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166466 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6467 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056468
6469 d.set_cancel_in_received_data(true);
6470
6471 r->Start();
6472 EXPECT_TRUE(r->is_pending());
6473
Wez2a31b222018-06-07 22:07:156474 d.RunUntilComplete();
mmenke94f1bd92016-12-07 21:13:056475
6476 EXPECT_EQ(1, d.response_started_count());
6477 EXPECT_NE(0, d.received_bytes_count());
6478 EXPECT_FALSE(d.received_data_before_response());
6479 EXPECT_EQ(ERR_ABORTED, d.request_status());
6480 }
6481}
6482
6483TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6484 ASSERT_TRUE(http_test_server()->Start());
6485
6486 TestDelegate d;
6487 {
6488 // This returns an empty response (With headers).
Ryan Sleevib8449e02018-07-15 04:31:076489 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166490 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6491 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446492
6493 d.set_cancel_in_received_data(true);
6494
[email protected]f7022f32014-08-21 16:32:196495 r->Start();
6496 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446497
Wez2a31b222018-06-07 22:07:156498 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446499
6500 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056501 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446502 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506503 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446504 }
6505}
6506
mmenke94f1bd92016-12-07 21:13:056507TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556508 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446509
6510 TestDelegate d;
6511 {
Ryan Sleevib8449e02018-07-15 04:31:076512 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166513 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6514 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446515
[email protected]f7022f32014-08-21 16:32:196516 r->Start();
6517 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446518
6519 // The request will be implicitly canceled when it is destroyed. The
6520 // test delegate must not post a quit message when this happens because
6521 // this test doesn't actually have a message loop. The quit message would
6522 // get put on this thread's message queue and the next test would exit
6523 // early, causing problems.
Wez0e717112018-06-18 23:09:226524 d.set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:446525 }
6526 // expect things to just cleanup properly.
6527
kimwjdalsl2bb4ff02015-12-16 22:06:026528 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446529 // message loop
6530 EXPECT_FALSE(d.received_data_before_response());
6531 EXPECT_EQ(0, d.bytes_received());
6532}
6533
mmenke94f1bd92016-12-07 21:13:056534TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556535 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446536
6537 // populate cache
6538 {
6539 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076540 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166541 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6542 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196543 r->Start();
Wez2a31b222018-06-07 22:07:156544 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506545 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446546 }
6547
6548 // cancel read from cache (see bug 990242)
6549 {
6550 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076551 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166552 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6553 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196554 r->Start();
6555 r->Cancel();
Wez2a31b222018-06-07 22:07:156556 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446557
maksim.sisovb53724b52016-09-16 05:30:506558 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446559 EXPECT_EQ(1, d.response_started_count());
6560 EXPECT_EQ(0, d.bytes_received());
6561 EXPECT_FALSE(d.received_data_before_response());
6562 }
6563}
6564
6565TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556566 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446567 HTTPUploadDataOperationTest("POST");
6568}
6569
6570TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556571 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446572 HTTPUploadDataOperationTest("PUT");
6573}
6574
6575TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556576 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446577
6578 TestDelegate d;
6579 {
Ryan Sleevib8449e02018-07-15 04:31:076580 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166581 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6582 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196583 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446584
[email protected]f7022f32014-08-21 16:32:196585 r->Start();
6586 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446587
Wez2a31b222018-06-07 22:07:156588 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446589
maksim.sisovb53724b52016-09-16 05:30:506590 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6591 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446592
6593 EXPECT_FALSE(d.received_data_before_response());
6594 EXPECT_TRUE(d.data_received().empty());
6595 }
6596}
6597
6598TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556599 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446600
6601 TestDelegate d;
6602 {
Ryan Sleevib8449e02018-07-15 04:31:076603 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166604 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6605 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196606 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446607
[email protected]6cdfd7f2013-02-08 20:40:156608 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196609 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026610 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446611
danakj8522a25b2016-04-16 00:17:366612 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446613
[email protected]6cdfd7f2013-02-08 20:40:156614 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196615 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476616 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446617 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196618 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146619 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076620 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046621 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6622 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446623
[email protected]f7022f32014-08-21 16:32:196624 r->Start();
6625 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446626
Wez2a31b222018-06-07 22:07:156627 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446628
avibf0746c2015-12-09 19:53:146629 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296630 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6631 ASSERT_LE(size64, std::numeric_limits<int>::max());
6632 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366633 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446634
[email protected]7600d0b2013-12-08 21:43:306635 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446636
maksim.sisovb53724b52016-09-16 05:30:506637 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6638 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446639
6640 EXPECT_FALSE(d.received_data_before_response());
6641
[email protected]329b68b2012-11-14 17:54:276642 EXPECT_EQ(size, d.bytes_received());
6643 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446644 }
6645}
6646
[email protected]999dd8c2013-11-12 06:45:546647TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556648 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546649
6650 TestDelegate d;
6651 {
Ryan Sleevib8449e02018-07-15 04:31:076652 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166653 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6654 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196655 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546656
danakj8522a25b2016-04-16 00:17:366657 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546658
Jeremy Roman0579ed62017-08-29 15:56:196659 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456660 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546661 base::FilePath(FILE_PATH_LITERAL(
6662 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076663 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046664 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6665 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546666
[email protected]f7022f32014-08-21 16:32:196667 r->Start();
6668 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546669
Wez2a31b222018-06-07 22:07:156670 d.RunUntilComplete();
[email protected]999dd8c2013-11-12 06:45:546671
[email protected]999dd8c2013-11-12 06:45:546672 EXPECT_TRUE(d.request_failed());
6673 EXPECT_FALSE(d.received_data_before_response());
6674 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506675 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546676 }
6677}
6678
mmenke56b0cbb912016-03-28 21:34:536679namespace {
6680
6681// Adds a standard set of data to an upload for chunked upload integration
6682// tests.
6683void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6684 writer->AppendData("a", 1, false);
6685 writer->AppendData("bcd", 3, false);
6686 writer->AppendData("this is a longer chunk than before.", 35, false);
6687 writer->AppendData("\r\n\r\n", 4, false);
6688 writer->AppendData("0", 1, false);
6689 writer->AppendData("2323", 4, true);
6690}
6691
6692// Checks that the upload data added in AddChunksToUpload() was echoed back from
6693// the server.
6694void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6695 // This should match the chunks sent by AddChunksToUpload().
6696 const std::string expected_data =
6697 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6698
maksim.sisovb53724b52016-09-16 05:30:506699 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6700 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536701
6702 EXPECT_FALSE(d->received_data_before_response());
6703
6704 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6705 EXPECT_EQ(expected_data, d->data_received());
6706}
6707
6708} // namespace
6709
[email protected]316c1e5e2012-09-12 15:17:446710TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556711 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446712
6713 TestDelegate d;
6714 {
Ryan Sleevib8449e02018-07-15 04:31:076715 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166716 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6717 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366718 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536719 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366720 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536721 upload_data_stream->CreateWriter();
6722 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196723 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536724 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196725 r->Start();
6726 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446727
Wez2a31b222018-06-07 22:07:156728 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446729
[email protected]f7022f32014-08-21 16:32:196730 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446731 }
6732}
6733
[email protected]329b68b2012-11-14 17:54:276734TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556735 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276736
6737 TestDelegate d;
6738 {
Ryan Sleevib8449e02018-07-15 04:31:076739 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166740 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6741 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366742 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536743 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366744 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536745 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046746 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196747 r->set_method("POST");
6748 r->Start();
6749 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536750 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156751 d.RunUntilComplete();
[email protected]329b68b2012-11-14 17:54:276752
[email protected]f7022f32014-08-21 16:32:196753 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276754 }
6755}
6756
Asanka Herathf05753e2018-08-16 17:38:206757TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556758 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446759
6760 TestDelegate d;
6761 {
Ryan Sleevib8449e02018-07-15 04:31:076762 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166763 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6764 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366765 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536766 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366767 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536768 upload_data_stream->CreateWriter();
6769 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196770 r->set_method("POST");
6771 r->Start();
6772 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446773
Asanka Herathf05753e2018-08-16 17:38:206774 // Pump messages until we start sending headers..
[email protected]255620da2013-08-19 13:14:296775 base::RunLoop().RunUntilIdle();
Asanka Herathf05753e2018-08-16 17:38:206776
6777 // And now wait for completion.
6778 base::RunLoop run_loop;
6779 d.set_on_complete(run_loop.QuitClosure());
mmenke56b0cbb912016-03-28 21:34:536780 AddDataToUpload(writer.get());
Asanka Herathf05753e2018-08-16 17:38:206781 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:446782
[email protected]f7022f32014-08-21 16:32:196783 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446784 }
6785}
6786
6787TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556788 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446789
6790 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076791 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166792 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6793 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196794 req->Start();
Wez2a31b222018-06-07 22:07:156795 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446796
[email protected]f7022f32014-08-21 16:32:196797 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446798
6799 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196800 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446801
6802 std::string header;
6803 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6804 EXPECT_EQ("private", header);
6805
6806 header.clear();
6807 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6808 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6809
6810 // The response has two "X-Multiple-Entries" headers.
6811 // This verfies our output has them concatenated together.
6812 header.clear();
6813 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6814 EXPECT_EQ("a, b", header);
6815}
6816
tommycli59a63432015-11-06 00:10:556817// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6818// security state. (see http://crbug.com/550977).
6819#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466820TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556821 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6822 https_test_server.SetSSLConfig(
6823 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6824 https_test_server.ServeFilesFromSourceDirectory(
6825 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466826 ASSERT_TRUE(https_test_server.Start());
6827
tommycli59a63432015-11-06 00:10:556828 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466829 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076830 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166831 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6832 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196833 request->Start();
Wez2a31b222018-06-07 22:07:156834 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466835
6836 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076837 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406838 TransportSecurityState::STSState sts_state;
6839 TransportSecurityState::PKPState pkp_state;
6840 EXPECT_TRUE(
6841 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6842 EXPECT_FALSE(
6843 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6844 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6845 sts_state.upgrade_mode);
6846 EXPECT_TRUE(sts_state.include_subdomains);
6847 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036848#if defined(OS_ANDROID)
6849 // Android's CertVerifyProc does not (yet) handle pins.
6850#else
martijnc0d6b622015-06-30 19:14:406851 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036852#endif
[email protected]37fd55fb2013-06-29 13:13:276853}
6854
estarka5da76702015-04-09 04:00:166855TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556856 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6857 https_test_server.ServeFilesFromSourceDirectory(
6858 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166859 ASSERT_TRUE(https_test_server.Start());
6860 // Make sure this test fails if the test server is changed to not
6861 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556862 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6863 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166864
6865 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076866 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166867 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6868 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166869 request->Start();
Wez2a31b222018-06-07 22:07:156870 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:166871 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076872 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406873 TransportSecurityState::STSState sts_state;
6874 EXPECT_FALSE(
6875 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166876}
6877
estark06e0dac2015-08-07 21:56:016878namespace {
Martijn Croonenb1383da2017-10-11 11:56:356879const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
Matt Mueller230996f12018-10-22 19:39:446880const char kPKPReportUri[] = "http://report-uri.preloaded.test/pkp";
6881const char kPKPHost[] = "with-report-uri-pkp.preloaded.test";
estark06e0dac2015-08-07 21:56:016882} // namespace
6883
Matt Mueller230996f12018-10-22 19:39:446884// Tests that reports get sent on PKP violations when a report-uri is set.
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516885TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
Matt Mueller230996f12018-10-22 19:39:446886 GURL report_uri(kPKPReportUri);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516887 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6888 https_test_server.SetSSLConfig(
6889 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6890 https_test_server.ServeFilesFromSourceDirectory(
6891 base::FilePath(kTestFilePath));
6892 ASSERT_TRUE(https_test_server.Start());
6893
Matt Mueller230996f12018-10-22 19:39:446894 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016895
6896 // Set up a pin for |test_server_hostname|.
6897 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446898 security_state.EnableStaticPinsForTesting();
6899 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016900
6901 MockCertificateReportSender mock_report_sender;
6902 security_state.SetReportSender(&mock_report_sender);
6903
6904 // Set up a MockCertVerifier to trigger a violation of the previously
6905 // set pin.
6906 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6907 ASSERT_TRUE(cert);
6908
6909 MockCertVerifier cert_verifier;
6910 CertVerifyResult verify_result;
6911 verify_result.verified_cert = cert;
6912 verify_result.is_issued_by_known_root = true;
6913 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446914 ASSERT_TRUE(
6915 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016916 verify_result.public_key_hashes.push_back(hash3);
6917 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6918
6919 TestNetworkDelegate network_delegate;
6920 TestURLRequestContext context(true);
6921 context.set_transport_security_state(&security_state);
6922 context.set_network_delegate(&network_delegate);
6923 context.set_cert_verifier(&cert_verifier);
6924 context.Init();
6925
6926 // Now send a request to trigger the violation.
6927 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366928 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446929 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166930 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016931 violating_request->Start();
Wez2a31b222018-06-07 22:07:156932 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016933
6934 // Check that a report was sent.
6935 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6936 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446937 EXPECT_EQ("application/json; charset=utf-8",
6938 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366939 std::unique_ptr<base::Value> value(
Lei Zhanga8b4c5fb2019-02-16 03:02:036940 base::JSONReader::ReadDeprecated(mock_report_sender.latest_report()));
estark06e0dac2015-08-07 21:56:016941 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086942 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016943 base::DictionaryValue* report_dict;
6944 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6945 std::string report_hostname;
6946 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6947 EXPECT_EQ(test_server_hostname, report_hostname);
6948}
6949
Matt Mueller230996f12018-10-22 19:39:446950// Tests that reports do not get sent on requests to static pkp hosts that
6951// don't have pin violations.
6952TEST_F(URLRequestTestHTTP, ProcessPKPWithNoViolation) {
tommycli59a63432015-11-06 00:10:556953 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6954 https_test_server.SetSSLConfig(
6955 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6956 https_test_server.ServeFilesFromSourceDirectory(
6957 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016958 ASSERT_TRUE(https_test_server.Start());
6959
Matt Mueller230996f12018-10-22 19:39:446960 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016961
6962 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446963 security_state.EnableStaticPinsForTesting();
6964 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016965 MockCertificateReportSender mock_report_sender;
6966 security_state.SetReportSender(&mock_report_sender);
6967
Matt Mueller230996f12018-10-22 19:39:446968 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6969 ASSERT_TRUE(cert);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516970 MockCertVerifier mock_cert_verifier;
Matt Mueller230996f12018-10-22 19:39:446971 CertVerifyResult verify_result;
6972 verify_result.verified_cert = cert;
6973 verify_result.is_issued_by_known_root = true;
6974 HashValue hash;
6975 // The expected value of GoodPin1 used by |test_default::kHSTSSource|.
6976 ASSERT_TRUE(
6977 hash.FromString("sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY="));
6978 verify_result.public_key_hashes.push_back(hash);
6979 mock_cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6980
6981 TestNetworkDelegate network_delegate;
estark06e0dac2015-08-07 21:56:016982 TestURLRequestContext context(true);
6983 context.set_transport_security_state(&security_state);
6984 context.set_network_delegate(&network_delegate);
6985 context.set_cert_verifier(&mock_cert_verifier);
estark06e0dac2015-08-07 21:56:016986 context.Init();
6987
6988 // Now send a request that does not trigger the violation.
6989 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366990 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446991 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166992 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016993 request->Start();
Wez2a31b222018-06-07 22:07:156994 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016995
Matt Mueller230996f12018-10-22 19:39:446996 // Check that the request succeeded, a report was not sent and the pkp was
6997 // not bypassed.
6998 EXPECT_EQ(OK, d.request_status());
estark06e0dac2015-08-07 21:56:016999 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
7000 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
Matt Mueller230996f12018-10-22 19:39:447001 TransportSecurityState::STSState sts_state;
martijnc0d6b622015-06-30 19:14:407002 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:447003 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
7004 &sts_state, &pkp_state));
7005 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
7006 EXPECT_FALSE(request->ssl_info().pkp_bypassed);
estarka5da76702015-04-09 04:00:167007}
7008
dadriandf302c42016-06-10 18:48:597009TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
7010 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7011 https_test_server.SetSSLConfig(
7012 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7013 https_test_server.ServeFilesFromSourceDirectory(
7014 base::FilePath(kTestFilePath));
7015 ASSERT_TRUE(https_test_server.Start());
7016
7017 // Set up a MockCertVerifier to be a local root that violates the pin
7018 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7019 ASSERT_TRUE(cert);
7020
7021 MockCertVerifier cert_verifier;
7022 CertVerifyResult verify_result;
7023 verify_result.verified_cert = cert;
7024 verify_result.is_issued_by_known_root = false;
7025 HashValue hash;
7026 ASSERT_TRUE(
7027 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
7028 verify_result.public_key_hashes.push_back(hash);
7029 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
dadriandf302c42016-06-10 18:48:597030
Matt Mueller230996f12018-10-22 19:39:447031 std::string test_server_hostname = kPKPHost;
dadriandf302c42016-06-10 18:48:597032
Matt Mueller230996f12018-10-22 19:39:447033 // Set up PKP
dadriandf302c42016-06-10 18:48:597034 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:447035 security_state.EnableStaticPinsForTesting();
7036 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7037 MockCertificateReportSender mock_report_sender;
7038 security_state.SetReportSender(&mock_report_sender);
dadriandf302c42016-06-10 18:48:597039
7040 TestNetworkDelegate network_delegate;
7041 TestURLRequestContext context(true);
7042 context.set_transport_security_state(&security_state);
7043 context.set_network_delegate(&network_delegate);
7044 context.set_cert_verifier(&cert_verifier);
7045 context.Init();
7046
7047 TestDelegate d;
7048 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:447049 https_test_server.GetURL(test_server_hostname, "/simple.html"),
7050 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:597051 request->Start();
Wez2a31b222018-06-07 22:07:157052 d.RunUntilComplete();
dadriandf302c42016-06-10 18:48:597053
Matt Mueller230996f12018-10-22 19:39:447054 // Check that the request succeeded, a report was not sent and the PKP was
7055 // bypassed.
7056 EXPECT_EQ(OK, d.request_status());
7057 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
7058 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
7059 TransportSecurityState::STSState sts_state;
dadriandf302c42016-06-10 18:48:597060 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:447061 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
7062 &sts_state, &pkp_state));
7063 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
dadriandf302c42016-06-10 18:48:597064 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
7065}
7066
[email protected]242d8562012-10-30 21:20:467067TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:557068 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7069 https_test_server.SetSSLConfig(
7070 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7071 https_test_server.ServeFilesFromSourceDirectory(
7072 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:467073 ASSERT_TRUE(https_test_server.Start());
7074
tommycli59a63432015-11-06 00:10:557075 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167076
[email protected]242d8562012-10-30 21:20:467077 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077078 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557079 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167080 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197081 request->Start();
Wez2a31b222018-06-07 22:07:157082 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:467083
7084 // We should have set parameters from the first header, not the second.
7085 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:077086 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:407087 TransportSecurityState::STSState sts_state;
7088 EXPECT_TRUE(
7089 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7090 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7091 sts_state.upgrade_mode);
7092 EXPECT_FALSE(sts_state.include_subdomains);
7093 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:467094}
7095
estark1614475f2016-03-10 03:46:477096// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
7097// called.
7098class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
7099 public:
7100 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:277101 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:477102
7103 void OnExpectCTFailed(const HostPortPair& host_port_pair,
7104 const GURL& report_uri,
estarkae028b462017-06-20 23:25:017105 base::Time expiration,
estarkbf1b52962017-05-05 17:05:257106 const X509Certificate* validated_certificate_chain,
7107 const X509Certificate* served_certificate_chain,
7108 const SignedCertificateTimestampAndStatusList&
7109 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:477110 num_failures_++;
7111 }
7112
7113 uint32_t num_failures() { return num_failures_; }
7114
7115 private:
7116 uint32_t num_failures_;
7117};
7118
Emily Stark627238f2017-11-29 03:29:547119// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:477120// for every certificate.
7121class MockCTPolicyEnforcer : public CTPolicyEnforcer {
7122 public:
7123 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:547124 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:277125 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:477126
Emily Stark627238f2017-11-29 03:29:547127 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:477128 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:237129 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:207130 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:477131 return default_result_;
7132 }
7133
Emily Stark627238f2017-11-29 03:29:547134 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:477135 default_result_ = default_result;
7136 }
7137
7138 private:
Emily Stark627238f2017-11-29 03:29:547139 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:477140};
7141
Emily Stark4cfecf072017-08-08 01:05:517142// Tests that Expect CT headers for the preload list are processed correctly.
7143TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:357144 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7145
estark1614475f2016-03-10 03:46:477146 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7147 https_test_server.SetSSLConfig(
7148 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7149 https_test_server.ServeFilesFromSourceDirectory(
7150 base::FilePath(kTestFilePath));
7151 ASSERT_TRUE(https_test_server.Start());
7152
7153 MockExpectCTReporter reporter;
7154 TransportSecurityState transport_security_state;
7155 transport_security_state.enable_static_expect_ct_ = true;
7156 transport_security_state.SetExpectCTReporter(&reporter);
7157
7158 // Set up a MockCertVerifier to accept the certificate that the server sends.
7159 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7160 ASSERT_TRUE(cert);
7161 MockCertVerifier cert_verifier;
7162 CertVerifyResult verify_result;
7163 verify_result.verified_cert = cert;
7164 verify_result.is_issued_by_known_root = true;
7165 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7166
rsleevi22cae1672016-12-28 01:53:367167 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
7168 // CT violation.
7169 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:477170 MockCTPolicyEnforcer ct_policy_enforcer;
7171 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547172 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:477173
7174 TestNetworkDelegate network_delegate;
7175 // Use a MockHostResolver (which by default maps all hosts to
7176 // 127.0.0.1) so that the request can be sent to a site on the Expect
7177 // CT preload list.
7178 MockHostResolver host_resolver;
7179 TestURLRequestContext context(true);
7180 context.set_host_resolver(&host_resolver);
7181 context.set_transport_security_state(&transport_security_state);
7182 context.set_network_delegate(&network_delegate);
7183 context.set_cert_verifier(&cert_verifier);
7184 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:467185 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:477186 context.Init();
7187
7188 // Now send a request to trigger the violation.
7189 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:517190 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:477191 GURL::Replacements replace_host;
7192 replace_host.SetHostStr(kExpectCTStaticHostname);
7193 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:167194 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
7195 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:477196 violating_request->Start();
Wez2a31b222018-06-07 22:07:157197 d.RunUntilComplete();
estark1614475f2016-03-10 03:46:477198
7199 EXPECT_EQ(1u, reporter.num_failures());
7200}
Emily Stark4cfecf072017-08-08 01:05:517201
7202// Tests that Expect CT HTTP headers are processed correctly.
7203TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
7204 base::test::ScopedFeatureList feature_list;
7205 feature_list.InitAndEnableFeature(
7206 TransportSecurityState::kDynamicExpectCTFeature);
7207
7208 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7209 https_test_server.SetSSLConfig(
7210 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7211 https_test_server.ServeFilesFromSourceDirectory(
7212 base::FilePath(kTestFilePath));
7213 ASSERT_TRUE(https_test_server.Start());
7214
7215 MockExpectCTReporter reporter;
7216 TransportSecurityState transport_security_state;
7217 transport_security_state.SetExpectCTReporter(&reporter);
7218
7219 // Set up a MockCertVerifier to accept the certificate that the server sends.
7220 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7221 ASSERT_TRUE(cert);
7222 MockCertVerifier cert_verifier;
7223 CertVerifyResult verify_result;
7224 verify_result.verified_cert = cert;
7225 verify_result.is_issued_by_known_root = true;
7226 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7227
7228 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7229 // compliance.
7230 DoNothingCTVerifier ct_verifier;
7231 MockCTPolicyEnforcer ct_policy_enforcer;
7232 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547233 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517234
7235 TestNetworkDelegate network_delegate;
7236 // Use a MockHostResolver (which by default maps all hosts to
7237 // 127.0.0.1).
7238 MockHostResolver host_resolver;
7239 TestURLRequestContext context(true);
7240 context.set_host_resolver(&host_resolver);
7241 context.set_transport_security_state(&transport_security_state);
7242 context.set_network_delegate(&network_delegate);
7243 context.set_cert_verifier(&cert_verifier);
7244 context.set_cert_transparency_verifier(&ct_verifier);
7245 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7246 context.Init();
7247
7248 // Now send a request to trigger the header processing.
7249 TestDelegate d;
7250 GURL url = https_test_server.GetURL("/expect-ct-header.html");
7251 std::unique_ptr<URLRequest> request(context.CreateRequest(
7252 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7253 request->Start();
Wez2a31b222018-06-07 22:07:157254 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517255
7256 TransportSecurityState::ExpectCTState state;
7257 ASSERT_TRUE(
7258 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7259 EXPECT_TRUE(state.enforce);
7260 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7261}
7262
7263// Tests that if multiple Expect CT HTTP headers are sent, they are all
7264// processed.
7265TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
7266 base::test::ScopedFeatureList feature_list;
7267 feature_list.InitAndEnableFeature(
7268 TransportSecurityState::kDynamicExpectCTFeature);
7269
7270 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7271 https_test_server.SetSSLConfig(
7272 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7273 https_test_server.ServeFilesFromSourceDirectory(
7274 base::FilePath(kTestFilePath));
7275 ASSERT_TRUE(https_test_server.Start());
7276
7277 MockExpectCTReporter reporter;
7278 TransportSecurityState transport_security_state;
7279 transport_security_state.SetExpectCTReporter(&reporter);
7280
7281 // Set up a MockCertVerifier to accept the certificate that the server sends.
7282 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7283 ASSERT_TRUE(cert);
7284 MockCertVerifier cert_verifier;
7285 CertVerifyResult verify_result;
7286 verify_result.verified_cert = cert;
7287 verify_result.is_issued_by_known_root = true;
7288 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7289
7290 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7291 // compliance.
7292 DoNothingCTVerifier ct_verifier;
7293 MockCTPolicyEnforcer ct_policy_enforcer;
7294 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547295 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517296
7297 TestNetworkDelegate network_delegate;
7298 // Use a MockHostResolver (which by default maps all hosts to
7299 // 127.0.0.1).
7300 MockHostResolver host_resolver;
7301 TestURLRequestContext context(true);
7302 context.set_host_resolver(&host_resolver);
7303 context.set_transport_security_state(&transport_security_state);
7304 context.set_network_delegate(&network_delegate);
7305 context.set_cert_verifier(&cert_verifier);
7306 context.set_cert_transparency_verifier(&ct_verifier);
7307 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7308 context.Init();
7309
7310 // Now send a request to trigger the header processing.
7311 TestDelegate d;
7312 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7313 std::unique_ptr<URLRequest> request(context.CreateRequest(
7314 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7315 request->Start();
Wez2a31b222018-06-07 22:07:157316 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517317
7318 TransportSecurityState::ExpectCTState state;
7319 ASSERT_TRUE(
7320 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7321 EXPECT_TRUE(state.enforce);
7322 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7323}
7324
mmenkefd9d15c2017-06-29 13:45:547325#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477326
Lily Chenfec60d92019-01-24 01:16:427327#if BUILDFLAG(ENABLE_REPORTING)
7328
Lily Chend3930e72019-03-01 19:31:117329TEST_F(URLRequestTestHTTP, NetworkErrorLogging_DontReportIfNetworkNotAccessed) {
7330 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7331 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7332 ASSERT_TRUE(https_test_server.Start());
7333 GURL request_url = https_test_server.GetURL("/cachetime");
7334
7335 TestNetworkErrorLoggingService nel_service;
7336 TestURLRequestContext context(true);
7337 context.set_network_error_logging_service(&nel_service);
7338 context.Init();
7339
7340 // Populate the cache.
7341 TestDelegate d;
7342 std::unique_ptr<URLRequest> request(context.CreateRequest(
7343 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7344 request->Start();
7345 d.RunUntilComplete();
7346
7347 ASSERT_EQ(1u, nel_service.errors().size());
7348 const TestNetworkErrorLoggingService::RequestDetails& error =
7349 nel_service.errors()[0];
7350 EXPECT_EQ(request_url, error.uri);
7351 EXPECT_EQ(200, error.status_code);
7352 EXPECT_EQ(OK, error.type);
7353
7354 request = context.CreateRequest(request_url, DEFAULT_PRIORITY, &d,
7355 TRAFFIC_ANNOTATION_FOR_TESTS);
7356 request->Start();
7357 d.RunUntilComplete();
7358
7359 EXPECT_FALSE(request->response_info().network_accessed);
7360 EXPECT_TRUE(request->response_info().was_cached);
7361 // No additional NEL report was generated.
7362 EXPECT_EQ(1u, nel_service.errors().size());
7363}
7364
Lily Chenfec60d92019-01-24 01:16:427365TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicSuccess) {
7366 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7367 https_test_server.ServeFilesFromSourceDirectory(
7368 base::FilePath(kTestFilePath));
7369 ASSERT_TRUE(https_test_server.Start());
7370 GURL request_url = https_test_server.GetURL("/simple.html");
7371
7372 TestNetworkErrorLoggingService nel_service;
7373 TestURLRequestContext context(true);
7374 context.set_network_error_logging_service(&nel_service);
7375 context.Init();
7376
7377 TestDelegate d;
7378 std::unique_ptr<URLRequest> request(context.CreateRequest(
7379 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7380 request->Start();
7381 d.RunUntilComplete();
7382
7383 ASSERT_EQ(1u, nel_service.errors().size());
7384 const TestNetworkErrorLoggingService::RequestDetails& error =
7385 nel_service.errors()[0];
7386 EXPECT_EQ(request_url, error.uri);
7387 EXPECT_EQ(200, error.status_code);
7388 EXPECT_EQ(OK, error.type);
7389}
7390
7391TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicError) {
7392 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7393 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7394 ASSERT_TRUE(https_test_server.Start());
7395 GURL request_url = https_test_server.GetURL("/close-socket");
7396
7397 TestNetworkErrorLoggingService nel_service;
7398 TestURLRequestContext context(true);
7399 context.set_network_error_logging_service(&nel_service);
7400 context.Init();
7401
7402 TestDelegate d;
7403 std::unique_ptr<URLRequest> request(context.CreateRequest(
7404 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7405 request->Start();
7406 d.RunUntilComplete();
7407
7408 ASSERT_EQ(1u, nel_service.errors().size());
7409 const TestNetworkErrorLoggingService::RequestDetails& error =
7410 nel_service.errors()[0];
7411 EXPECT_EQ(request_url, error.uri);
7412 EXPECT_EQ(0, error.status_code);
7413 EXPECT_EQ(ERR_EMPTY_RESPONSE, error.type);
7414}
7415
7416TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Redirect) {
7417 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7418 https_test_server.ServeFilesFromSourceDirectory(
7419 base::FilePath(kTestFilePath));
7420 ASSERT_TRUE(https_test_server.Start());
7421 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7422 GURL redirect_url = https_test_server.GetURL("/with-headers.html");
7423
7424 TestNetworkErrorLoggingService nel_service;
7425 TestURLRequestContext context(true);
7426 context.set_network_error_logging_service(&nel_service);
7427 context.Init();
7428
7429 TestDelegate d;
7430 std::unique_ptr<URLRequest> request(context.CreateRequest(
7431 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7432 request->Start();
7433 d.RunUntilComplete();
7434
7435 ASSERT_EQ(2u, nel_service.errors().size());
7436 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7437 nel_service.errors()[0];
7438 EXPECT_EQ(request_url, error1.uri);
7439 EXPECT_EQ(302, error1.status_code);
7440 EXPECT_EQ(OK, error1.type);
7441 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7442 nel_service.errors()[1];
7443 EXPECT_EQ(redirect_url, error2.uri);
7444 EXPECT_EQ(200, error2.status_code);
7445 EXPECT_EQ(OK, error2.type);
7446}
7447
Lily Chend3930e72019-03-01 19:31:117448TEST_F(URLRequestTestHTTP, NetworkErrorLogging_RedirectWithoutLocationHeader) {
7449 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7450 https_test_server.ServeFilesFromSourceDirectory(
7451 base::FilePath(kTestFilePath));
7452 ASSERT_TRUE(https_test_server.Start());
7453 GURL request_url = https_test_server.GetURL("/308-without-location-header");
7454
7455 TestNetworkErrorLoggingService nel_service;
7456 TestURLRequestContext context(true);
7457 context.set_network_error_logging_service(&nel_service);
7458 context.Init();
7459
7460 TestDelegate d;
7461 std::unique_ptr<URLRequest> request(context.CreateRequest(
7462 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7463 request->Start();
7464 d.RunUntilComplete();
7465
7466 ASSERT_EQ(1u, nel_service.errors().size());
7467 const TestNetworkErrorLoggingService::RequestDetails& error =
7468 nel_service.errors()[0];
7469 EXPECT_EQ(request_url, error.uri);
7470 EXPECT_EQ(308, error.status_code);
7471 // The body of the response was successfully read.
7472 EXPECT_EQ(OK, error.type);
7473}
7474
Lily Chenfec60d92019-01-24 01:16:427475TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Auth) {
7476 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7477 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7478 ASSERT_TRUE(https_test_server.Start());
7479 GURL request_url = https_test_server.GetURL("/auth-basic");
7480
7481 TestNetworkErrorLoggingService nel_service;
7482 TestURLRequestContext context(true);
7483 context.set_network_error_logging_service(&nel_service);
7484 context.Init();
7485
7486 TestDelegate d;
7487 d.set_credentials(AuthCredentials(kUser, kSecret));
7488 std::unique_ptr<URLRequest> request(context.CreateRequest(
7489 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7490 request->Start();
7491 d.RunUntilComplete();
7492
7493 ASSERT_EQ(2u, nel_service.errors().size());
7494 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7495 nel_service.errors()[0];
7496 EXPECT_EQ(request_url, error1.uri);
7497 EXPECT_EQ(401, error1.status_code);
7498 EXPECT_EQ(OK, error1.type);
7499 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7500 nel_service.errors()[1];
7501 EXPECT_EQ(request_url, error2.uri);
7502 EXPECT_EQ(200, error2.status_code);
7503 EXPECT_EQ(OK, error2.type);
7504}
7505
Lily Chend3930e72019-03-01 19:31:117506TEST_F(URLRequestTestHTTP, NetworkErrorLogging_304Response) {
7507 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7508 https_test_server.AddDefaultHandlers(base::FilePath(kTestFilePath));
7509 ASSERT_TRUE(https_test_server.Start());
7510 GURL request_url = https_test_server.GetURL("/auth-basic");
7511
7512 TestNetworkErrorLoggingService nel_service;
7513 TestURLRequestContext context(true);
7514 context.set_network_error_logging_service(&nel_service);
7515 context.Init();
7516
7517 // populate the cache
7518 {
7519 TestDelegate d;
7520 d.set_credentials(AuthCredentials(kUser, kSecret));
7521 std::unique_ptr<URLRequest> r(context.CreateRequest(
7522 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7523 r->Start();
7524 d.RunUntilComplete();
7525 }
7526 ASSERT_EQ(2u, nel_service.errors().size());
7527 const TestNetworkErrorLoggingService::RequestDetails& error1 =
7528 nel_service.errors()[0];
7529 EXPECT_EQ(request_url, error1.uri);
7530 EXPECT_EQ(401, error1.status_code);
7531 EXPECT_EQ(OK, error1.type);
7532 const TestNetworkErrorLoggingService::RequestDetails& error2 =
7533 nel_service.errors()[1];
7534 EXPECT_EQ(request_url, error2.uri);
7535 EXPECT_EQ(200, error2.status_code);
7536 EXPECT_EQ(OK, error2.type);
7537
7538 // repeat request with end-to-end validation. since auth-basic results in a
7539 // cachable page, we expect this test to result in a 304. in which case, the
7540 // response should be fetched from the cache.
7541 {
7542 TestDelegate d;
7543 d.set_credentials(AuthCredentials(kUser, kSecret));
7544 std::unique_ptr<URLRequest> r(context.CreateRequest(
7545 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7546 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7547 r->Start();
7548 d.RunUntilComplete();
7549
7550 // Should be the same cached document.
7551 EXPECT_TRUE(r->was_cached());
7552 }
7553 ASSERT_EQ(3u, nel_service.errors().size());
7554 const TestNetworkErrorLoggingService::RequestDetails& error3 =
7555 nel_service.errors()[2];
7556 EXPECT_EQ(request_url, error3.uri);
7557 EXPECT_EQ(304, error3.status_code);
7558 EXPECT_EQ(OK, error3.type);
7559}
7560
7561TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelInResponseStarted) {
Lily Chenfec60d92019-01-24 01:16:427562 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7563 https_test_server.ServeFilesFromSourceDirectory(
7564 base::FilePath(kTestFilePath));
7565 ASSERT_TRUE(https_test_server.Start());
7566 GURL request_url = https_test_server.GetURL("/simple.html");
7567
7568 TestNetworkErrorLoggingService nel_service;
7569 TestURLRequestContext context(true);
7570 context.set_network_error_logging_service(&nel_service);
7571 context.Init();
7572
7573 TestDelegate d;
7574 d.set_cancel_in_response_started(true);
7575 std::unique_ptr<URLRequest> request(context.CreateRequest(
7576 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7577 request->Start();
7578 d.RunUntilComplete();
7579
7580 ASSERT_EQ(1u, nel_service.errors().size());
7581 const TestNetworkErrorLoggingService::RequestDetails& error =
7582 nel_service.errors()[0];
7583 EXPECT_EQ(request_url, error.uri);
7584 EXPECT_EQ(200, error.status_code);
Lily Chend3930e72019-03-01 19:31:117585 // Headers were received and the body should have been read but was not.
7586 EXPECT_EQ(ERR_ABORTED, error.type);
7587}
7588
7589TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelOnDataReceived) {
7590 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7591 https_test_server.ServeFilesFromSourceDirectory(
7592 base::FilePath(kTestFilePath));
7593 ASSERT_TRUE(https_test_server.Start());
7594 GURL request_url = https_test_server.GetURL("/simple.html");
7595
7596 TestNetworkErrorLoggingService nel_service;
7597 TestURLRequestContext context(true);
7598 context.set_network_error_logging_service(&nel_service);
7599 context.Init();
7600
7601 TestDelegate d;
7602 d.set_cancel_in_received_data(true);
7603 std::unique_ptr<URLRequest> request(context.CreateRequest(
7604 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7605 request->Start();
7606 d.RunUntilComplete();
7607
7608 ASSERT_EQ(1u, nel_service.errors().size());
7609 const TestNetworkErrorLoggingService::RequestDetails& error =
7610 nel_service.errors()[0];
7611 EXPECT_EQ(request_url, error.uri);
7612 EXPECT_EQ(200, error.status_code);
7613 // Data was received but the body was not completely read.
7614 EXPECT_EQ(ERR_ABORTED, error.type);
7615}
7616
7617TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelRedirect) {
7618 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7619 https_test_server.ServeFilesFromSourceDirectory(
7620 base::FilePath(kTestFilePath));
7621 ASSERT_TRUE(https_test_server.Start());
7622 GURL request_url = https_test_server.GetURL("/redirect-test.html");
7623
7624 TestNetworkErrorLoggingService nel_service;
7625 TestURLRequestContext context(true);
7626 context.set_network_error_logging_service(&nel_service);
7627 context.Init();
7628
7629 TestDelegate d;
7630 d.set_cancel_in_received_redirect(true);
7631 std::unique_ptr<URLRequest> request(context.CreateRequest(
7632 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7633 request->Start();
7634 d.RunUntilComplete();
7635
7636 ASSERT_EQ(1u, nel_service.errors().size());
7637 const TestNetworkErrorLoggingService::RequestDetails& error =
7638 nel_service.errors()[0];
7639 EXPECT_EQ(request_url, error.uri);
7640 EXPECT_EQ(302, error.status_code);
7641 // A valid HTTP response was received, even though the request was cancelled.
Lily Chenfec60d92019-01-24 01:16:427642 EXPECT_EQ(OK, error.type);
7643}
7644
7645#endif // BUILDFLAG(ENABLE_REPORTING)
7646
[email protected]316c1e5e2012-09-12 15:17:447647TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557648 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447649
7650 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077651 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557652 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167653 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197654 req->Start();
Wez2a31b222018-06-07 22:07:157655 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447656
7657 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197658 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447659 EXPECT_EQ("text/html", mime_type);
7660
7661 std::string charset;
[email protected]f7022f32014-08-21 16:32:197662 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447663 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197664 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447665}
7666
[email protected]02494ec2014-05-07 15:05:297667TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347668 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347669 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347670 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027671 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347672
7673 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507674 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347675}
7676
brettwa1228ebb2016-10-28 03:51:347677#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297678TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7679 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7680 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457681 FileProtocolHandler file_protocol_handler(
7682 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297683 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7684
7685 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507686 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297687}
7688
[email protected]588614c22013-08-16 00:09:027689TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557690 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447691
7692 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077693 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557694 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167695 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197696 req->Start();
Wez2a31b222018-06-07 22:07:157697 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447698
maksim.sisovb53724b52016-09-16 05:30:507699 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307700
7701 // The redirect should have been rejected before reporting it to the caller.
7702 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447703}
brettwa1228ebb2016-10-28 03:51:347704#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447705
[email protected]588614c22013-08-16 00:09:027706TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557707 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027708
7709 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077710 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557711 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167712 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197713 req->Start();
Wez2a31b222018-06-07 22:07:157714 d.RunUntilComplete();
[email protected]588614c22013-08-16 00:09:027715
maksim.sisovb53724b52016-09-16 05:30:507716 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307717
7718 // The redirect should have been rejected before reporting it to the
7719 // caller. See https://crbug.com/723796
7720 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027721}
7722
davidbend894710b2017-06-06 19:28:307723// Test that redirects to invalid URLs are rejected. See
7724// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447725TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557726 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447727
7728 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077729 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557730 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167731 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197732 req->Start();
Wez2a31b222018-06-07 22:07:157733 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447734
davidbend894710b2017-06-06 19:28:307735 EXPECT_EQ(1, d.response_started_count());
7736 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7737
7738 // The redirect should have been rejected before reporting it to the caller.
7739 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447740}
7741
[email protected]e50efea2014-03-24 18:41:007742// Make sure redirects are cached, despite not reading their bodies.
7743TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557744 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007745 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557746 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007747
7748 {
7749 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077750 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167751 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197752 req->Start();
Wez2a31b222018-06-07 22:07:157753 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507754 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007755 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557756 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007757 }
7758
7759 {
7760 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077761 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167762 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197763 req->Start();
Wez0e717112018-06-18 23:09:227764 d.RunUntilRedirect();
[email protected]e50efea2014-03-24 18:41:007765
7766 EXPECT_EQ(1, d.received_redirect_count());
7767 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197768 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007769
Arthur Sonzognib8465ff72019-01-04 18:44:357770 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
7771 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:157772 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007773 EXPECT_EQ(1, d.received_redirect_count());
7774 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507775 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557776 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007777 }
7778}
7779
7780// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7781// when the headers are read, since the body won't have been read.
7782TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557783 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007784 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557785 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007786
7787 {
7788 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557789 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007790 default_network_delegate_.set_redirect_on_headers_received_url(
7791 redirect_to_url);
7792
7793 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077794 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167795 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197796 req->Start();
Wez2a31b222018-06-07 22:07:157797 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507798 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007799 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197800 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007801 }
7802
7803 {
7804 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077805 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167806 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197807 req->Start();
Wez2a31b222018-06-07 22:07:157808 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007809
maksim.sisovb53724b52016-09-16 05:30:507810 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197811 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007812 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197813 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007814 }
7815}
7816
[email protected]5f714132014-03-26 10:41:167817// Tests that redirection to an unsafe URL is allowed when it has been marked as
7818// safe.
Ryan Sleevia9d6aa62019-07-26 13:32:187819TEST_F(URLRequestTestHTTP, UnsafeRedirectToAllowedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557820 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167821
7822 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7823 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7824 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7825
7826 TestDelegate d;
7827 {
Ryan Sleevib8449e02018-07-15 04:31:077828 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167829 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7830 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167831
[email protected]f7022f32014-08-21 16:32:197832 r->Start();
Wez2a31b222018-06-07 22:07:157833 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167834
maksim.sisovb53724b52016-09-16 05:30:507835 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197836 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197837 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167838 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7839 }
7840}
7841
7842// Tests that a redirect to a different unsafe URL is blocked, even after adding
Ryan Sleevia9d6aa62019-07-26 13:32:187843// some other URL to the allowlist.
[email protected]5f714132014-03-26 10:41:167844TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557845 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167846
7847 GURL unsafe_url("data:text/html,something");
7848 GURL different_unsafe_url("data:text/html,something-else");
7849 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7850 default_network_delegate_.set_allowed_unsafe_redirect_url(
7851 different_unsafe_url);
7852
7853 TestDelegate d;
7854 {
Ryan Sleevib8449e02018-07-15 04:31:077855 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167856 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7857 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167858
[email protected]f7022f32014-08-21 16:32:197859 r->Start();
Wez2a31b222018-06-07 22:07:157860 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167861
maksim.sisovb53724b52016-09-16 05:30:507862 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307863
7864 // The redirect should have been rejected before reporting it to the caller.
7865 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167866 }
7867}
7868
[email protected]5f714132014-03-26 10:41:167869// Redirects from an URL with fragment to an unsafe URL with fragment should
7870// be allowed, and the reference fragment of the target URL should be preserved.
7871TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557872 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167873
tommycli59a63432015-11-06 00:10:557874 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167875 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7876 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7877
7878 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7879 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7880
7881 TestDelegate d;
7882 {
Ryan Sleevib8449e02018-07-15 04:31:077883 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167884 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167885
[email protected]f7022f32014-08-21 16:32:197886 r->Start();
Wez2a31b222018-06-07 22:07:157887 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167888
[email protected]f7022f32014-08-21 16:32:197889 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507890 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197891 EXPECT_EQ(original_url, r->original_url());
7892 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167893 }
7894}
7895
7896// When a delegate has specified a safe redirect URL, but it does not match the
7897// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147898TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557899 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167900
tommycli59a63432015-11-06 00:10:557901 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167902 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557903 GURL redirect_url(http_test_server()->GetURL("/target"));
7904 GURL expected_redirect_url(
7905 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167906
7907 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7908 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7909
7910 TestDelegate d;
7911 {
Ryan Sleevib8449e02018-07-15 04:31:077912 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167913 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167914
[email protected]f7022f32014-08-21 16:32:197915 r->Start();
Wez2a31b222018-06-07 22:07:157916 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167917
[email protected]f7022f32014-08-21 16:32:197918 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507919 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197920 EXPECT_EQ(original_url, r->original_url());
7921 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167922 }
7923}
7924
[email protected]f878230e2014-04-03 15:36:147925// When a delegate has specified a safe redirect URL, assume that the redirect
7926// URL should not be changed. In particular, the reference fragment should not
7927// be modified.
7928TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557929 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147930
tommycli59a63432015-11-06 00:10:557931 GURL original_url(
7932 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147933 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7934
7935 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7936 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7937
7938 TestDelegate d;
7939 {
Ryan Sleevib8449e02018-07-15 04:31:077940 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167941 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147942
[email protected]f7022f32014-08-21 16:32:197943 r->Start();
Wez2a31b222018-06-07 22:07:157944 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147945
[email protected]f7022f32014-08-21 16:32:197946 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507947 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197948 EXPECT_EQ(original_url, r->original_url());
7949 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147950 }
7951}
7952
7953// When a URLRequestRedirectJob is created, the redirection must be followed and
7954// the reference fragment of the target URL must not be modified.
7955TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557956 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147957
tommycli59a63432015-11-06 00:10:557958 GURL original_url(
7959 http_test_server()->GetURL("/original#should-not-be-appended"));
7960 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147961
7962 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077963 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167964 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147965
danakj8522a25b2016-04-16 00:17:367966 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197967 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427968 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7969 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:147970
[email protected]f7022f32014-08-21 16:32:197971 r->Start();
Wez2a31b222018-06-07 22:07:157972 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147973
maksim.sisovb53724b52016-09-16 05:30:507974 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197975 EXPECT_EQ(original_url, r->original_url());
7976 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147977}
7978
lizeb5120f6dc2016-02-19 09:29:447979TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
7980 ASSERT_TRUE(http_test_server()->Start());
7981
7982 const std::string referrer("foobar://totally.legit.referrer");
7983 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077984 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167985 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7986 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:447987 req->SetReferrer(referrer);
7988 req->Start();
Wez2a31b222018-06-07 22:07:157989 d.RunUntilComplete();
lizeb5120f6dc2016-02-19 09:29:447990
7991 EXPECT_EQ(std::string("None"), d.data_received());
7992}
7993
[email protected]316c1e5e2012-09-12 15:17:447994TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:557995 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447996
7997 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077998 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167999 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8000 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198001 req->SetReferrer("http://user:[email protected]/");
8002 req->Start();
Wez2a31b222018-06-07 22:07:158003 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448004
8005 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
8006}
8007
[email protected]99ecf6e2013-04-10 22:46:138008TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:558009 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138010
8011 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078012 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168013 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8014 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198015 req->SetReferrer("http://foo.com/test#fragment");
8016 req->Start();
Wez2a31b222018-06-07 22:07:158017 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138018
8019 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
8020}
8021
8022TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:558023 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138024
8025 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078026 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168027 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8028 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198029 req->SetReferrer("http://foo.com/test#fragment");
8030 req->SetReferrer("");
8031 req->Start();
Wez2a31b222018-06-07 22:07:158032 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138033
8034 EXPECT_EQ(std::string("None"), d.data_received());
8035}
8036
Mike Westfbd44112019-05-08 18:23:378037TEST_F(URLRequestTestHTTP, CapRefererDisabled) {
8038 ASSERT_TRUE(http_test_server()->Start());
8039
8040 // Create a string, and pad it out to ~10k with a very exciting path.
8041 std::string long_referer_header = "http://foo.com/";
8042 long_referer_header.resize(10000, 'a');
8043
8044 // If the feature isn't enabled, a long `referer` will remain long.
8045 TestDelegate d;
Mike West9e3affdd2019-06-07 07:43:578046 base::test::ScopedFeatureList feature_list;
8047 feature_list.InitAndDisableFeature(features::kCapRefererHeaderLength);
Mike Westfbd44112019-05-08 18:23:378048 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8049 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8050 TRAFFIC_ANNOTATION_FOR_TESTS));
8051 req->SetReferrer(long_referer_header);
8052 req->Start();
8053 d.RunUntilComplete();
8054
8055 EXPECT_EQ(long_referer_header, d.data_received());
8056}
8057
8058TEST_F(URLRequestTestHTTP, CapRefererHeaderLengthEnabled) {
8059 ASSERT_TRUE(http_test_server()->Start());
8060
8061 // Create a string, and pad it out to ~10k with a very exciting path.
8062 std::string long_referer_header = "http://foo.com/";
8063 long_referer_header.resize(10000, 'a');
8064
8065 // If the feature is enabled without params, a `referer` longer than 4096
8066 // bytes will be shortened.
8067 {
8068 TestDelegate d;
8069 base::test::ScopedFeatureList feature_list;
8070 feature_list.InitAndEnableFeature(features::kCapRefererHeaderLength);
8071
8072 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8073 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8074 TRAFFIC_ANNOTATION_FOR_TESTS));
8075 req->SetReferrer(long_referer_header);
8076 req->Start();
8077 d.RunUntilComplete();
8078
8079 EXPECT_EQ("http://foo.com/", d.data_received());
8080 }
8081
8082 // If the feature is enabled with params, they will govern the shortening
8083 // behavior as expected. The following three tests verify behavior for a
8084 // param larger than the referrer length, exactly the same as the string
8085 // length, and shorter than the string length.
8086 {
8087 TestDelegate d;
8088 std::map<std::string, std::string> params;
8089 params["MaxRefererHeaderLength"] =
8090 base::NumberToString(long_referer_header.length() + 1);
8091
8092 base::test::ScopedFeatureList feature_list;
8093 feature_list.InitAndEnableFeatureWithParameters(
8094 features::kCapRefererHeaderLength, params);
8095
8096 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8097 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8098 TRAFFIC_ANNOTATION_FOR_TESTS));
8099 req->SetReferrer(long_referer_header);
8100 req->Start();
8101 d.RunUntilComplete();
8102
8103 EXPECT_EQ(long_referer_header, d.data_received());
8104 }
8105
8106 {
8107 TestDelegate d;
8108 std::map<std::string, std::string> params;
8109 params["MaxRefererHeaderLength"] =
8110 base::NumberToString(long_referer_header.length());
8111
8112 base::test::ScopedFeatureList feature_list;
8113 feature_list.InitAndEnableFeatureWithParameters(
8114 features::kCapRefererHeaderLength, params);
8115
8116 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8117 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8118 TRAFFIC_ANNOTATION_FOR_TESTS));
8119 req->SetReferrer(long_referer_header);
8120 req->Start();
8121 d.RunUntilComplete();
8122
8123 EXPECT_EQ(long_referer_header, d.data_received());
8124 }
8125
8126 {
8127 TestDelegate d;
8128 std::map<std::string, std::string> params;
8129 params["MaxRefererHeaderLength"] =
8130 base::NumberToString(long_referer_header.length() - 1);
8131
8132 base::test::ScopedFeatureList feature_list;
8133 feature_list.InitAndEnableFeatureWithParameters(
8134 features::kCapRefererHeaderLength, params);
8135
8136 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8137 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8138 TRAFFIC_ANNOTATION_FOR_TESTS));
8139 req->SetReferrer(long_referer_header);
8140 req->Start();
8141 d.RunUntilComplete();
8142
8143 EXPECT_EQ("http://foo.com/", d.data_received());
8144 }
8145}
8146
[email protected]316c1e5e2012-09-12 15:17:448147TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:558148 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448149
8150 TestDelegate d;
8151 {
8152 d.set_cancel_in_received_redirect(true);
Ryan Sleevib8449e02018-07-15 04:31:078153 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168154 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8155 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198156 req->Start();
Wez2a31b222018-06-07 22:07:158157 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448158
8159 EXPECT_EQ(1, d.response_started_count());
8160 EXPECT_EQ(0, d.bytes_received());
8161 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508162 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448163 }
8164}
8165
8166TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:558167 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448168
8169 TestDelegate d;
8170 {
tommycli59a63432015-11-06 00:10:558171 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078172 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168173 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048174
[email protected]f7022f32014-08-21 16:32:198175 req->Start();
Wez0e717112018-06-18 23:09:228176 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:448177
8178 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:238179 EXPECT_TRUE(d.have_full_request_headers());
8180 CheckFullRequestHeaders(d.full_request_headers(), test_url);
8181 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:448182
Arthur Sonzognib8465ff72019-01-04 18:44:358183 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8184 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:158185 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448186
8187 EXPECT_EQ(1, d.response_started_count());
8188 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508189 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448190
[email protected]6cdfd7f2013-02-08 20:40:158191 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198192 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478193 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:448194 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8195
8196 std::string contents;
[email protected]82f84b92013-08-30 18:23:508197 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:448198 EXPECT_EQ(contents, d.data_received());
8199 }
8200}
8201
[email protected]79e1fd62013-06-20 06:50:048202TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:558203 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:048204
8205 TestDelegate d;
8206 {
tommycli59a63432015-11-06 00:10:558207 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078208 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168209 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048210
8211 EXPECT_FALSE(d.have_full_request_headers());
8212
[email protected]f7022f32014-08-21 16:32:198213 req->Start();
Wez0e717112018-06-18 23:09:228214 d.RunUntilRedirect();
[email protected]79e1fd62013-06-20 06:50:048215
8216 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:048217
Arthur Sonzognib8465ff72019-01-04 18:44:358218 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8219 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:158220 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:048221
tommycli59a63432015-11-06 00:10:558222 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:048223 EXPECT_EQ(1, d.response_started_count());
8224 EXPECT_TRUE(d.have_full_request_headers());
8225 CheckFullRequestHeaders(d.full_request_headers(), target_url);
8226 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508227 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:048228
8229 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198230 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478231 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:048232 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8233
8234 std::string contents;
[email protected]82f84b92013-08-30 18:23:508235 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:048236 EXPECT_EQ(contents, d.data_received());
8237 }
8238}
8239
Arthur Sonzognib8465ff72019-01-04 18:44:358240TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedHeaders) {
Chong Zhang7607f1f2018-06-01 20:52:208241 ASSERT_TRUE(http_test_server()->Start());
8242
8243 TestDelegate d;
8244 {
Chong Zhang7607f1f2018-06-01 20:52:208245 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:078246 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Chong Zhang7607f1f2018-06-01 20:52:208247 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8248
8249 // Set initial headers for the request.
8250 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8251 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8252
8253 req->Start();
Wez0e717112018-06-18 23:09:228254 d.RunUntilRedirect();
Chong Zhang7607f1f2018-06-01 20:52:208255
8256 // Initial request should only have initial headers.
8257 EXPECT_EQ(1, d.received_redirect_count());
8258 EXPECT_TRUE(d.have_full_request_headers());
8259 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8260 std::string sent_value;
8261 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8262 EXPECT_EQ("Value1", sent_value);
8263 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8264 EXPECT_EQ("Value2", sent_value);
8265 EXPECT_FALSE(sent_headers1.GetHeader("Header3", &sent_value));
8266 d.ClearFullRequestHeaders();
8267
8268 // Overwrite Header2 and add Header3.
Arthur Sonzognib8465ff72019-01-04 18:44:358269 net::HttpRequestHeaders modified_headers;
8270 modified_headers.SetHeader("Header2", "");
8271 modified_headers.SetHeader("Header3", "Value3");
Chong Zhang7607f1f2018-06-01 20:52:208272
Arthur Sonzognib8465ff72019-01-04 18:44:358273 req->FollowDeferredRedirect(base::nullopt /* removed_headers */,
8274 modified_headers);
Wez2a31b222018-06-07 22:07:158275 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:208276
8277 EXPECT_EQ(1, d.response_started_count());
8278 EXPECT_FALSE(d.received_data_before_response());
8279 EXPECT_EQ(OK, d.request_status());
8280
8281 // Redirected request should also have modified headers.
8282 EXPECT_TRUE(d.have_full_request_headers());
8283 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8284 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8285 EXPECT_EQ("Value1", sent_value);
8286 EXPECT_TRUE(sent_headers2.GetHeader("Header2", &sent_value));
8287 EXPECT_EQ("", sent_value);
8288 EXPECT_TRUE(sent_headers2.GetHeader("Header3", &sent_value));
8289 EXPECT_EQ("Value3", sent_value);
8290 }
8291}
8292
Arthur Sonzognib8465ff72019-01-04 18:44:358293TEST_F(URLRequestTestHTTP, DeferredRedirect_RemovedHeaders) {
8294 ASSERT_TRUE(http_test_server()->Start());
8295
8296 TestDelegate d;
8297 {
8298 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
8299 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8300 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8301
8302 // Set initial headers for the request.
8303 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8304 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8305
8306 req->Start();
8307 d.RunUntilRedirect();
8308
8309 // Initial request should have initial headers.
8310 EXPECT_EQ(1, d.received_redirect_count());
8311 EXPECT_TRUE(d.have_full_request_headers());
8312 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8313 std::string sent_value;
8314 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8315 EXPECT_EQ("Value1", sent_value);
8316 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8317 EXPECT_EQ("Value2", sent_value);
8318 d.ClearFullRequestHeaders();
8319
8320 // Keep Header1 and remove Header2.
8321 std::vector<std::string> removed_headers({"Header2"});
8322 req->FollowDeferredRedirect(removed_headers,
8323 base::nullopt /* modified_headers */);
8324 d.RunUntilComplete();
8325
8326 EXPECT_EQ(1, d.response_started_count());
8327 EXPECT_FALSE(d.received_data_before_response());
8328 EXPECT_EQ(OK, d.request_status());
8329
8330 // Redirected request should also have
8331 EXPECT_TRUE(d.have_full_request_headers());
8332 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8333 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8334 EXPECT_EQ("Value1", sent_value);
8335 EXPECT_FALSE(sent_headers2.GetHeader("Header2", &sent_value));
8336 }
8337}
8338
[email protected]316c1e5e2012-09-12 15:17:448339TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:558340 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448341
8342 TestDelegate d;
8343 {
Ryan Sleevib8449e02018-07-15 04:31:078344 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168345 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8346 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198347 req->Start();
Wez0e717112018-06-18 23:09:228348 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:448349
8350 EXPECT_EQ(1, d.received_redirect_count());
8351
[email protected]f7022f32014-08-21 16:32:198352 req->Cancel();
Wez2a31b222018-06-07 22:07:158353 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448354
8355 EXPECT_EQ(1, d.response_started_count());
8356 EXPECT_EQ(0, d.bytes_received());
8357 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508358 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448359 }
8360}
8361
8362TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:558363 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448364
[email protected]3b23a222013-05-15 21:33:258365 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:448366 {
8367 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078368 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558369 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168370 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448371 HttpRequestHeaders headers;
8372 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198373 req->SetExtraRequestHeaders(headers);
8374 req->Start();
Wez2a31b222018-06-07 22:07:158375 d.RunUntilComplete();
[email protected]3b23a222013-05-15 21:33:258376
8377 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198378 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258379 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448380 }
8381
[email protected]3b23a222013-05-15 21:33:258382 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:448383 {
8384 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078385 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558386 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168387 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448388 HttpRequestHeaders headers;
8389 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198390 req->SetExtraRequestHeaders(headers);
8391 req->Start();
Wez2a31b222018-06-07 22:07:158392 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448393
[email protected]f7022f32014-08-21 16:32:198394 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258395
8396 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198397 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258398 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:448399 }
8400
[email protected]3b23a222013-05-15 21:33:258401 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:448402 {
8403 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078404 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558405 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168406 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448407 HttpRequestHeaders headers;
8408 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:198409 req->SetExtraRequestHeaders(headers);
8410 req->Start();
Wez2a31b222018-06-07 22:07:158411 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448412
[email protected]f7022f32014-08-21 16:32:198413 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258414
8415 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198416 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258417 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448418 }
8419}
8420
8421TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:558422 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448423
8424 // populate the cache
8425 {
8426 TestDelegate d;
8427 d.set_credentials(AuthCredentials(kUser, kSecret));
8428
Ryan Sleevib8449e02018-07-15 04:31:078429 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168430 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8431 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198432 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448433
Wez2a31b222018-06-07 22:07:158434 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448435
8436 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8437 }
8438
8439 // repeat request with end-to-end validation. since auth-basic results in a
8440 // cachable page, we expect this test to result in a 304. in which case, the
8441 // response should be fetched from the cache.
8442 {
8443 TestDelegate d;
8444 d.set_credentials(AuthCredentials(kUser, kSecret));
8445
Ryan Sleevib8449e02018-07-15 04:31:078446 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168447 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8448 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198449 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8450 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448451
Wez2a31b222018-06-07 22:07:158452 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448453
8454 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8455
8456 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198457 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:448458 }
8459}
8460
8461// Check that Set-Cookie headers in 401 responses are respected.
8462// http://crbug.com/6450
8463TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:558464 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448465
8466 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:558467 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:448468
8469 // Request a page that will give a 401 containing a Set-Cookie header.
8470 // Verify that when the transaction is restarted, it includes the new cookie.
8471 {
[email protected]ceefd7fd2012-11-29 00:36:248472 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448473 TestURLRequestContext context(true);
8474 context.set_network_delegate(&network_delegate);
8475 context.Init();
8476
8477 TestDelegate d;
8478 d.set_credentials(AuthCredentials(kUser, kSecret));
8479
danakj8522a25b2016-04-16 00:17:368480 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:168481 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
8482 TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298483 r->set_site_for_cookies(url_requiring_auth);
[email protected]f7022f32014-08-21 16:32:198484 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448485
Wez2a31b222018-06-07 22:07:158486 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448487
8488 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8489
8490 // Make sure we sent the cookie in the restarted transaction.
8491 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8492 != std::string::npos);
8493 }
8494
8495 // Same test as above, except this time the restart is initiated earlier
8496 // (without user intervention since identity is embedded in the URL).
8497 {
[email protected]ceefd7fd2012-11-29 00:36:248498 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448499 TestURLRequestContext context(true);
8500 context.set_network_delegate(&network_delegate);
8501 context.Init();
8502
8503 TestDelegate d;
8504
8505 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:188506 replacements.SetUsernameStr("user2");
8507 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:448508 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
8509
rhalavatib7bd7c792017-04-27 05:25:168510 std::unique_ptr<URLRequest> r(context.CreateRequest(
8511 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298512 r->set_site_for_cookies(url_with_identity);
[email protected]f7022f32014-08-21 16:32:198513 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448514
Wez2a31b222018-06-07 22:07:158515 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448516
8517 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
8518
8519 // Make sure we sent the cookie in the restarted transaction.
8520 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8521 != std::string::npos);
8522 }
8523}
8524
Matt Menke0743e342019-06-11 20:48:108525TEST_F(URLRequestTestHTTP, BasicAuthWithCookiesCancelAuth) {
8526 ASSERT_TRUE(http_test_server()->Start());
8527
8528 GURL url_requiring_auth =
8529 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
8530
8531 // Request a page that will give a 401 containing a Set-Cookie header.
8532 // Verify that cookies are set before credentials are provided, and then
8533 // cancelling auth does not result in setting the cookies again.
8534 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8535 TestURLRequestContext context(true);
8536 context.set_network_delegate(&network_delegate);
8537 context.Init();
8538
8539 TestDelegate d;
8540
8541 EXPECT_TRUE(GetAllCookies(&context).empty());
8542
8543 std::unique_ptr<URLRequest> r(context.CreateRequest(
8544 url_requiring_auth, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8545 r->set_site_for_cookies(url_requiring_auth);
8546 r->Start();
8547 d.RunUntilAuthRequired();
8548
8549 // Cookie should have been set.
8550 EXPECT_EQ(1, network_delegate.set_cookie_count());
8551 CookieList cookies = GetAllCookies(&context);
8552 ASSERT_EQ(1u, cookies.size());
8553 EXPECT_EQ("got_challenged", cookies[0].Name());
8554 EXPECT_EQ("true", cookies[0].Value());
8555
8556 // Delete cookie.
8557 context.cookie_store()->DeleteAllAsync(CookieStore::DeleteCallback());
8558
8559 // Cancel auth and continue the request.
8560 r->CancelAuth();
8561 d.RunUntilComplete();
8562 ASSERT_TRUE(r->response_headers());
8563 EXPECT_EQ(401, r->response_headers()->response_code());
8564
8565 // Cookie should not have been set again.
8566 EXPECT_TRUE(GetAllCookies(&context).empty());
8567 EXPECT_EQ(1, network_delegate.set_cookie_count());
8568}
8569
Maks Orlovich15714232019-06-16 23:14:098570TEST_F(URLRequestTest, ReportCookieActivity) {
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548571 HttpTestServer test_server;
8572 ASSERT_TRUE(test_server.Start());
8573
8574 FilteringTestLayeredNetworkDelegate network_delegate(
8575 std::make_unique<TestNetworkDelegate>());
8576 network_delegate.SetCookieFilter("not_stored_cookie");
8577 network_delegate.set_block_get_cookies();
8578 TestURLRequestContext context(true);
8579 context.set_network_delegate(&network_delegate);
8580 context.Init();
Maks Orlovich15714232019-06-16 23:14:098581 // Make sure cookies blocked from being stored are caught, and those that are
8582 // accepted are reported as well.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548583 {
8584 TestDelegate d;
Maks Orlovich15714232019-06-16 23:14:098585 GURL test_url = test_server.GetURL(
8586 "/set-cookie?not_stored_cookie=true&"
8587 "stored_cookie=tasty"
8588 "&path_cookie=narrow;path=/set-cookie");
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548589 std::unique_ptr<URLRequest> req(context.CreateRequest(
Lily Chen3ac7cf42019-05-30 23:29:298590 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8591 req->set_site_for_cookies(test_url);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548592 req->Start();
8593 d.RunUntilComplete();
8594
Maks Orlovich15714232019-06-16 23:14:098595 ASSERT_EQ(3u, req->maybe_stored_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548596 EXPECT_EQ("not_stored_cookie",
Maks Orlovich15714232019-06-16 23:14:098597 req->maybe_stored_cookies()[0].cookie->Name());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548598 EXPECT_EQ(
8599 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
Maks Orlovich15714232019-06-16 23:14:098600 req->maybe_stored_cookies()[0].status);
8601 EXPECT_EQ("stored_cookie", req->maybe_stored_cookies()[1].cookie->Name());
8602 EXPECT_EQ(net::CanonicalCookie::CookieInclusionStatus::INCLUDE,
8603 req->maybe_stored_cookies()[1].status);
8604 EXPECT_EQ("stored_cookie", req->maybe_stored_cookies()[1].cookie->Name());
8605 EXPECT_EQ(net::CanonicalCookie::CookieInclusionStatus::INCLUDE,
8606 req->maybe_stored_cookies()[2].status);
8607 EXPECT_EQ("path_cookie", req->maybe_stored_cookies()[2].cookie->Name());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548608 }
8609 {
8610 TestDelegate d;
8611 // Make sure cookies blocked from being sent are caught.
Lily Chen3ac7cf42019-05-30 23:29:298612 GURL test_url = test_server.GetURL("/echoheader?Cookie");
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548613 std::unique_ptr<URLRequest> req(context.CreateRequest(
Lily Chen3ac7cf42019-05-30 23:29:298614 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8615 req->set_site_for_cookies(test_url);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548616 req->Start();
8617 d.RunUntilComplete();
8618
Maks Orlovich15714232019-06-16 23:14:098619 EXPECT_TRUE(d.data_received().find("stored_cookie=tasty") ==
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548620 std::string::npos);
8621
Maks Orlovich15714232019-06-16 23:14:098622 ASSERT_EQ(2u, req->maybe_sent_cookies().size());
8623 EXPECT_EQ("path_cookie", req->maybe_sent_cookies()[0].cookie.Name());
8624 EXPECT_EQ(net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_NOT_ON_PATH,
8625 req->maybe_sent_cookies()[0].status);
8626 EXPECT_EQ("stored_cookie", req->maybe_sent_cookies()[1].cookie.Name());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548627 EXPECT_EQ(
8628 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
Maks Orlovich15714232019-06-16 23:14:098629 req->maybe_sent_cookies()[1].status);
8630 }
8631
8632 network_delegate.unset_block_get_cookies();
8633 {
8634 // Now with sending cookies re-enabled, it should actually be sent.
8635 TestDelegate d;
8636 GURL test_url = test_server.GetURL("/echoheader?Cookie");
8637 std::unique_ptr<URLRequest> req(context.CreateRequest(
8638 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8639 req->set_site_for_cookies(test_url);
8640 req->Start();
8641 d.RunUntilComplete();
8642
8643 EXPECT_TRUE(d.data_received().find("stored_cookie=tasty") !=
8644 std::string::npos);
8645
8646 ASSERT_EQ(2u, req->maybe_sent_cookies().size());
8647 EXPECT_EQ("path_cookie", req->maybe_sent_cookies()[0].cookie.Name());
8648 EXPECT_EQ(net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_NOT_ON_PATH,
8649 req->maybe_sent_cookies()[0].status);
8650 EXPECT_EQ("stored_cookie", req->maybe_sent_cookies()[1].cookie.Name());
8651 EXPECT_EQ(net::CanonicalCookie::CookieInclusionStatus::INCLUDE,
8652 req->maybe_sent_cookies()[1].status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548653 }
8654}
8655
Maks Orlovich0d9da122019-06-13 20:14:438656TEST_F(URLRequestTestHTTP, AuthChallengeCancelCookieCollect) {
8657 ASSERT_TRUE(http_test_server()->Start());
8658 GURL url_requiring_auth =
8659 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
8660
8661 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8662 std::make_unique<TestNetworkDelegate>());
8663 filtering_network_delegate.SetCookieFilter("got_challenged");
8664 TestURLRequestContext context(true);
8665 context.set_network_delegate(&filtering_network_delegate);
8666 context.Init();
8667
8668 TestDelegate delegate;
8669
8670 std::unique_ptr<URLRequest> request(
8671 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &delegate,
8672 TRAFFIC_ANNOTATION_FOR_TESTS));
8673 request->set_site_for_cookies(url_requiring_auth);
8674 request->Start();
8675
8676 delegate.RunUntilAuthRequired();
Maks Orlovich15714232019-06-16 23:14:098677 ASSERT_EQ(1u, request->maybe_stored_cookies().size());
Maks Orlovich0d9da122019-06-13 20:14:438678 EXPECT_EQ(
8679 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
Maks Orlovich15714232019-06-16 23:14:098680 request->maybe_stored_cookies()[0].status);
Maks Orlovich0d9da122019-06-13 20:14:438681 EXPECT_EQ("got_challenged=true",
Maks Orlovich15714232019-06-16 23:14:098682 request->maybe_stored_cookies()[0].cookie_string);
Maks Orlovich0d9da122019-06-13 20:14:438683
8684 // This shouldn't DCHECK-fail.
8685 request->CancelAuth();
8686 delegate.RunUntilComplete();
8687}
8688
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548689TEST_F(URLRequestTestHTTP, AuthChallengeWithFilteredCookies) {
Aaron Tagliaboschi028009e2019-03-07 16:28:068690 ASSERT_TRUE(http_test_server()->Start());
8691
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548692 GURL url_requiring_auth =
8693 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
8694 GURL url_requiring_auth_wo_cookies =
8695 http_test_server()->GetURL("/auth-basic");
Maks Orlovich15714232019-06-16 23:14:098696 // Check maybe_stored_cookies is populated first round trip, and cleared on
8697 // the second.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548698 {
8699 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8700 std::make_unique<TestNetworkDelegate>());
8701 filtering_network_delegate.SetCookieFilter("got_challenged");
8702 TestURLRequestContext context(true);
8703 context.set_network_delegate(&filtering_network_delegate);
8704 context.Init();
Aaron Tagliaboschi028009e2019-03-07 16:28:068705
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548706 TestDelegate delegate;
Aaron Tagliaboschi028009e2019-03-07 16:28:068707
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548708 std::unique_ptr<URLRequest> request(
8709 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &delegate,
8710 TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298711 request->set_site_for_cookies(url_requiring_auth);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548712 request->Start();
Aaron Tagliaboschi028009e2019-03-07 16:28:068713
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548714 delegate.RunUntilAuthRequired();
8715 // Make sure it was blocked once.
8716 EXPECT_EQ(1, filtering_network_delegate.blocked_set_cookie_count());
Aaron Tagliaboschi028009e2019-03-07 16:28:068717
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548718 // The number of cookies blocked from the most recent round trip.
Maks Orlovich15714232019-06-16 23:14:098719 ASSERT_EQ(1u, request->maybe_stored_cookies().size());
8720 EXPECT_EQ(
8721 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
8722 request->maybe_stored_cookies().front().status);
Aaron Tagliaboschi028009e2019-03-07 16:28:068723
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548724 // Now check the second round trip
8725 request->SetAuth(AuthCredentials(kUser, kSecret));
8726 delegate.RunUntilComplete();
8727 EXPECT_THAT(delegate.request_status(), IsOk());
Aaron Tagliaboschi028009e2019-03-07 16:28:068728
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548729 // There are DCHECKs in URLRequestHttpJob that would fail if
Maks Orlovich15714232019-06-16 23:14:098730 // maybe_sent_cookies and maybe_stored_cookies were not cleared properly.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548731
8732 // Make sure the cookie was actually filtered and not sent.
8733 EXPECT_EQ(std::string::npos,
8734 delegate.data_received().find("Cookie: got_challenged=true"));
8735
Maks Orlovich15714232019-06-16 23:14:098736 // The number of cookies that most recent round trip tried to set.
8737 ASSERT_EQ(0u, request->maybe_stored_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548738 }
8739
Maks Orlovich15714232019-06-16 23:14:098740 // Check maybe_sent_cookies on first round trip (and cleared for the second).
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548741 {
8742 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
8743 std::make_unique<TestNetworkDelegate>());
8744 filtering_network_delegate.set_block_get_cookies();
8745 TestURLRequestContext context(true);
8746 context.set_network_delegate(&filtering_network_delegate);
8747
8748 std::unique_ptr<CookieMonster> cm =
8749 std::make_unique<CookieMonster>(nullptr, nullptr);
8750 cm->SetCookieWithOptionsAsync(url_requiring_auth_wo_cookies,
8751 "another_cookie=true", CookieOptions(),
8752 CookieStore::SetCookiesCallback());
8753 context.set_cookie_store(cm.get());
8754 context.Init();
8755
8756 TestDelegate delegate;
8757
8758 std::unique_ptr<URLRequest> request(
8759 context.CreateRequest(url_requiring_auth_wo_cookies, DEFAULT_PRIORITY,
8760 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
Lily Chen3ac7cf42019-05-30 23:29:298761 request->set_site_for_cookies(url_requiring_auth_wo_cookies);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548762 request->Start();
8763
8764 delegate.RunUntilAuthRequired();
8765
Maks Orlovich15714232019-06-16 23:14:098766 ASSERT_EQ(1u, request->maybe_sent_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548767 EXPECT_EQ("another_cookie",
Maks Orlovich15714232019-06-16 23:14:098768 request->maybe_sent_cookies().front().cookie.Name());
8769 EXPECT_EQ("true", request->maybe_sent_cookies().front().cookie.Value());
8770 EXPECT_EQ(
8771 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
8772 request->maybe_sent_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548773
Maks Orlovich15714232019-06-16 23:14:098774 // Check maybe_sent_cookies on second roundtrip.
8775 request->set_maybe_sent_cookies({});
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548776 cm->DeleteAllAsync(CookieStore::DeleteCallback());
8777 cm->SetCookieWithOptionsAsync(url_requiring_auth_wo_cookies,
8778 "one_more_cookie=true", CookieOptions(),
8779 CookieStore::SetCookiesCallback());
8780
8781 request->SetAuth(AuthCredentials(kUser, kSecret));
8782 delegate.RunUntilComplete();
8783 EXPECT_THAT(delegate.request_status(), IsOk());
8784
8785 // There are DCHECKs in URLRequestHttpJob that would fail if
Maks Orlovich15714232019-06-16 23:14:098786 // maybe_sent_cookies and maybe_stored_cookies were not cleared properly.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548787
8788 // Make sure the cookie was actually filtered.
8789 EXPECT_EQ(std::string::npos,
8790 delegate.data_received().find("Cookie: one_more_cookie=true"));
8791 // got_challenged was set after the first request and blocked on the second,
8792 // so it should only have been blocked this time
8793 EXPECT_EQ(2, filtering_network_delegate.blocked_get_cookie_count());
8794
8795 // // The number of cookies blocked from the most recent round trip.
Maks Orlovich15714232019-06-16 23:14:098796 ASSERT_EQ(1u, request->maybe_sent_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548797 EXPECT_EQ("one_more_cookie",
Maks Orlovich15714232019-06-16 23:14:098798 request->maybe_sent_cookies().front().cookie.Name());
8799 EXPECT_EQ(
8800 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
8801 request->maybe_sent_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:548802 }
Aaron Tagliaboschi028009e2019-03-07 16:28:068803}
8804
[email protected]58e32bb2013-01-21 18:23:258805// Tests that load timing works as expected with auth and the cache.
8806TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:558807 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:258808
8809 // populate the cache
8810 {
8811 TestDelegate d;
8812 d.set_credentials(AuthCredentials(kUser, kSecret));
8813
Ryan Sleevib8449e02018-07-15 04:31:078814 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168815 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8816 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198817 r->Start();
[email protected]58e32bb2013-01-21 18:23:258818
Wez2a31b222018-06-07 22:07:158819 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258820
8821 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8822
8823 LoadTimingInfo load_timing_info_before_auth;
8824 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
8825 &load_timing_info_before_auth));
8826 TestLoadTimingNotReused(load_timing_info_before_auth,
8827 CONNECT_TIMING_HAS_DNS_TIMES);
8828
8829 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198830 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:258831 // The test server does not support keep alive sockets, so the second
8832 // request with auth should use a new socket.
8833 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
8834 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
8835 load_timing_info.socket_log_id);
8836 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
8837 load_timing_info.connect_timing.connect_start);
8838 }
8839
[email protected]3b23a222013-05-15 21:33:258840 // Repeat request with end-to-end validation. Since auth-basic results in a
8841 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258842 // response should be fetched from the cache.
8843 {
8844 TestDelegate d;
8845 d.set_credentials(AuthCredentials(kUser, kSecret));
8846
Ryan Sleevib8449e02018-07-15 04:31:078847 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168848 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8849 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198850 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8851 r->Start();
[email protected]58e32bb2013-01-21 18:23:258852
Wez2a31b222018-06-07 22:07:158853 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258854
8855 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8856
8857 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198858 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258859
[email protected]3b23a222013-05-15 21:33:258860 // Since there was a request that went over the wire, the load timing
8861 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258862 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198863 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258864 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258865 }
8866}
8867
[email protected]316c1e5e2012-09-12 15:17:448868// In this test, we do a POST which the server will 302 redirect.
8869// The subsequent transaction should use GET, and should not send the
8870// Content-Type header.
8871// http://code.google.com/p/chromium/issues/detail?id=843
8872TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558873 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448874
8875 const char kData[] = "hello world";
8876
8877 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078878 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168879 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8880 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198881 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078882 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448883
8884 // Set headers (some of which are specific to the POST).
8885 HttpRequestHeaders headers;
Yeol45b9e0a2018-07-27 02:03:298886 headers.SetHeader("Content-Type",
8887 "multipart/form-data;"
8888 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ");
8889 headers.SetHeader("Accept",
8890 "text/xml,application/xml,application/xhtml+xml,"
8891 "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
8892 headers.SetHeader("Accept-Language", "en-US,en");
8893 headers.SetHeader("Accept-Charset", "ISO-8859-1,*,utf-8");
8894 headers.SetHeader("Content-Length", "11");
8895 headers.SetHeader("Origin", "http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198896 req->SetExtraRequestHeaders(headers);
8897 req->Start();
Wez2a31b222018-06-07 22:07:158898 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448899
8900 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198901 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448902 EXPECT_EQ("text/html", mime_type);
8903
8904 const std::string& data = d.data_received();
8905
8906 // Check that the post-specific headers were stripped:
8907 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8908 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498909 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448910
8911 // These extra request headers should not have been stripped.
8912 EXPECT_TRUE(ContainsString(data, "Accept:"));
8913 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8914 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8915}
8916
jww5fe460ff2015-03-28 00:22:518917// The following tests check that we handle mutating the request for HTTP
8918// redirects as expected.
8919// See https://crbug.com/56373, https://crbug.com/102130, and
8920// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448921
8922TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558923 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448924
tommycli59a63432015-11-06 00:10:558925 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518926 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558927 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448928
8929 HTTPRedirectMethodTest(url, "POST", "GET", true);
8930 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8931 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518932
8933 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8934 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498935 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8936 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8937 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408938 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8939 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448940}
8941
8942TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558943 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448944
tommycli59a63432015-11-06 00:10:558945 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518946 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558947 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448948
8949 HTTPRedirectMethodTest(url, "POST", "GET", true);
8950 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8951 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518952
8953 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8954 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498955 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8956 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8957 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408958 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8959 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448960}
8961
8962TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558963 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448964
tommycli59a63432015-11-06 00:10:558965 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518966 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558967 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448968
8969 HTTPRedirectMethodTest(url, "POST", "GET", true);
8970 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8971 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518972
Alex Clarke1e08882b32017-10-06 14:22:408973 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8974 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8975 std::string());
8976 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8977 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8978 std::string());
jww5fe460ff2015-03-28 00:22:518979 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8980 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408981 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8982 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8983 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8984 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8985 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498986 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8987 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8988 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408989 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
8990 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:448991}
8992
8993TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558994 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448995
tommycli59a63432015-11-06 00:10:558996 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518997 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558998 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448999
9000 HTTPRedirectMethodTest(url, "POST", "POST", true);
9001 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
9002 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:519003
9004 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
9005 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
9006 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
9007 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:409008 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
9009 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:449010}
9011
[email protected]0a17aab32014-04-24 03:32:379012TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:559013 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:379014
tommycli59a63432015-11-06 00:10:559015 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:519016 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:559017 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:379018
9019 HTTPRedirectMethodTest(url, "POST", "POST", true);
9020 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
9021 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:519022
9023 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
9024 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
9025 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
9026 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:409027 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
9028 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:379029}
9030
9031// Make sure that 308 responses without bodies are not treated as redirects.
9032// Certain legacy apis that pre-date the response code expect this behavior
9033// (Like Google Drive).
9034TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:559035 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:379036
9037 TestDelegate d;
tommycli59a63432015-11-06 00:10:559038 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:379039
Ryan Sleevib8449e02018-07-15 04:31:079040 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169041 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:379042
[email protected]f7022f32014-08-21 16:32:199043 request->Start();
Wez2a31b222018-06-07 22:07:159044 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:509045 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:379046 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:199047 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:379048 EXPECT_EQ("This is not a redirect.", d.data_received());
9049}
9050
[email protected]f878230e2014-04-03 15:36:149051TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:559052 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:149053
tommycli59a63432015-11-06 00:10:559054 GURL original_url(
9055 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
9056 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:149057
9058 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:149059 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9060 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:149061
Josh Karlinbe37f912018-12-07 01:05:149062 r->Start();
9063 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:149064
Josh Karlinbe37f912018-12-07 01:05:149065 EXPECT_EQ(2U, r->url_chain().size());
9066 EXPECT_EQ(OK, d.request_status());
9067 EXPECT_EQ(original_url, r->original_url());
9068 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:149069}
9070
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549071TEST_F(URLRequestTestHTTP, RedirectWithFilteredCookies) {
9072 ASSERT_TRUE(http_test_server()->Start());
9073
9074 // FilteringTestLayeredNetworkDelegate filters by name, so the names of the
9075 // two cookies have to be the same. The values have been set to different
9076 // strings (the value of the server-redirect cookies is "true" and set-cookie
9077 // is "other") to differentiate between the two round trips.
9078 GURL redirect_to(
9079 http_test_server()->GetURL("/set-cookie?server-redirect=other"));
9080
9081 GURL original_url(http_test_server()->GetURL("/server-redirect-with-cookie?" +
9082 redirect_to.spec()));
9083
9084 GURL original_url_wo_cookie(
9085 http_test_server()->GetURL("/server-redirect?" + redirect_to.spec()));
Maks Orlovich15714232019-06-16 23:14:099086 // Check maybe_stored_cookies on first round trip.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549087 {
9088 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
9089 std::make_unique<TestNetworkDelegate>()); // Must outlive URLRequest.
9090 filtering_network_delegate.SetCookieFilter(
9091 "server-redirect"); // Filter the cookie server-redirect sets.
9092 TestURLRequestContext context(true);
9093 context.set_network_delegate(&filtering_network_delegate);
9094 context.Init();
9095
9096 TestDelegate delegate;
9097 std::unique_ptr<URLRequest> request(
9098 context.CreateRequest(original_url, DEFAULT_PRIORITY, &delegate,
9099 TRAFFIC_ANNOTATION_FOR_TESTS));
9100
Lily Chen3ac7cf42019-05-30 23:29:299101 request->set_site_for_cookies(original_url);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549102 request->Start();
9103 delegate.RunUntilRedirect();
9104
9105 // Make sure it was blocked once.
9106 EXPECT_EQ(1, filtering_network_delegate.blocked_set_cookie_count());
9107
9108 // The number of cookies blocked from the most recent round trip.
Maks Orlovich15714232019-06-16 23:14:099109 ASSERT_EQ(1u, request->maybe_stored_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549110 EXPECT_EQ("server-redirect",
Maks Orlovich15714232019-06-16 23:14:099111 request->maybe_stored_cookies().front().cookie->Name());
9112 EXPECT_EQ("true", request->maybe_stored_cookies().front().cookie->Value());
9113 EXPECT_EQ(
9114 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
9115 request->maybe_stored_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549116
Maks Orlovich15714232019-06-16 23:14:099117 // Check maybe_stored_cookies on second round trip (and clearing from the
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549118 // first).
9119 request->FollowDeferredRedirect(base::nullopt, base::nullopt);
9120 delegate.RunUntilComplete();
9121 EXPECT_THAT(delegate.request_status(), IsOk());
9122
9123 // There are DCHECKs in URLRequestHttpJob that would fail if
Maks Orlovich15714232019-06-16 23:14:099124 // maybe_sent_cookies and maybe_stored_cookies we not cleared properly.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549125
9126 // Make sure it was blocked twice.
9127 EXPECT_EQ(2, filtering_network_delegate.blocked_set_cookie_count());
9128
9129 // The number of cookies blocked from the most recent round trip.
Maks Orlovich15714232019-06-16 23:14:099130 ASSERT_EQ(1u, request->maybe_stored_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549131 EXPECT_EQ("server-redirect",
Maks Orlovich15714232019-06-16 23:14:099132 request->maybe_stored_cookies().front().cookie->Name());
9133 EXPECT_EQ("other", request->maybe_stored_cookies().front().cookie->Value());
9134 EXPECT_EQ(
9135 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
9136 request->maybe_stored_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549137 }
9138
Maks Orlovich15714232019-06-16 23:14:099139 // Check maybe_sent_cookies on first round trip.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549140 {
9141 FilteringTestLayeredNetworkDelegate filtering_network_delegate(
9142 std::make_unique<TestNetworkDelegate>());
9143 filtering_network_delegate.set_block_get_cookies();
9144 TestURLRequestContext context(true);
9145 context.set_network_delegate(&filtering_network_delegate);
9146 std::unique_ptr<CookieMonster> cm =
9147 std::make_unique<CookieMonster>(nullptr, nullptr);
9148 cm->SetCookieWithOptionsAsync(original_url, "another_cookie=true",
9149 CookieOptions(),
9150 CookieStore::SetCookiesCallback());
9151 context.set_cookie_store(cm.get());
9152 context.Init();
9153
9154 TestDelegate delegate;
9155 std::unique_ptr<URLRequest> request(
9156 context.CreateRequest(original_url_wo_cookie, DEFAULT_PRIORITY,
9157 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
9158
Lily Chen3ac7cf42019-05-30 23:29:299159 request->set_site_for_cookies(original_url_wo_cookie);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549160 request->Start();
9161
9162 delegate.RunUntilRedirect();
9163
Maks Orlovich15714232019-06-16 23:14:099164 ASSERT_EQ(1u, request->maybe_sent_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549165 EXPECT_EQ("another_cookie",
Maks Orlovich15714232019-06-16 23:14:099166 request->maybe_sent_cookies().front().cookie.Name());
9167 EXPECT_EQ(
9168 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
9169 request->maybe_sent_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549170
Maks Orlovich15714232019-06-16 23:14:099171 // Check maybe_sent_cookies on second round trip
9172 request->set_maybe_sent_cookies({});
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549173 cm->DeleteAllAsync(CookieStore::DeleteCallback());
9174 cm->SetCookieWithOptionsAsync(original_url_wo_cookie,
9175 "one_more_cookie=true", CookieOptions(),
9176 CookieStore::SetCookiesCallback());
9177
9178 request->FollowDeferredRedirect(base::nullopt, base::nullopt);
9179 delegate.RunUntilComplete();
9180 EXPECT_THAT(delegate.request_status(), IsOk());
9181
9182 // There are DCHECKs in URLRequestHttpJob that would fail if
Maks Orlovich15714232019-06-16 23:14:099183 // maybe_sent_cookies and maybe_stored_cookies we not cleared properly.
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549184
9185 EXPECT_EQ(2, filtering_network_delegate.blocked_get_cookie_count());
9186
9187 // The number of cookies blocked from the most recent round trip.
Maks Orlovich15714232019-06-16 23:14:099188 ASSERT_EQ(1u, request->maybe_sent_cookies().size());
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549189 EXPECT_EQ("one_more_cookie",
Maks Orlovich15714232019-06-16 23:14:099190 request->maybe_sent_cookies().front().cookie.Name());
9191 EXPECT_EQ("true", request->maybe_sent_cookies().front().cookie.Value());
9192 EXPECT_EQ(
9193 net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
9194 request->maybe_sent_cookies().front().status);
Aaron Tagliaboschifd4f3f012019-05-30 23:05:549195 }
9196}
9197
[email protected]cba24642014-08-15 20:49:599198TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:559199 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:599200
tommycli59a63432015-11-06 00:10:559201 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:599202 GURL first_party_url("http://example.com");
9203
9204 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:149205 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9206 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9207 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:599208
Josh Karlinbe37f912018-12-07 01:05:149209 r->Start();
9210 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:599211
Josh Karlinbe37f912018-12-07 01:05:149212 EXPECT_EQ(2U, r->url_chain().size());
9213 EXPECT_EQ(OK, d.request_status());
9214 EXPECT_EQ(first_party_url, r->site_for_cookies());
9215}
9216
9217TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameOrigin) {
9218 ASSERT_TRUE(http_test_server()->Start());
9219
9220 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9221 url::Origin top_frame_origin =
9222 url::Origin::Create(GURL("http://example.com"));
9223 TestDelegate d;
9224
9225 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9226 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9227 r->set_top_frame_origin(top_frame_origin);
9228
9229 r->Start();
9230 d.RunUntilComplete();
9231
9232 EXPECT_EQ(2U, r->url_chain().size());
9233 EXPECT_EQ(OK, d.request_status());
9234 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
9235}
9236
9237TEST_F(URLRequestTestHTTP, RedirectPreserveUnsetTopFrameOrigin) {
9238 ASSERT_TRUE(http_test_server()->Start());
9239
9240 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9241 TestDelegate d;
9242
9243 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9244 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9245 // Since we're not setting a top frame origin, we wouldn't expect one after
9246 // the redirect.
9247 r->Start();
9248 d.RunUntilComplete();
9249
9250 EXPECT_EQ(2U, r->url_chain().size());
9251 EXPECT_EQ(OK, d.request_status());
9252 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:599253}
9254
Josh Karlinf3caee1642018-12-10 22:54:279255TEST_F(URLRequestTestHTTP, RedirectPreserveTopFrameURL) {
9256 ASSERT_TRUE(http_test_server()->Start());
9257
9258 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9259 url::Origin top_frame_origin =
9260 url::Origin::Create(GURL("http://example.com"));
9261 TestDelegate d;
9262 {
9263 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9264 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9265 r->set_top_frame_origin(top_frame_origin);
9266
9267 r->Start();
9268 d.RunUntilComplete();
9269
9270 EXPECT_EQ(2U, r->url_chain().size());
9271 EXPECT_EQ(OK, d.request_status());
9272 EXPECT_EQ(top_frame_origin, *r->top_frame_origin());
9273 }
9274}
9275
[email protected]cba24642014-08-15 20:49:599276TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:559277 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:599278
tommycli59a63432015-11-06 00:10:559279 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:599280 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:559281 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:599282
9283 TestDelegate d;
Josh Karlinbe37f912018-12-07 01:05:149284
Ryan Sleevib8449e02018-07-15 04:31:079285 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169286 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:469287 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:199288 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:599289 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
9290
[email protected]f7022f32014-08-21 16:32:199291 r->Start();
Wez2a31b222018-06-07 22:07:159292 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:599293
[email protected]f7022f32014-08-21 16:32:199294 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:509295 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:469296 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
Josh Karlinbe37f912018-12-07 01:05:149297}
9298
9299TEST_F(URLRequestTestHTTP, RedirectUpdateTopFrameOrigin) {
9300 ASSERT_TRUE(http_test_server()->Start());
9301
9302 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9303 url::Origin original_top_frame_origin =
9304 url::Origin::Create(GURL("http://example.com"));
9305 url::Origin expected_top_frame_origin =
9306 url::Origin::Create(GURL(http_test_server()->GetURL("/echo")));
9307
9308 TestDelegate d;
9309
9310 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9311 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9312 r->set_top_frame_origin(original_top_frame_origin);
9313 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
9314
9315 r->Start();
9316 d.RunUntilComplete();
9317
9318 EXPECT_EQ(2U, r->url_chain().size());
9319 EXPECT_EQ(OK, d.request_status());
9320 EXPECT_EQ(expected_top_frame_origin, *r->top_frame_origin());
9321}
9322
9323TEST_F(URLRequestTestHTTP, RedirectIgnoreUnsetTopFrameOrigin) {
9324 ASSERT_TRUE(http_test_server()->Start());
9325
9326 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
9327 TestDelegate d;
9328
9329 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
9330 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
9331 // Since we're not setting a top frame origin, we wouldn't expect one after
9332 // the redirect.
9333 r->set_first_party_url_policy(URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
9334
9335 r->Start();
9336 d.RunUntilComplete();
9337
9338 EXPECT_EQ(2U, r->url_chain().size());
9339 EXPECT_EQ(OK, d.request_status());
9340 EXPECT_FALSE(r->top_frame_origin());
[email protected]cba24642014-08-15 20:49:599341}
9342
[email protected]316c1e5e2012-09-12 15:17:449343TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:559344 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449345
9346 const char kData[] = "hello world";
9347
9348 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079349 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169350 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9351 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199352 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079353 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:449354 HttpRequestHeaders headers;
9355 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:249356 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:199357 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:449358
danakj8522a25b2016-04-16 00:17:369359 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559360 req.get(), &default_network_delegate_,
9361 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429362 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9363 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:449364
[email protected]f7022f32014-08-21 16:32:199365 req->Start();
Wez2a31b222018-06-07 22:07:159366 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:199367 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:449368}
9369
9370TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:559371 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449372
9373 const char kData[] = "hello world";
9374
9375 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079376 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169377 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9378 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199379 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079380 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:449381 HttpRequestHeaders headers;
9382 headers.SetHeader(HttpRequestHeaders::kContentLength,
Avi Drissman4365a4782018-12-28 19:26:249383 base::NumberToString(base::size(kData) - 1));
[email protected]f7022f32014-08-21 16:32:199384 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:449385
danakj8522a25b2016-04-16 00:17:369386 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559387 req.get(), &default_network_delegate_,
9388 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:099389 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:429390 "Very Good Reason"));
9391 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:449392
[email protected]f7022f32014-08-21 16:32:199393 req->Start();
Wez2a31b222018-06-07 22:07:159394 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:199395 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:449396 EXPECT_EQ(kData, d.data_received());
9397}
9398
9399// Check that default A-L header is sent.
9400TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559401 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449402
[email protected]8790210c2013-12-02 05:29:539403 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:249404 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:449405 TestURLRequestContext context(true);
9406 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:439407 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:449408 context.Init();
9409
9410 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369411 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:559412 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169413 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199414 req->Start();
Wez2a31b222018-06-07 22:07:159415 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449416 EXPECT_EQ("en", d.data_received());
9417}
9418
9419// Check that an empty A-L header is not sent. http://crbug.com/77365.
9420TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559421 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449422
[email protected]8790210c2013-12-02 05:29:539423 std::string empty_string; // Avoid most vexing parse on line below.
9424 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:249425 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:449426 TestURLRequestContext context(true);
9427 context.set_network_delegate(&network_delegate);
9428 context.Init();
9429 // We override the language after initialization because empty entries
9430 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:439431 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:449432
9433 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369434 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:559435 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169436 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199437 req->Start();
Wez2a31b222018-06-07 22:07:159438 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449439 EXPECT_EQ("None", d.data_received());
9440}
9441
9442// Check that if request overrides the A-L header, the default is not appended.
9443// See http://crbug.com/20894
9444TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559445 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449446
9447 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079448 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559449 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169450 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449451 HttpRequestHeaders headers;
9452 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:199453 req->SetExtraRequestHeaders(headers);
9454 req->Start();
Wez2a31b222018-06-07 22:07:159455 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449456 EXPECT_EQ(std::string("ru"), d.data_received());
9457}
9458
9459// Check that default A-E header is sent.
9460TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559461 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449462
9463 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079464 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559465 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169466 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449467 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:199468 req->SetExtraRequestHeaders(headers);
9469 req->Start();
Wez2a31b222018-06-07 22:07:159470 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449471 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
9472}
9473
9474// Check that if request overrides the A-E header, the default is not appended.
9475// See http://crbug.com/47381
9476TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559477 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449478
9479 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079480 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559481 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169482 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449483 HttpRequestHeaders headers;
9484 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[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_FALSE(ContainsString(d.data_received(), "gzip"));
9489 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
9490}
9491
[email protected]84f05432013-03-15 01:00:129492// Check that setting the A-C header sends the proper header.
9493TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
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-Charset"),
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::kAcceptCharset, "koi-8r");
[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_EQ(std::string("koi-8r"), d.data_received());
9506}
9507
9508// Check that default User-Agent header is sent.
9509TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:559510 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449511
9512 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079513 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559514 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169515 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199516 req->Start();
Wez2a31b222018-06-07 22:07:159517 d.RunUntilComplete();
Ryan Sleevib8449e02018-07-15 04:31:079518 EXPECT_EQ(default_context().http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:379519 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449520}
9521
9522// Check that if request overrides the User-Agent header,
9523// the default is not appended.
marqf14fff8d2015-12-02 15:52:299524// TODO(crbug.com/564656) This test is flaky on iOS.
9525#if defined(OS_IOS)
9526#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
9527#else
9528#define MAYBE_OverrideUserAgent OverrideUserAgent
9529#endif
9530TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:559531 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449532
9533 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079534 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559535 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169536 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449537 HttpRequestHeaders headers;
9538 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:199539 req->SetExtraRequestHeaders(headers);
9540 req->Start();
Wez2a31b222018-06-07 22:07:159541 d.RunUntilComplete();
[email protected]cd6f2522014-01-16 18:27:359542 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449543}
9544
[email protected]ee4c30d2012-11-07 15:08:439545// Check that a NULL HttpUserAgentSettings causes the corresponding empty
9546// User-Agent header to be sent but does not send the Accept-Language and
9547// Accept-Charset headers.
9548TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:559549 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:439550
[email protected]ceefd7fd2012-11-29 00:36:249551 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:439552 TestURLRequestContext context(true);
9553 context.set_network_delegate(&network_delegate);
9554 context.Init();
9555 // We override the HttpUserAgentSettings after initialization because empty
9556 // entries get overridden by Init().
Raul Tambre94493c652019-03-11 17:18:359557 context.set_http_user_agent_settings(nullptr);
[email protected]ee4c30d2012-11-07 15:08:439558
9559 struct {
9560 const char* request;
9561 const char* expected_response;
tommycli59a63432015-11-06 00:10:559562 } tests[] = {{"/echoheader?Accept-Language", "None"},
9563 {"/echoheader?Accept-Charset", "None"},
9564 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:439565
Avi Drissman4365a4782018-12-28 19:26:249566 for (size_t i = 0; i < base::size(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:439567 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369568 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169569 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
9570 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199571 req->Start();
Wez2a31b222018-06-07 22:07:159572 d.RunUntilComplete();
[email protected]ee4c30d2012-11-07 15:08:439573 EXPECT_EQ(tests[i].expected_response, d.data_received())
9574 << " Request = \"" << tests[i].request << "\"";
9575 }
9576}
9577
[email protected]5033ab82013-03-22 20:17:469578// Make sure that URLRequest passes on its priority updates to
9579// newly-created jobs after the first one.
9580TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:559581 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:469582
9583 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079584 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169585 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9586 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199587 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:469588
danakj8522a25b2016-04-16 00:17:369589 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559590 req.get(), &default_network_delegate_,
9591 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429592 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9593 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:469594
[email protected]f7022f32014-08-21 16:32:199595 req->SetPriority(LOW);
9596 req->Start();
9597 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:469598
mmenkeed0498b2015-12-08 23:20:429599 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:369600 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:429601 req.get(), &default_network_delegate_, &job_priority));
9602 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:469603
9604 // Should trigger |job| to be started.
Wez2a31b222018-06-07 22:07:159605 d.RunUntilComplete();
mmenkeed0498b2015-12-08 23:20:429606 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:469607}
9608
[email protected]80abdad2014-03-15 00:20:549609// Check that creating a network request while entering/exiting suspend mode
9610// fails as it should. This is the only case where an HttpTransactionFactory
9611// does not return an HttpTransaction.
9612TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
9613 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:369614 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
Ryan Sleevib8449e02018-07-15 04:31:079615 default_context().http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:549616 network_layer->OnSuspend();
9617
dchengc7eeda422015-12-26 03:56:489618 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:039619 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:279620 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:549621
9622 TestURLRequestContext context(true);
9623 context.set_http_transaction_factory(&http_cache);
9624 context.Init();
9625
9626 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369627 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169628 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9629 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199630 req->Start();
Wez2a31b222018-06-07 22:07:159631 d.RunUntilComplete();
[email protected]80abdad2014-03-15 00:20:549632
9633 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:509634 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:549635}
9636
mmenke2281f3762015-11-02 20:38:179637namespace {
[email protected]80abdad2014-03-15 00:20:549638
mmenke2281f3762015-11-02 20:38:179639// HttpTransactionFactory that synchronously fails to create transactions.
9640class FailingHttpTransactionFactory : public HttpTransactionFactory {
9641 public:
9642 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
9643 : network_session_(network_session) {}
9644
Chris Watkins7a41d3552017-12-01 02:13:279645 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:179646
9647 // HttpTransactionFactory methods:
9648 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:369649 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:179650 return ERR_FAILED;
9651 }
9652
9653 HttpCache* GetCache() override { return nullptr; }
9654
9655 HttpNetworkSession* GetSession() override { return network_session_; }
9656
9657 private:
9658 HttpNetworkSession* network_session_;
9659
9660 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
9661};
9662
9663} // namespace
9664
9665// Check that when a request that fails to create an HttpTransaction can be
9666// cancelled while the failure notification is pending, and doesn't send two
9667// failure notifications.
9668//
9669// This currently only happens when in suspend mode and there's no cache, but
9670// just use a special HttpTransactionFactory, to avoid depending on those
9671// behaviors.
9672TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
9673 FailingHttpTransactionFactory http_transaction_factory(
Ryan Sleevib8449e02018-07-15 04:31:079674 default_context().http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:549675 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:179676 context.set_http_transaction_factory(&http_transaction_factory);
9677 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:549678 context.Init();
9679
9680 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369681 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169682 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9683 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:179684 // Don't send cookies (Collecting cookies is asynchronous, and need request to
9685 // try to create an HttpNetworkTransaction synchronously on start).
9686 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:199687 req->Start();
mmenke2281f3762015-11-02 20:38:179688 req->Cancel();
Wez2a31b222018-06-07 22:07:159689 d.RunUntilComplete();
mmenke2281f3762015-11-02 20:38:179690 // Run pending error task, if there is one.
9691 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:549692
9693 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:179694 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509695 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:179696
9697 // NetworkDelegate should see the cancellation, but not the error.
9698 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
9699 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:549700}
9701
ttuttlec0c828492015-05-15 01:25:559702TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:559703 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559704
9705 TestDelegate d;
tommycli59a63432015-11-06 00:10:559706 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079707 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169708 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559709
9710 req->Start();
Wez2a31b222018-06-07 22:07:159711 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559712
9713 EXPECT_TRUE(req->response_info().network_accessed);
9714}
9715
9716TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:559717 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559718
9719 // Populate the cache.
9720 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079721 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169722 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9723 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559724 req->Start();
Wez2a31b222018-06-07 22:07:159725 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559726
maksim.sisovb53724b52016-09-16 05:30:509727 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559728 EXPECT_TRUE(req->response_info().network_accessed);
9729 EXPECT_FALSE(req->response_info().was_cached);
9730
Ryan Sleevib8449e02018-07-15 04:31:079731 req = default_context().CreateRequest(
9732 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9733 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:559734 req->Start();
Wez2a31b222018-06-07 22:07:159735 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559736
maksim.sisovb53724b52016-09-16 05:30:509737 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559738 EXPECT_FALSE(req->response_info().network_accessed);
9739 EXPECT_TRUE(req->response_info().was_cached);
9740}
9741
9742TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:559743 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559744
9745 TestDelegate d;
tommycli59a63432015-11-06 00:10:559746 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:079747 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169748 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:339749 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:559750
9751 req->Start();
Wez2a31b222018-06-07 22:07:159752 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559753
9754 EXPECT_FALSE(req->response_info().network_accessed);
9755}
9756
rdsmithbf8c3c12016-11-18 18:16:249757// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:089758// correctly in the absence of contention.
9759TEST_F(URLRequestTestHTTP, ThrottledPriority) {
9760 ASSERT_TRUE(http_test_server()->Start());
9761
9762 TestDelegate d;
9763 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, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:089766 req->Start();
Wez2a31b222018-06-07 22:07:159767 d.RunUntilComplete();
rdsmith5eb6fbc2016-10-21 17:36:089768
9769 EXPECT_TRUE(req->status().is_success());
9770}
9771
ricea3a1c71f2016-06-17 10:05:269772TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
9773 ASSERT_TRUE(http_test_server()->Start());
9774
9775 TestDelegate d;
9776 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169777 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9778 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269779 req->Start();
Wez2a31b222018-06-07 22:07:159780 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269781
9782 EXPECT_EQ(5, req->GetRawBodyBytes());
9783}
9784
9785TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
9786 ASSERT_TRUE(http_test_server()->Start());
9787
9788 TestDelegate d;
9789 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169790 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
9791 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269792 req->Start();
Wez2a31b222018-06-07 22:07:159793 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269794
9795 EXPECT_EQ(30, req->GetRawBodyBytes());
9796}
9797
jamd3f5a3c2016-10-27 18:52:029798// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
9799// the delegate isn't called back synchronously.
9800TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
9801 ASSERT_TRUE(http_test_server()->Start());
9802 default_network_delegate_.set_before_start_transaction_fails();
9803
9804 TestDelegate d;
9805 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169806 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
9807 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:029808 req->Start();
9809 DCHECK(!d.response_completed());
Wez2a31b222018-06-07 22:07:159810 d.RunUntilComplete();
jamd3f5a3c2016-10-27 18:52:029811 DCHECK(d.response_completed());
9812 EXPECT_EQ(ERR_FAILED, d.request_status());
9813}
9814
bengr1bf8e942014-11-07 01:36:509815class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9816 public:
9817 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9818 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9819 // tests into the factory tests.
Raul Tambre94493c652019-03-11 17:18:359820 URLRequestInterceptorTestHTTP()
9821 : URLRequestTestHTTP(), interceptor_(nullptr) {}
bengr1bf8e942014-11-07 01:36:509822
9823 void SetUpFactory() override {
9824 interceptor_ = new MockURLRequestInterceptor();
9825 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369826 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509827 }
9828
9829 MockURLRequestInterceptor* interceptor() const {
9830 return interceptor_;
9831 }
9832
9833 private:
9834 MockURLRequestInterceptor* interceptor_;
9835};
9836
9837TEST_F(URLRequestInterceptorTestHTTP,
9838 NetworkDelegateNotificationOnRedirectIntercept) {
9839 interceptor()->set_intercept_redirect(true);
9840 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9841 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9842
tommycli59a63432015-11-06 00:10:559843 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509844
9845 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369846 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169847 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9848 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509849 req->Start();
Wez2a31b222018-06-07 22:07:159850 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509851
9852 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9853 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509854 int status = d.request_status();
9855 EXPECT_EQ(OK, status);
9856 if (status == OK)
bengr1bf8e942014-11-07 01:36:509857 EXPECT_EQ(200, req->response_headers()->response_code());
9858
9859 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9860 EXPECT_EQ(1, d.response_started_count());
9861 EXPECT_EQ(0, d.received_redirect_count());
9862
9863 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009864 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509865 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9866}
9867
9868TEST_F(URLRequestInterceptorTestHTTP,
9869 NetworkDelegateNotificationOnErrorIntercept) {
9870 // Intercept that error and respond with an OK response.
9871 interceptor()->set_intercept_final_response(true);
9872 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9873 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9874 default_network_delegate()->set_can_be_intercepted_on_error(true);
9875
tommycli59a63432015-11-06 00:10:559876 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509877
9878 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369879 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559880 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169881 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509882 req->set_method("GET");
9883 req->Start();
Wez2a31b222018-06-07 22:07:159884 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509885
9886 EXPECT_TRUE(interceptor()->did_intercept_final());
9887
9888 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509889 int status = d.request_status();
9890 EXPECT_EQ(OK, status);
9891 if (status == OK)
bengr1bf8e942014-11-07 01:36:509892 EXPECT_EQ(200, req->response_headers()->response_code());
9893 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9894 EXPECT_EQ(1, d.response_started_count());
9895 EXPECT_EQ(0, d.received_redirect_count());
9896
9897 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009898 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509899 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9900}
9901
9902TEST_F(URLRequestInterceptorTestHTTP,
9903 NetworkDelegateNotificationOnResponseIntercept) {
9904 // Intercept that error and respond with an OK response.
9905 interceptor()->set_intercept_final_response(true);
9906
9907 // Intercept with a real URLRequestHttpJob.
9908 interceptor()->set_use_url_request_http_job(true);
9909
tommycli59a63432015-11-06 00:10:559910 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509911
9912 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369913 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169914 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9915 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509916 req->set_method("GET");
9917 req->Start();
Wez2a31b222018-06-07 22:07:159918 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509919
9920 EXPECT_TRUE(interceptor()->did_intercept_final());
9921
9922 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509923 int status = d.request_status();
9924 EXPECT_EQ(OK, status);
9925 if (status == OK)
bengr1bf8e942014-11-07 01:36:509926 EXPECT_EQ(200, req->response_headers()->response_code());
9927 EXPECT_EQ("hello", d.data_received());
9928 EXPECT_EQ(1, d.response_started_count());
9929 EXPECT_EQ(0, d.received_redirect_count());
9930
9931 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009932 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509933 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9934}
9935
mkwst0c5eab872014-11-21 14:18:549936class URLRequestTestReferrerPolicy : public URLRequestTest {
9937 public:
Chris Watkins7a41d3552017-12-01 02:13:279938 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:549939
tommycli59a63432015-11-06 00:10:559940 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9941 origin_server_.reset(new EmbeddedTestServer(type));
9942 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9943 origin_server_->AddDefaultHandlers(
9944 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9945 } else {
9946 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9947 }
mkwst0c5eab872014-11-21 14:18:549948 ASSERT_TRUE(origin_server_->Start());
9949 }
9950
tommycli59a63432015-11-06 00:10:559951 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9952 net::EmbeddedTestServer::Type dest_type) {
9953 origin_server_.reset(new EmbeddedTestServer(origin_type));
9954 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9955 origin_server_->AddDefaultHandlers(
9956 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9957 } else {
9958 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9959 }
mkwst0c5eab872014-11-21 14:18:549960 ASSERT_TRUE(origin_server_->Start());
9961
tommycli59a63432015-11-06 00:10:559962 destination_server_.reset(new EmbeddedTestServer(dest_type));
9963 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9964 destination_server_->AddDefaultHandlers(
9965 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9966 } else {
9967 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9968 }
mkwst0c5eab872014-11-21 14:18:549969 ASSERT_TRUE(destination_server_->Start());
9970 }
9971
9972 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9973 const GURL& referrer,
9974 const GURL& expected) {
9975 // Create and execute the request: we'll only have a |destination_server_|
9976 // if the origins are meant to be distinct. Otherwise, we'll use the
9977 // |origin_server_| for both endpoints.
9978 GURL destination_url =
tommycli59a63432015-11-06 00:10:559979 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9980 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549981 GURL origin_url =
tommycli59a63432015-11-06 00:10:559982 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549983
9984 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:079985 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169986 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549987 req->set_referrer_policy(policy);
9988 req->SetReferrer(referrer.spec());
9989 req->Start();
Wez2a31b222018-06-07 22:07:159990 d.RunUntilComplete();
mkwst0c5eab872014-11-21 14:18:549991
9992 EXPECT_EQ(1, d.response_started_count());
9993 EXPECT_EQ(1, d.received_redirect_count());
9994 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509995 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549996 EXPECT_EQ(200, req->response_headers()->response_code());
9997
9998 EXPECT_EQ(expected.spec(), req->referrer());
9999 if (expected.is_empty())
10000 EXPECT_EQ("None", d.data_received());
10001 else
10002 EXPECT_EQ(expected.spec(), d.data_received());
10003 }
10004
tommycli59a63432015-11-06 00:10:5510005 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:5410006
10007 private:
danakj8522a25b2016-04-16 00:17:3610008 std::unique_ptr<EmbeddedTestServer> origin_server_;
10009 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:5410010};
10011
10012TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:5510013 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:5410014
estarkc8ccba82017-06-13 22:37:4010015 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410016 VerifyReferrerAfterRedirect(
10017 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010018 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410019
10020 VerifyReferrerAfterRedirect(
10021 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010022 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410023
10024 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010025 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410026
estarkc8ccba82017-06-13 22:37:4010027 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10028 referrer);
10029
10030 // The original referrer set on the request is expected to obey the referrer
10031 // policy and already be stripped to the origin; thus this test case just
10032 // checks that this policy doesn't cause the referrer to change when following
10033 // a redirect.
10034 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10035 referrer.GetOrigin());
10036
10037 VerifyReferrerAfterRedirect(
10038 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
10039 referrer);
10040
10041 // The original referrer set on the request is expected to obey the referrer
10042 // policy and already be stripped to the origin; thus this test case just
10043 // checks that this policy doesn't cause the referrer to change when following
10044 // a redirect.
10045 VerifyReferrerAfterRedirect(
10046 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10047 referrer.GetOrigin(), referrer.GetOrigin());
10048
10049 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410050}
10051
tommycli59a63432015-11-06 00:10:5510052TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
10053 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
10054 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:4010055 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410056
10057 VerifyReferrerAfterRedirect(
10058 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010059 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410060
10061 VerifyReferrerAfterRedirect(
10062 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010063 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:5410064
10065 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010066 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
10067 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:5410068
estarkc8ccba82017-06-13 22:37:4010069 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10070 referrer);
10071
10072 // The original referrer set on the request is expected to obey the referrer
10073 // policy and already be stripped to the origin; thus this test case just
10074 // checks that this policy doesn't cause the referrer to change when following
10075 // a redirect.
10076 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10077 referrer.GetOrigin());
10078
10079 VerifyReferrerAfterRedirect(
10080 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10081
10082 // The original referrer set on the request is expected to obey the referrer
10083 // policy and already be stripped to the origin; thus this test case just
10084 // checks that this policy doesn't cause the referrer to change when following
10085 // a redirect.
10086 VerifyReferrerAfterRedirect(
10087 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10088 referrer.GetOrigin(), referrer.GetOrigin());
10089
10090 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410091}
10092
10093TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:5510094 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:4010095 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410096
10097 VerifyReferrerAfterRedirect(
10098 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010099 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410100
10101 VerifyReferrerAfterRedirect(
10102 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010103 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410104
10105 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010106 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410107
estarkc8ccba82017-06-13 22:37:4010108 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10109 referrer);
10110
10111 // The original referrer set on the request is expected to obey the referrer
10112 // policy and already be stripped to the origin; thus this test case just
10113 // checks that this policy doesn't cause the referrer to change when following
10114 // a redirect.
10115 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10116 referrer.GetOrigin());
10117
10118 VerifyReferrerAfterRedirect(
10119 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
10120 referrer);
10121
10122 // The original referrer set on the request is expected to obey the referrer
10123 // policy and already be stripped to the origin; thus this test case just
10124 // checks that this policy doesn't cause the referrer to change when following
10125 // a redirect.
10126 VerifyReferrerAfterRedirect(
10127 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10128 referrer.GetOrigin(), referrer.GetOrigin());
10129
10130 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410131}
10132
tommycli59a63432015-11-06 00:10:5510133TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
10134 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
10135 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:4010136 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410137
10138 VerifyReferrerAfterRedirect(
10139 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010140 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410141
10142 VerifyReferrerAfterRedirect(
10143 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010144 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410145
10146 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010147 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:5510148 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410149
estarkc8ccba82017-06-13 22:37:4010150 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10151 referrer);
10152
10153 // The original referrer set on the request is expected to obey the referrer
10154 // policy and already be stripped to the origin; thus this test case just
10155 // checks that this policy doesn't cause the referrer to change when following
10156 // a redirect.
10157 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10158 referrer.GetOrigin());
10159
10160 VerifyReferrerAfterRedirect(
10161 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10162
10163 // The original referrer set on the request is expected to obey the referrer
10164 // policy and already be stripped to the origin; thus this test case just
10165 // checks that this policy doesn't cause the referrer to change when following
10166 // a redirect.
10167 VerifyReferrerAfterRedirect(
10168 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10169 referrer.GetOrigin(), referrer.GetOrigin());
10170
10171 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410172}
10173
tommycli59a63432015-11-06 00:10:5510174TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
10175 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
10176 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:4010177 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410178
10179 VerifyReferrerAfterRedirect(
10180 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010181 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:5410182
10183 VerifyReferrerAfterRedirect(
10184 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010185 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410186
10187 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010188 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:5510189 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410190
estarkc8ccba82017-06-13 22:37:4010191 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10192 referrer);
10193
10194 // The original referrer set on the request is expected to obey the referrer
10195 // policy and already be stripped to the origin; thus this test case just
10196 // checks that this policy doesn't cause the referrer to change when following
10197 // a redirect.
10198 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10199 referrer.GetOrigin());
10200
10201 VerifyReferrerAfterRedirect(
10202 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10203
10204 // The original referrer set on the request is expected to obey the referrer
10205 // policy and already be stripped to the origin; thus this test case just
10206 // checks that this policy doesn't cause the referrer to change when following
10207 // a redirect.
10208 VerifyReferrerAfterRedirect(
10209 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10210 referrer.GetOrigin(), referrer.GetOrigin());
10211
10212 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410213}
10214
tommycli59a63432015-11-06 00:10:5510215TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
10216 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
10217 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:4010218 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:5410219
10220 VerifyReferrerAfterRedirect(
10221 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:4010222 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:5410223
10224 VerifyReferrerAfterRedirect(
10225 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:4010226 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:5410227
10228 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:4010229 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:5510230 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:5410231
estarkc8ccba82017-06-13 22:37:4010232 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
10233 referrer);
10234
10235 // The original referrer set on the request is expected to obey the referrer
10236 // policy and already be stripped to the origin; thus this test case just
10237 // checks that this policy doesn't cause the referrer to change when following
10238 // a redirect.
10239 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
10240 referrer.GetOrigin());
10241
10242 VerifyReferrerAfterRedirect(
10243 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
10244
10245 // The original referrer set on the request is expected to obey the referrer
10246 // policy and already be stripped to the origin, though it should be
10247 // subsequently cleared during the downgrading redirect.
10248 VerifyReferrerAfterRedirect(
10249 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
10250 referrer.GetOrigin(), GURL());
10251
10252 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:5410253}
10254
Bence Béky98447b12018-05-08 03:14:0110255class HTTPSRequestTest : public TestWithScopedTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:5010256 public:
fdorayf33fede2017-05-11 21:18:1010257 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:0910258 default_context_.set_network_delegate(&default_network_delegate_);
10259 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:5010260 }
Martijn Croonenb1383da2017-10-11 11:56:3510261 ~HTTPSRequestTest() override {
10262 SetTransportSecurityStateSourceForTesting(nullptr);
10263 }
[email protected]87a09a92011-07-14 15:50:5010264
10265 protected:
[email protected]ceefd7fd2012-11-29 00:36:2410266 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:0910267 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:4610268};
10269
[email protected]c044616e2013-02-20 02:01:2610270TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:5510271 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10272 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210273 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:1110274 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:4610275
[email protected]ea224582008-12-07 20:25:4610276 TestDelegate d;
10277 {
danakj8522a25b2016-04-16 00:17:3610278 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610279 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10280 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910281 r->Start();
10282 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:4610283
Wez2a31b222018-06-07 22:07:1510284 d.RunUntilComplete();
[email protected]ea224582008-12-07 20:25:4610285
10286 EXPECT_EQ(1, d.response_started_count());
10287 EXPECT_FALSE(d.received_data_before_response());
10288 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:1910289 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:1910290 EXPECT_EQ(test_server.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3710291 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
[email protected]6d81b482011-02-22 19:47:1910292 EXPECT_EQ(test_server.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3710293 r->GetResponseRemoteEndpoint().port());
[email protected]ea224582008-12-07 20:25:4610294 }
[email protected]ea224582008-12-07 20:25:4610295}
10296
[email protected]5774ada2010-07-15 06:30:5410297TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:5510298 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10299 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10300 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210301 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:1110302 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:3310303
10304 bool err_allowed = true;
10305 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
10306 TestDelegate d;
10307 {
10308 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:3610309 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610310 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10311 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:3310312
[email protected]f7022f32014-08-21 16:32:1910313 r->Start();
10314 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:3310315
Wez2a31b222018-06-07 22:07:1510316 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:3310317
10318 EXPECT_EQ(1, d.response_started_count());
10319 EXPECT_FALSE(d.received_data_before_response());
10320 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:1710321 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:3310322 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:1910323 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:1710324 } else {
[email protected]bacff652009-03-31 17:50:3310325 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:1710326 }
[email protected]bacff652009-03-31 17:50:3310327 }
10328 }
10329}
10330
[email protected]5774ada2010-07-15 06:30:5410331TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:5510332 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10333 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
10334 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210335 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:1110336 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:3310337
10338 // Iterate from false to true, just so that we do the opposite of the
10339 // previous test in order to increase test coverage.
10340 bool err_allowed = false;
10341 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
10342 TestDelegate d;
10343 {
10344 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:3610345 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610346 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10347 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:3310348
[email protected]f7022f32014-08-21 16:32:1910349 r->Start();
10350 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:3310351
Wez2a31b222018-06-07 22:07:1510352 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:3310353
10354 EXPECT_EQ(1, d.response_started_count());
10355 EXPECT_FALSE(d.received_data_before_response());
10356 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:1710357 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:3310358 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:1910359 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:1710360 } else {
[email protected]bacff652009-03-31 17:50:3310361 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:1710362 }
[email protected]bacff652009-03-31 17:50:3310363 }
10364 }
10365}
[email protected]73e0bba2009-02-19 22:57:0910366
Emily Stark79fba5842019-04-25 04:59:3610367// A TestDelegate used to test that an appropriate net error code is provided
10368// when an SSL certificate error occurs.
10369class SSLNetErrorTestDelegate : public TestDelegate {
10370 public:
10371 void OnSSLCertificateError(URLRequest* request,
10372 int net_error,
10373 const SSLInfo& ssl_info,
10374 bool fatal) override {
10375 net_error_ = net_error;
10376 on_ssl_certificate_error_called_ = true;
10377 TestDelegate::OnSSLCertificateError(request, net_error, ssl_info, fatal);
10378 }
10379
10380 bool on_ssl_certificate_error_called() {
10381 return on_ssl_certificate_error_called_;
10382 }
10383
10384 int net_error() { return net_error_; }
10385
10386 private:
10387 bool on_ssl_certificate_error_called_ = false;
10388 int net_error_ = net::OK;
10389};
10390
10391// Tests that the URLRequest::Delegate receives an appropriate net error code
10392// when an SSL certificate error occurs.
10393TEST_F(HTTPSRequestTest, SSLNetErrorReportedToDelegate) {
10394 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10395 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
10396 test_server.AddDefaultHandlers(
10397 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10398 ASSERT_TRUE(test_server.Start());
10399
10400 SSLNetErrorTestDelegate d;
10401 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10402 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10403 TRAFFIC_ANNOTATION_FOR_TESTS));
10404 r->Start();
10405 EXPECT_TRUE(r->is_pending());
10406 d.RunUntilComplete();
10407
10408 EXPECT_TRUE(d.on_ssl_certificate_error_called());
10409 EXPECT_EQ(net::ERR_CERT_DATE_INVALID, d.net_error());
10410}
10411
tommycli59a63432015-11-06 00:10:5510412// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
10413// security state. (see http://crbug.com/550977).
10414#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:3510415// This tests that a load of a domain with preloaded HSTS and HPKP with a
10416// certificate error sets the |certificate_errors_are_fatal| flag correctly.
10417// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:4410418TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:3510419 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
10420
tommycli59a63432015-11-06 00:10:5510421 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10422 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10423 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:4410424 ASSERT_TRUE(test_server.Start());
10425
Martijn Croonenb1383da2017-10-11 11:56:3510426 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
10427 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
10428 // means that we have to use a MockHostResolver in order to direct
10429 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
10430 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:4410431
10432 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:2410433 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:4410434 TestURLRequestContext context(true);
10435 context.set_network_delegate(&network_delegate);
10436 context.set_host_resolver(&host_resolver);
10437 TransportSecurityState transport_security_state;
10438 context.set_transport_security_state(&transport_security_state);
10439 context.Init();
10440
10441 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610442 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:3510443 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:3610444 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610445 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410446
[email protected]f7022f32014-08-21 16:32:1910447 r->Start();
10448 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410449
Wez2a31b222018-06-07 22:07:1510450 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410451
10452 EXPECT_EQ(1, d.response_started_count());
10453 EXPECT_FALSE(d.received_data_before_response());
10454 EXPECT_TRUE(d.have_certificate_errors());
10455 EXPECT_TRUE(d.certificate_errors_are_fatal());
10456}
10457
10458// This tests that cached HTTPS page loads do not cause any updates to the
10459// TransportSecurityState.
10460TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:3510461 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
10462
[email protected]316c1e5e2012-09-12 15:17:4410463 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
10464 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:5510465 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10466 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
10467 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:4410468 ASSERT_TRUE(test_server.Start());
10469
Martijn Croonenb1383da2017-10-11 11:56:3510470 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
10471 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
10472 // means that we have to use a MockHostResolver in order to direct
10473 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
10474 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:4410475
10476 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:2410477 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:4410478 TestURLRequestContext context(true);
10479 context.set_network_delegate(&network_delegate);
10480 context.set_host_resolver(&host_resolver);
10481 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:2610482
martijnc0d6b622015-06-30 19:14:4010483 TransportSecurityState::STSState static_sts_state;
10484 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610485 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510486 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:4410487 context.set_transport_security_state(&transport_security_state);
10488 context.Init();
10489
martijnc0d6b622015-06-30 19:14:4010490 TransportSecurityState::STSState dynamic_sts_state;
10491 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:3510492 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
10493 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
10494 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
10495 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610496
[email protected]316c1e5e2012-09-12 15:17:4410497 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610498 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:3510499 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:3610500 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610501 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410502
[email protected]f7022f32014-08-21 16:32:1910503 r->Start();
10504 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410505
Wez2a31b222018-06-07 22:07:1510506 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410507
10508 EXPECT_EQ(1, d.response_started_count());
10509 EXPECT_FALSE(d.received_data_before_response());
10510 EXPECT_TRUE(d.have_certificate_errors());
10511 EXPECT_TRUE(d.certificate_errors_are_fatal());
10512
[email protected]9e6968d2014-05-07 21:46:2610513 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:4010514 TransportSecurityState::STSState new_static_sts_state;
10515 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610516 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510517 "hsts-hpkp-preloaded.test", &new_static_sts_state,
10518 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:4010519 TransportSecurityState::STSState new_dynamic_sts_state;
10520 TransportSecurityState::PKPState new_dynamic_pkp_state;
10521 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:3510522 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:4010523 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:3510524 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610525
martijnc0d6b622015-06-30 19:14:4010526 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
10527 EXPECT_EQ(new_static_sts_state.include_subdomains,
10528 static_sts_state.include_subdomains);
10529 EXPECT_EQ(new_static_pkp_state.include_subdomains,
10530 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:4810531 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
10532 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
10533 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:4410534}
10535
[email protected]8ccc69f2012-11-28 19:52:1410536// Make sure HSTS preserves a POST request's method and body.
10537TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
10538 static const char kData[] = "hello world";
10539
tommycli59a63432015-11-06 00:10:5510540 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10541 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210542 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:1410543 ASSERT_TRUE(test_server.Start());
10544
10545
10546 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10547 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:5510548 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:2210549 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:1410550 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:1410551
10552 // Force https for www.somewhere.com.
10553 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:2010554 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
10555 bool include_subdomains = false;
10556 transport_security_state.AddHSTS("www.somewhere.com", expiry,
10557 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:1410558
10559 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10560
10561 TestURLRequestContext context(true);
10562 context.set_host_resolver(&host_resolver);
10563 context.set_transport_security_state(&transport_security_state);
10564 context.set_network_delegate(&network_delegate);
10565 context.Init();
10566
10567 TestDelegate d;
10568 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
10569 // cause a certificate error. Ignore the error.
10570 d.set_allow_certificate_errors(true);
10571
danakj8522a25b2016-04-16 00:17:3610572 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:1910573 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:3610574 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610575 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910576 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:0710577 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:1410578
[email protected]f7022f32014-08-21 16:32:1910579 req->Start();
Wez2a31b222018-06-07 22:07:1510580 d.RunUntilComplete();
[email protected]8ccc69f2012-11-28 19:52:1410581
[email protected]f7022f32014-08-21 16:32:1910582 EXPECT_EQ("https", req->url().scheme());
10583 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:1410584 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:4010585
10586 LoadTimingInfo load_timing_info;
10587 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
10588 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
10589 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:1410590}
10591
rob4e0be1f2014-09-11 23:40:2210592// Make sure that the CORS headers are added to cross-origin HSTS redirects.
10593TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
10594 static const char kOriginHeaderValue[] = "http://www.example.com";
10595
tommycli59a63432015-11-06 00:10:5510596 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10597 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:2210598 ASSERT_TRUE(test_server.Start());
10599
10600 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10601 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:5510602 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
10603 // default.
rob4e0be1f2014-09-11 23:40:2210604 MockHostResolver host_resolver;
10605
10606 TransportSecurityState transport_security_state;
10607 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
10608 bool include_subdomains = false;
10609 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
10610
10611 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10612
10613 MockCertVerifier cert_verifier;
10614 cert_verifier.set_default_result(OK);
10615
10616 TestURLRequestContext context(true);
10617 context.set_host_resolver(&host_resolver);
10618 context.set_transport_security_state(&transport_security_state);
10619 context.set_network_delegate(&network_delegate);
10620 context.set_cert_verifier(&cert_verifier);
10621 context.Init();
10622
10623 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
10624 test_server.host_port_pair().port()));
10625 url::Replacements<char> replacements;
10626 const char kNewScheme[] = "https";
10627 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
10628 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
10629
10630 TestDelegate d;
rob4e0be1f2014-09-11 23:40:2210631
rhalavatib7bd7c792017-04-27 05:25:1610632 std::unique_ptr<URLRequest> req(context.CreateRequest(
10633 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:2210634 // Set Origin header to simulate a cross-origin request.
10635 HttpRequestHeaders request_headers;
10636 request_headers.SetHeader("Origin", kOriginHeaderValue);
10637 req->SetExtraRequestHeaders(request_headers);
10638
10639 req->Start();
Wez0e717112018-06-18 23:09:2210640 d.RunUntilRedirect();
rob4e0be1f2014-09-11 23:40:2210641
10642 EXPECT_EQ(1, d.received_redirect_count());
10643
10644 const HttpResponseHeaders* headers = req->response_headers();
10645 std::string redirect_location;
Raul Tambre94493c652019-03-11 17:18:3510646 EXPECT_TRUE(
10647 headers->EnumerateHeader(nullptr, "Location", &redirect_location));
rob4e0be1f2014-09-11 23:40:2210648 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
10649
10650 std::string received_cors_header;
Raul Tambre94493c652019-03-11 17:18:3510651 EXPECT_TRUE(headers->EnumerateHeader(nullptr, "Access-Control-Allow-Origin",
rob4e0be1f2014-09-11 23:40:2210652 &received_cors_header));
10653 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
10654}
10655
[email protected]316c1e5e2012-09-12 15:17:4410656namespace {
10657
10658class SSLClientAuthTestDelegate : public TestDelegate {
10659 public:
10660 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
Wez0e717112018-06-18 23:09:2210661 set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:4410662 }
dchengb03027d2014-10-21 12:00:2010663 void OnCertificateRequested(URLRequest* request,
10664 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:4410665 on_certificate_requested_count_++;
Wez0e717112018-06-18 23:09:2210666 std::move(on_certificate_requested_).Run();
10667 }
10668 void RunUntilCertificateRequested() {
10669 base::RunLoop run_loop;
10670 on_certificate_requested_ = run_loop.QuitClosure();
10671 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:4410672 }
10673 int on_certificate_requested_count() {
10674 return on_certificate_requested_count_;
10675 }
10676 private:
10677 int on_certificate_requested_count_;
Wez0e717112018-06-18 23:09:2210678 base::OnceClosure on_certificate_requested_;
[email protected]316c1e5e2012-09-12 15:17:4410679};
10680
David Benjamin76a40ad2018-02-24 22:22:0810681class TestSSLPrivateKey : public SSLPrivateKey {
10682 public:
10683 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
10684 : key_(std::move(key)) {}
10685
10686 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
10687 int sign_count() const { return sign_count_; }
10688
David Benjaminb65b0732018-11-09 20:33:5310689 std::string GetProviderName() override { return key_->GetProviderName(); }
David Benjamin76a40ad2018-02-24 22:22:0810690 std::vector<uint16_t> GetAlgorithmPreferences() override {
10691 return key_->GetAlgorithmPreferences();
10692 }
10693 void Sign(uint16_t algorithm,
10694 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:2610695 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:0810696 sign_count_++;
10697 if (fail_signing_) {
10698 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:2610699 FROM_HERE, base::BindOnce(std::move(callback),
10700 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
10701 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:0810702 } else {
David Benjamin8f2d2c12018-02-27 00:08:2610703 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:0810704 }
10705 }
10706
10707 private:
10708 ~TestSSLPrivateKey() override = default;
10709
10710 scoped_refptr<SSLPrivateKey> key_;
10711 bool fail_signing_ = false;
10712 int sign_count_ = 0;
10713};
10714
[email protected]316c1e5e2012-09-12 15:17:4410715} // namespace
10716
10717// TODO(davidben): Test the rest of the code. Specifically,
10718// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:4410719// - Getting a certificate request in an SSL renegotiation sending the
10720// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:0810721TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:5510722 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10723 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:1210724 ssl_config.client_cert_type =
10725 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:0810726 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:5510727 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210728 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410729 ASSERT_TRUE(test_server.Start());
10730
10731 SSLClientAuthTestDelegate d;
10732 {
danakj8522a25b2016-04-16 00:17:3610733 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610734 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10735 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410736
[email protected]f7022f32014-08-21 16:32:1910737 r->Start();
10738 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410739
Wez0e717112018-06-18 23:09:2210740 d.RunUntilCertificateRequested();
10741 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410742
10743 EXPECT_EQ(1, d.on_certificate_requested_count());
10744 EXPECT_FALSE(d.received_data_before_response());
10745 EXPECT_EQ(0, d.bytes_received());
10746
10747 // Send no certificate.
10748 // TODO(davidben): Get temporary client cert import (with keys) working on
10749 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:5410750 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:4410751
Wez2a31b222018-06-07 22:07:1510752 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410753
David Benjamin76a40ad2018-02-24 22:22:0810754 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:4410755 EXPECT_EQ(1, d.response_started_count());
10756 EXPECT_FALSE(d.received_data_before_response());
10757 EXPECT_NE(0, d.bytes_received());
10758 }
10759}
10760
David Benjamin76a40ad2018-02-24 22:22:0810761TEST_F(HTTPSRequestTest, ClientAuth) {
10762 std::unique_ptr<FakeClientCertIdentity> identity =
10763 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10764 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10765 ASSERT_TRUE(identity);
10766 scoped_refptr<TestSSLPrivateKey> private_key =
10767 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10768
10769 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10770 net::SSLServerConfig ssl_config;
10771 ssl_config.client_cert_type =
10772 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10773 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10774 test_server.AddDefaultHandlers(
10775 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10776 ASSERT_TRUE(test_server.Start());
10777
10778 {
10779 SSLClientAuthTestDelegate d;
10780 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10781 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10782 TRAFFIC_ANNOTATION_FOR_TESTS));
10783
10784 r->Start();
10785 EXPECT_TRUE(r->is_pending());
10786
Wez0e717112018-06-18 23:09:2210787 d.RunUntilCertificateRequested();
10788 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810789
10790 EXPECT_EQ(1, d.on_certificate_requested_count());
10791 EXPECT_FALSE(d.received_data_before_response());
10792 EXPECT_EQ(0, d.bytes_received());
10793
10794 // Send a certificate.
10795 r->ContinueWithCertificate(identity->certificate(), private_key);
10796
Wez2a31b222018-06-07 22:07:1510797 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810798
10799 EXPECT_EQ(OK, d.request_status());
10800 EXPECT_EQ(1, d.response_started_count());
10801 EXPECT_FALSE(d.received_data_before_response());
10802 EXPECT_NE(0, d.bytes_received());
10803
10804 // The private key should have been used.
10805 EXPECT_EQ(1, private_key->sign_count());
10806 }
10807
10808 // Close all connections and clear the session cache to force a new handshake.
10809 default_context_.http_transaction_factory()
10810 ->GetSession()
10811 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710812 default_context_.http_transaction_factory()
10813 ->GetSession()
10814 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810815
10816 // Connecting again should not call OnCertificateRequested. The identity is
10817 // taken from the client auth cache.
10818 {
10819 SSLClientAuthTestDelegate d;
10820 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10821 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10822 TRAFFIC_ANNOTATION_FOR_TESTS));
10823
10824 r->Start();
10825 EXPECT_TRUE(r->is_pending());
10826
Wez2a31b222018-06-07 22:07:1510827 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810828
10829 EXPECT_EQ(OK, d.request_status());
10830 EXPECT_EQ(0, d.on_certificate_requested_count());
10831 EXPECT_FALSE(d.received_data_before_response());
10832 EXPECT_EQ(1, d.response_started_count());
10833 EXPECT_FALSE(d.received_data_before_response());
10834 EXPECT_NE(0, d.bytes_received());
10835
10836 // The private key should have been used.
10837 EXPECT_EQ(2, private_key->sign_count());
10838 }
10839}
10840
10841// Test that private keys that fail to sign anything get evicted from the cache.
10842TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
10843 std::unique_ptr<FakeClientCertIdentity> identity =
10844 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10845 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10846 ASSERT_TRUE(identity);
10847 scoped_refptr<TestSSLPrivateKey> private_key =
10848 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10849 private_key->set_fail_signing(true);
10850
10851 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10852 net::SSLServerConfig ssl_config;
10853 ssl_config.client_cert_type =
10854 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10855 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10856 test_server.AddDefaultHandlers(
10857 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10858 ASSERT_TRUE(test_server.Start());
10859
10860 {
10861 SSLClientAuthTestDelegate d;
10862 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10863 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10864 TRAFFIC_ANNOTATION_FOR_TESTS));
10865
10866 r->Start();
10867 EXPECT_TRUE(r->is_pending());
Wez0e717112018-06-18 23:09:2210868
10869 d.RunUntilCertificateRequested();
10870 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810871
10872 EXPECT_EQ(1, d.on_certificate_requested_count());
10873 EXPECT_FALSE(d.received_data_before_response());
10874 EXPECT_EQ(0, d.bytes_received());
10875
10876 // Send a certificate.
10877 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510878 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810879
10880 // The private key cannot sign anything, so we report an error.
10881 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
10882 EXPECT_EQ(1, d.response_started_count());
10883 EXPECT_FALSE(d.received_data_before_response());
10884 EXPECT_EQ(0, d.bytes_received());
10885
10886 // The private key should have been used.
10887 EXPECT_EQ(1, private_key->sign_count());
10888 }
10889
10890 // Close all connections and clear the session cache to force a new handshake.
10891 default_context_.http_transaction_factory()
10892 ->GetSession()
10893 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710894 default_context_.http_transaction_factory()
10895 ->GetSession()
10896 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810897
10898 // The bad identity should have been evicted from the cache, so connecting
10899 // again should call OnCertificateRequested again.
10900 {
10901 SSLClientAuthTestDelegate d;
10902 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10903 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10904 TRAFFIC_ANNOTATION_FOR_TESTS));
10905
10906 r->Start();
10907 EXPECT_TRUE(r->is_pending());
10908
Wez0e717112018-06-18 23:09:2210909 d.RunUntilCertificateRequested();
10910 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810911
10912 EXPECT_EQ(1, d.on_certificate_requested_count());
10913 EXPECT_FALSE(d.received_data_before_response());
10914 EXPECT_EQ(0, d.bytes_received());
10915
10916 // There should have been no additional uses of the private key.
10917 EXPECT_EQ(1, private_key->sign_count());
10918 }
10919}
10920
10921// Test that cached private keys that fail to sign anything trigger a
10922// retry. This is so we handle unplugged smartcards
10923// gracefully. https://crbug.com/813022.
10924TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
10925 std::unique_ptr<FakeClientCertIdentity> identity =
10926 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10927 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10928 ASSERT_TRUE(identity);
10929 scoped_refptr<TestSSLPrivateKey> private_key =
10930 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10931
10932 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10933 net::SSLServerConfig ssl_config;
10934 ssl_config.client_cert_type =
10935 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10936 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10937 test_server.AddDefaultHandlers(
10938 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10939 ASSERT_TRUE(test_server.Start());
10940
10941 // Connect with a client certificate to put it in the client auth cache.
10942 {
10943 SSLClientAuthTestDelegate d;
10944 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10945 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10946 TRAFFIC_ANNOTATION_FOR_TESTS));
10947
10948 r->Start();
10949 EXPECT_TRUE(r->is_pending());
10950
Wez0e717112018-06-18 23:09:2210951 d.RunUntilCertificateRequested();
10952 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810953
10954 EXPECT_EQ(1, d.on_certificate_requested_count());
10955 EXPECT_FALSE(d.received_data_before_response());
10956 EXPECT_EQ(0, d.bytes_received());
10957
10958 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510959 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810960
10961 EXPECT_EQ(OK, d.request_status());
10962 EXPECT_EQ(1, d.response_started_count());
10963 EXPECT_FALSE(d.received_data_before_response());
10964 EXPECT_NE(0, d.bytes_received());
10965
10966 // The private key should have been used.
10967 EXPECT_EQ(1, private_key->sign_count());
10968 }
10969
10970 // Close all connections and clear the session cache to force a new handshake.
10971 default_context_.http_transaction_factory()
10972 ->GetSession()
10973 ->CloseAllConnections();
Daniel McArdle3a663d62019-01-31 00:48:4710974 default_context_.http_transaction_factory()
10975 ->GetSession()
10976 ->ClearSSLSessionCache();
David Benjamin76a40ad2018-02-24 22:22:0810977
10978 // Cause the private key to fail. Connecting again should attempt to use it,
10979 // notice the failure, and then request a new identity via
10980 // OnCertificateRequested.
10981 private_key->set_fail_signing(true);
10982
10983 {
10984 SSLClientAuthTestDelegate d;
10985 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10986 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10987 TRAFFIC_ANNOTATION_FOR_TESTS));
10988
10989 r->Start();
10990 EXPECT_TRUE(r->is_pending());
10991
Wez0e717112018-06-18 23:09:2210992 d.RunUntilCertificateRequested();
10993 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:0810994
10995 // There was an additional signing call on the private key (the one which
10996 // failed).
10997 EXPECT_EQ(2, private_key->sign_count());
10998
10999 // That caused another OnCertificateRequested call.
11000 EXPECT_EQ(1, d.on_certificate_requested_count());
11001 EXPECT_FALSE(d.received_data_before_response());
11002 EXPECT_EQ(0, d.bytes_received());
11003 }
11004}
11005
[email protected]316c1e5e2012-09-12 15:17:4411006TEST_F(HTTPSRequestTest, ResumeTest) {
11007 // Test that we attempt a session resume when making two connections to the
11008 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:2211009 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4411010 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2211011 SpawnedTestServer test_server(
11012 SpawnedTestServer::TYPE_HTTPS,
11013 ssl_options,
11014 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4411015 ASSERT_TRUE(test_server.Start());
11016
Daniel McArdle3a663d62019-01-31 00:48:4711017 default_context_.http_transaction_factory()
11018 ->GetSession()
11019 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4411020
11021 {
11022 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611023 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611024 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
11025 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4411026
[email protected]f7022f32014-08-21 16:32:1911027 r->Start();
11028 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4411029
Wez2a31b222018-06-07 22:07:1511030 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4411031
11032 EXPECT_EQ(1, d.response_started_count());
11033 }
11034
11035 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
11036 CloseAllConnections();
11037
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 // The response will look like;
Steven Valdez0ef94d02018-11-19 23:28:1311050 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]316c1e5e2012-09-12 15:17:4411051 // insert abc
11052 // lookup abc
11053 // insert xyz
11054 //
11055 // With a newline at the end which makes the split think that there are
11056 // four lines.
11057
11058 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2911059 std::vector<std::string> lines = base::SplitString(
11060 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Steven Valdez0ef94d02018-11-19 23:28:1311061 ASSERT_EQ(5u, lines.size()) << d.data_received();
[email protected]316c1e5e2012-09-12 15:17:4411062
11063 std::string session_id;
11064
Steven Valdez0ef94d02018-11-19 23:28:1311065 for (size_t i = 0; i < 3; i++) {
brettw3a2c6902015-07-06 19:43:2911066 std::vector<std::string> parts = base::SplitString(
11067 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4411068 ASSERT_EQ(2u, parts.size());
Steven Valdez0ef94d02018-11-19 23:28:1311069 if (i % 2 == 1) {
[email protected]316c1e5e2012-09-12 15:17:4411070 EXPECT_EQ("insert", parts[0]);
11071 session_id = parts[1];
11072 } else {
11073 EXPECT_EQ("lookup", parts[0]);
Steven Valdez0ef94d02018-11-19 23:28:1311074 if (i != 0)
11075 EXPECT_EQ(session_id, parts[1]);
[email protected]316c1e5e2012-09-12 15:17:4411076 }
11077 }
11078 }
11079}
11080
11081TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
11082 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
11083 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2211084 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4411085 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2211086 SpawnedTestServer test_server(
11087 SpawnedTestServer::TYPE_HTTPS,
11088 ssl_options,
11089 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4411090 ASSERT_TRUE(test_server.Start());
11091
Daniel McArdle3a663d62019-01-31 00:48:4711092 default_context_.http_transaction_factory()
11093 ->GetSession()
11094 ->ClearSSLSessionCache();
[email protected]316c1e5e2012-09-12 15:17:4411095
11096 {
11097 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611098 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0411099 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1611100 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4411101
[email protected]f7022f32014-08-21 16:32:1911102 r->Start();
11103 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4411104
Wez2a31b222018-06-07 22:07:1511105 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4411106
11107 EXPECT_EQ(1, d.response_started_count());
11108 }
11109
11110 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4111111 HttpNetworkSession::Context session_context;
11112 session_context.host_resolver = default_context_.host_resolver();
11113 session_context.cert_verifier = default_context_.cert_verifier();
11114 session_context.transport_security_state =
11115 default_context_.transport_security_state();
11116 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2011117 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4111118 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5911119 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4111120 session_context.ssl_config_service = default_context_.ssl_config_service();
11121 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4411122 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4111123 session_context.http_server_properties =
11124 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4411125
mmenke6ddfbea2017-05-31 21:48:4111126 HttpNetworkSession network_session(HttpNetworkSession::Params(),
11127 session_context);
zhongyi4928bd52017-02-08 02:16:2711128 std::unique_ptr<HttpCache> cache(
11129 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
11130 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4411131
11132 default_context_.set_http_transaction_factory(cache.get());
11133
11134 {
11135 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611136 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611137 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
11138 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4411139
[email protected]f7022f32014-08-21 16:32:1911140 r->Start();
11141 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4411142
Wez2a31b222018-06-07 22:07:1511143 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4411144
[email protected]316c1e5e2012-09-12 15:17:4411145 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0411146 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]316c1e5e2012-09-12 15:17:4411147 }
11148}
11149
Daniel McArdleda3fa942019-02-15 16:41:2111150// Test that sessions started with privacy mode enabled cannot be resumed when
11151// it is disabled, and vice versa.
11152TEST_F(HTTPSRequestTest, NoSessionResumptionBetweenPrivacyModes) {
11153 // Start a server.
11154 SpawnedTestServer test_server(
11155 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(),
11156 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11157 ASSERT_TRUE(test_server.Start());
11158 const auto url = test_server.GetURL("/");
11159
11160 auto ConnectAndCheckHandshake = [this, url](bool allow_credentials,
11161 auto expected_handshake) {
11162 // Construct request and indirectly set the privacy mode.
11163 TestDelegate d;
11164 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11165 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11166 r->set_allow_credentials(allow_credentials);
11167
11168 // Start the request and check the SSL handshake type.
11169 r->Start();
11170 EXPECT_TRUE(r->is_pending());
11171 d.RunUntilComplete();
11172 EXPECT_EQ(1, d.response_started_count());
11173 EXPECT_EQ(expected_handshake, r->ssl_info().handshake_type);
11174 };
11175
11176 // Exhaustively check all pairs of privacy mode values. Note that we are using
11177 // allow_credentials to indirectly enable/disable privacy mode.
11178 const bool kAllowCredentialsValues[] = {false, true};
11179 for (const auto allow_creds_1 : kAllowCredentialsValues) {
11180 for (const auto allow_creds_2 : kAllowCredentialsValues) {
11181 SCOPED_TRACE(base::StringPrintf("allow_creds_1=%d, allow_creds_2=%d",
11182 allow_creds_1, allow_creds_2));
11183
11184 // The session cache starts off empty, so we expect a full handshake.
11185 ConnectAndCheckHandshake(allow_creds_1, SSLInfo::HANDSHAKE_FULL);
11186
11187 // The second handshake depends on whether we are using the same session
11188 // cache as the first request.
11189 ConnectAndCheckHandshake(allow_creds_2, allow_creds_1 == allow_creds_2
11190 ? SSLInfo::HANDSHAKE_RESUME
11191 : SSLInfo::HANDSHAKE_FULL);
11192 // Flush both session caches.
11193 auto* network_session =
11194 default_context_.http_transaction_factory()->GetSession();
11195 network_session->ClearSSLSessionCache();
11196 }
11197 }
11198}
11199
Bence Béky98447b12018-05-08 03:14:0111200class HTTPSFallbackTest : public TestWithScopedTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:5511201 public:
fdorayf33fede2017-05-11 21:18:1011202 HTTPSFallbackTest() : context_(true) {
David Benjamin151ec6b2019-08-02 19:38:5211203 ssl_config_service_ =
11204 std::make_unique<TestSSLConfigService>(SSLContextConfig());
davidben095ebb52017-04-12 22:23:3411205 context_.set_ssl_config_service(ssl_config_service_.get());
11206 }
Chris Watkins7a41d3552017-12-01 02:13:2711207 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5511208
11209 protected:
davidben095ebb52017-04-12 22:23:3411210 TestSSLConfigService* ssl_config_service() {
11211 return ssl_config_service_.get();
11212 }
11213
[email protected]48d2b7c52014-06-27 01:16:5511214 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
11215 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0011216 context_.Init();
11217 delegate_.set_allow_certificate_errors(true);
11218
[email protected]48d2b7c52014-06-27 01:16:5511219 SpawnedTestServer test_server(
11220 SpawnedTestServer::TYPE_HTTPS,
11221 ssl_options,
11222 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11223 ASSERT_TRUE(test_server.Start());
11224
tommycli59a63432015-11-06 00:10:5511225 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1611226 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5511227 request_->Start();
11228
Wez2a31b222018-06-07 22:07:1511229 delegate_.RunUntilComplete();
[email protected]48d2b7c52014-06-27 01:16:5511230 }
11231
davidben095ebb52017-04-12 22:23:3411232 void ExpectConnection(int version) {
11233 EXPECT_EQ(1, delegate_.response_started_count());
11234 EXPECT_NE(0, delegate_.bytes_received());
11235 EXPECT_EQ(version, SSLConnectionStatusToVersion(
11236 request_->ssl_info().connection_status));
11237 }
11238
[email protected]48d2b7c52014-06-27 01:16:5511239 void ExpectFailure(int error) {
11240 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5011241 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5511242 }
11243
11244 private:
Ryan Sleevib8449e02018-07-15 04:31:0711245 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5511246 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4711247 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3611248 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:5511249};
11250
davidbenb127ca82015-06-15 19:05:4211251// Tests the TLS 1.0 fallback doesn't happen.
11252TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5511253 SpawnedTestServer::SSLOptions ssl_options(
11254 SpawnedTestServer::SSLOptions::CERT_OK);
11255 ssl_options.tls_intolerant =
11256 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
11257
11258 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5511259 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4211260}
11261
davidben5a312152016-06-27 22:11:4711262// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5511263TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4211264 SpawnedTestServer::SSLOptions ssl_options(
11265 SpawnedTestServer::SSLOptions::CERT_OK);
11266 ssl_options.tls_intolerant =
11267 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
11268
11269 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5511270 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
11271}
11272
David Benjamind61bd532019-04-23 21:11:3711273// Tests the TLS 1.2 fallback doesn't happen.
11274TEST_F(HTTPSFallbackTest, TLSv1_2NoFallback) {
davidben095ebb52017-04-12 22:23:3411275 SpawnedTestServer::SSLOptions ssl_options(
11276 SpawnedTestServer::SSLOptions::CERT_OK);
11277 ssl_options.tls_intolerant =
11278 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
davidben095ebb52017-04-12 22:23:3411279
11280 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
David Benjamind61bd532019-04-23 21:11:3711281 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidben095ebb52017-04-12 22:23:3411282}
11283
Bence Béky98447b12018-05-08 03:14:0111284class HTTPSSessionTest : public TestWithScopedTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:2411285 public:
fdorayf33fede2017-05-11 21:18:1011286 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5911287 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2411288
11289 default_context_.set_network_delegate(&default_network_delegate_);
11290 default_context_.set_cert_verifier(&cert_verifier_);
11291 default_context_.Init();
11292 }
Chris Watkins7a41d3552017-12-01 02:13:2711293 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2411294
11295 protected:
11296 MockCertVerifier cert_verifier_;
11297 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
11298 TestURLRequestContext default_context_;
11299};
11300
11301// Tests that session resumption is not attempted if an invalid certificate
11302// is presented.
11303TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
11304 SpawnedTestServer::SSLOptions ssl_options;
11305 ssl_options.record_resume = true;
11306 SpawnedTestServer test_server(
11307 SpawnedTestServer::TYPE_HTTPS,
11308 ssl_options,
11309 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11310 ASSERT_TRUE(test_server.Start());
11311
Daniel McArdle3a663d62019-01-31 00:48:4711312 default_context_.http_transaction_factory()
11313 ->GetSession()
11314 ->ClearSSLSessionCache();
[email protected]a8fed1742013-12-27 02:14:2411315
11316 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5911317 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2411318 {
11319 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611320 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Jesse Selover94c9a942019-01-16 01:18:0411321 test_server.GetURL("/"), DEFAULT_PRIORITY, &d,
rhalavatib7bd7c792017-04-27 05:25:1611322 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2411323
[email protected]f7022f32014-08-21 16:32:1911324 r->Start();
11325 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2411326
Wez2a31b222018-06-07 22:07:1511327 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2411328
11329 EXPECT_EQ(1, d.response_started_count());
11330 }
11331
11332 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
11333 CloseAllConnections();
11334
11335 // Now change the certificate to be acceptable (so that the response is
11336 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5911337 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2411338 {
11339 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611340 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611341 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
11342 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2411343
[email protected]f7022f32014-08-21 16:32:1911344 r->Start();
11345 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2411346
Wez2a31b222018-06-07 22:07:1511347 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2411348
[email protected]a8fed1742013-12-27 02:14:2411349 EXPECT_EQ(1, d.response_started_count());
Jesse Selover94c9a942019-01-16 01:18:0411350 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
[email protected]a8fed1742013-12-27 02:14:2411351 }
11352}
11353
[email protected]dffe8242012-03-20 15:14:2711354// This the fingerprint of the "Testing CA" certificate used by the testserver.
11355// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5811356static const SHA256HashValue kOCSPTestCertFingerprint = {{
11357 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
11358 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
11359 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1511360}};
[email protected]dffe8242012-03-20 15:14:2711361
[email protected]51523f52013-07-31 21:57:2811362// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
11363// testserver.
mattm0b12a6f2016-11-29 19:57:1611364static const SHA256HashValue kOCSPTestCertSPKI = {{
11365 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
11366 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
11367 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
11368}};
[email protected]51523f52013-07-31 21:57:2811369
[email protected]dffe8242012-03-20 15:14:2711370// This is the policy OID contained in the certificates that testserver
11371// generates.
11372static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
11373
11374class HTTPSOCSPTest : public HTTPSRequestTest {
11375 public:
11376 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0911377 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0811378 ev_test_policy_(
11379 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
11380 kOCSPTestCertFingerprint,
11381 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0211382 }
11383
dcheng67be2b1f2014-10-27 21:47:2911384 void SetUp() override {
Matt Muellera4aaa9d2019-04-24 21:09:1411385 cert_net_fetcher_ = base::MakeRefCounted<CertNetFetcherImpl>();
11386 cert_verifier_ = CertVerifier::CreateDefault(cert_net_fetcher_);
11387 context_.set_cert_verifier(cert_verifier_.get());
Ryan Sleevi8a9c9c12018-05-09 02:36:2311388 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
[email protected]ef2bf422012-05-11 03:27:0911389 context_.Init();
[email protected]dffe8242012-03-20 15:14:2711390
Matt Muellera4aaa9d2019-04-24 21:09:1411391 cert_net_fetcher_->SetURLRequestContext(&context_);
Ryan Sleevi24fe2682018-08-16 21:33:4611392 context_.cert_verifier()->SetConfig(GetCertVerifierConfig());
11393
[email protected]cba24642014-08-15 20:49:5911394 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2011395 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
Matt Mueller09c8fd9a2019-05-04 00:37:2411396 ASSERT_TRUE(root_cert);
[email protected]90499482013-06-01 00:39:5011397 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2711398
svaldez2135be52016-04-20 16:34:5311399#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0911400 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2711401#endif
11402 }
11403
dadrian612337a2016-07-20 22:36:5811404 void DoConnectionWithDelegate(
11405 const SpawnedTestServer::SSLOptions& ssl_options,
11406 TestDelegate* delegate,
11407 SSLInfo* out_ssl_info) {
11408 // Always overwrite |out_ssl_info|.
11409 out_ssl_info->Reset();
11410
[email protected]ce7d0cbc2013-05-03 18:57:2211411 SpawnedTestServer test_server(
11412 SpawnedTestServer::TYPE_HTTPS,
11413 ssl_options,
11414 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2711415 ASSERT_TRUE(test_server.Start());
11416
dadrian612337a2016-07-20 22:36:5811417 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1611418 std::unique_ptr<URLRequest> r(
11419 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
11420 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911421 r->Start();
[email protected]dffe8242012-03-20 15:14:2711422
Wez2a31b222018-06-07 22:07:1511423 delegate->RunUntilComplete();
dadrian612337a2016-07-20 22:36:5811424 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2711425
dadrian612337a2016-07-20 22:36:5811426 *out_ssl_info = r->ssl_info();
11427 }
11428
11429 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
11430 CertStatus* out_cert_status) {
11431 // Always overwrite |out_cert_status|.
11432 *out_cert_status = 0;
11433
11434 TestDelegate d;
11435 SSLInfo ssl_info;
11436 ASSERT_NO_FATAL_FAILURE(
11437 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
11438
11439 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2711440 }
11441
dcheng67be2b1f2014-10-27 21:47:2911442 ~HTTPSOCSPTest() override {
Matt Muellera4aaa9d2019-04-24 21:09:1411443 cert_net_fetcher_->Shutdown();
svaldez2135be52016-04-20 16:34:5311444#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1811445 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2711446#endif
11447 }
11448
[email protected]a13234c2012-03-20 21:45:0211449 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4611450 // GetCertVerifierConfig() configures the URLRequestContext that will be used
11451 // for making connections to the testserver. This can be overridden in test
11452 // subclasses for different behaviour.
11453 virtual CertVerifier::Config GetCertVerifierConfig() {
11454 CertVerifier::Config config;
11455 config.enable_rev_checking = true;
11456 return config;
[email protected]a13234c2012-03-20 21:45:0211457 }
11458
danakj8522a25b2016-04-16 00:17:3611459 std::unique_ptr<ScopedTestRoot> test_root_;
Ryan Sleevib8449e02018-07-15 04:31:0711460 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
Matt Muellera4aaa9d2019-04-24 21:09:1411461 scoped_refptr<CertNetFetcherImpl> cert_net_fetcher_;
11462 std::unique_ptr<CertVerifier> cert_verifier_;
[email protected]ef2bf422012-05-11 03:27:0911463 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3611464 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2711465};
11466
Matt Mueller36c3b102019-06-18 02:28:2011467static bool UsingBuiltinCertVerifier() {
11468#if defined(OS_FUCHSIA)
11469 return true;
11470#elif BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED)
11471 if (base::FeatureList::IsEnabled(features::kCertVerifierBuiltinFeature))
11472 return true;
11473#endif
11474 return false;
11475}
11476
[email protected]a13234c2012-03-20 21:45:0211477static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
Matt Mueller36c3b102019-06-18 02:28:2011478 if (UsingBuiltinCertVerifier())
11479 return 0;
mattmaf868e72016-09-23 23:25:2011480#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0211481 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
11482 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0411483 // TODO(eroman): Should this also be the return value for
11484 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0211485 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
11486#else
11487 return 0;
11488#endif
11489}
11490
[email protected]3a86a712013-07-30 07:16:2011491// SystemSupportsHardFailRevocationChecking returns true iff the current
11492// operating system supports revocation checking and can distinguish between
11493// situations where a given certificate lacks any revocation information (eg:
11494// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
11495// revocation information cannot be obtained (eg: the CRL was unreachable).
11496// If it does not, then tests which rely on 'hard fail' behaviour should be
11497// skipped.
11498static bool SystemSupportsHardFailRevocationChecking() {
Matt Mueller36c3b102019-06-18 02:28:2011499 if (UsingBuiltinCertVerifier())
11500 return true;
11501#if defined(OS_WIN) || defined(USE_NSS_CERTS)
[email protected]3a86a712013-07-30 07:16:2011502 return true;
11503#else
11504 return false;
11505#endif
11506}
11507
[email protected]a13234c2012-03-20 21:45:0211508// SystemUsesChromiumEVMetadata returns true iff the current operating system
11509// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
11510// several tests are effected because our testing EV certificate won't be
11511// recognised as EV.
11512static bool SystemUsesChromiumEVMetadata() {
Matt Mueller36c3b102019-06-18 02:28:2011513 if (UsingBuiltinCertVerifier())
11514 return true;
Eric Roman5f8d9d22017-10-17 02:32:5211515#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0111516 return true;
Eric Roman5f8d9d22017-10-17 02:32:5211517#else
11518 return false;
[email protected]05454a432012-03-20 20:04:0111519#endif
11520}
11521
mattmaf868e72016-09-23 23:25:2011522// Returns the expected CertStatus for tests that expect an online revocation
11523// check failure as a result of checking a test EV cert, which will not
11524// actually trigger an online revocation check on some platforms.
11525static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
11526 if (SystemUsesChromiumEVMetadata()) {
11527 return ExpectedCertStatusForFailedOnlineRevocationCheck();
11528 } else {
11529 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
11530 // be enabled, and thus there will not be a revocation check to fail.
11531 return 0u;
11532 }
11533}
11534
[email protected]b6f2de32012-08-17 04:35:0811535static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3911536#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0211537 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
11538 return false;
11539#else
11540 return true;
11541#endif
11542}
11543
davidbend1fb2f12014-11-08 02:51:0011544static bool SystemSupportsOCSPStapling() {
Matt Mueller36c3b102019-06-18 02:28:2011545 if (UsingBuiltinCertVerifier())
11546 return true;
Matt Mueller7f60dc42019-04-26 22:47:1011547#if defined(OS_ANDROID)
mathpc992e602015-10-21 20:34:0311548 return false;
Matt Mueller7f60dc42019-04-26 22:47:1011549#elif defined(OS_MACOSX)
11550 // The SecTrustSetOCSPResponse function exists since macOS 10.9+, but does
11551 // not actually do anything until 10.12.
11552 if (base::mac::IsAtLeastOS10_12())
11553 return true;
11554 return false;
11555#else
11556 return true;
mathpc992e602015-10-21 20:34:0311557#endif
davidbend1fb2f12014-11-08 02:51:0011558}
11559
[email protected]dffe8242012-03-20 15:14:2711560TEST_F(HTTPSOCSPTest, Valid) {
11561 if (!SystemSupportsOCSP()) {
11562 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11563 return;
11564 }
11565
[email protected]ce7d0cbc2013-05-03 18:57:2211566 SpawnedTestServer::SSLOptions ssl_options(
11567 SpawnedTestServer::SSLOptions::CERT_AUTO);
11568 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2711569
[email protected]924e9f92012-12-16 22:00:5311570 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211571 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711572
11573 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11574
[email protected]a13234c2012-03-20 21:45:0211575 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11576 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2711577
11578 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11579}
11580
11581TEST_F(HTTPSOCSPTest, Revoked) {
11582 if (!SystemSupportsOCSP()) {
11583 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11584 return;
11585 }
11586
[email protected]ce7d0cbc2013-05-03 18:57:2211587 SpawnedTestServer::SSLOptions ssl_options(
11588 SpawnedTestServer::SSLOptions::CERT_AUTO);
11589 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2711590
11591 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211592 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711593
[email protected]dffe8242012-03-20 15:14:2711594 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2711595 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11596 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11597}
11598
11599TEST_F(HTTPSOCSPTest, Invalid) {
11600 if (!SystemSupportsOCSP()) {
11601 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11602 return;
11603 }
11604
[email protected]ce7d0cbc2013-05-03 18:57:2211605 SpawnedTestServer::SSLOptions ssl_options(
11606 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811607 ssl_options.ocsp_status =
11608 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2711609
[email protected]924e9f92012-12-16 22:00:5311610 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211611 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711612
Matt Mueller36c3b102019-06-18 02:28:2011613 if (UsingBuiltinCertVerifier()) {
11614 // TODO(649017): This test uses soft-fail revocation checking, but returns
11615 // an invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
11616 // doesn't consider this a candidate for soft-fail (only considers
11617 // network-level failures as skippable).
11618 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11619 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11620 } else {
11621 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
11622 cert_status & CERT_STATUS_ALL_ERRORS);
11623 }
[email protected]dffe8242012-03-20 15:14:2711624
11625 // Without a positive OCSP response, we shouldn't show the EV status.
11626 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11627 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11628}
[email protected]a13234c2012-03-20 21:45:0211629
Matt Mueller5339d862018-05-02 18:53:5711630TEST_F(HTTPSOCSPTest, IntermediateValid) {
11631 if (!SystemSupportsOCSP()) {
11632 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11633 return;
11634 }
11635
11636 SpawnedTestServer::SSLOptions ssl_options(
11637 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11638 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11639 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11640
11641 CertStatus cert_status;
11642 DoConnection(ssl_options, &cert_status);
11643
11644 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11645
11646 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11647 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11648
11649 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11650}
11651
11652TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
11653 if (!SystemSupportsOCSP()) {
11654 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11655 return;
11656 }
11657
11658 SpawnedTestServer::SSLOptions ssl_options(
11659 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11660 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11661 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11662 // Use an OCSP response for the intermediate that would be too old for a leaf
11663 // cert, but is still valid for an intermediate.
11664 ssl_options.ocsp_intermediate_date =
11665 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
11666
11667 CertStatus cert_status;
11668 DoConnection(ssl_options, &cert_status);
11669
11670 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11671
11672 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11673 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11674
11675 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11676}
11677
11678TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
11679 if (!SystemSupportsOCSP()) {
11680 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11681 return;
11682 }
11683
11684 SpawnedTestServer::SSLOptions ssl_options(
11685 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11686 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11687 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11688 ssl_options.ocsp_intermediate_date =
11689 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
11690
11691 CertStatus cert_status;
11692 DoConnection(ssl_options, &cert_status);
11693
Matt Mueller36c3b102019-06-18 02:28:2011694 if (UsingBuiltinCertVerifier()) {
11695 // The builtin verifier enforces the baseline requirements for max age of an
11696 // intermediate's OCSP response.
11697 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11698 cert_status & CERT_STATUS_ALL_ERRORS);
11699 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11700 } else {
11701 // The platform verifiers are more lenient.
11702 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11703 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11704 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11705 }
Matt Mueller5339d862018-05-02 18:53:5711706 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11707}
11708
11709TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
11710 if (!SystemSupportsOCSP()) {
11711 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11712 return;
11713 }
11714
11715 SpawnedTestServer::SSLOptions ssl_options(
11716 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11717 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11718 ssl_options.ocsp_intermediate_status =
11719 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11720
11721 CertStatus cert_status;
11722 DoConnection(ssl_options, &cert_status);
11723
11724#if defined(OS_WIN)
11725 // TODO(mattm): why does CertVerifyProcWin accept this?
11726 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11727#else
11728 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11729#endif
11730 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11731 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11732}
11733
davidbend1fb2f12014-11-08 02:51:0011734TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0311735 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011736 LOG(WARNING)
11737 << "Skipping test because system doesn't support OCSP stapling";
11738 return;
11739 }
11740
11741 SpawnedTestServer::SSLOptions ssl_options(
11742 SpawnedTestServer::SSLOptions::CERT_AUTO);
11743 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11744 ssl_options.staple_ocsp_response = true;
11745 ssl_options.ocsp_server_unavailable = true;
11746
11747 CertStatus cert_status;
11748 DoConnection(ssl_options, &cert_status);
11749
11750 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11751
11752 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11753 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11754
11755 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11756}
11757
davidben6c3191b2014-11-21 22:38:0411758// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4811759#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0411760#define MAYBE_RevokedStapled DISABLED_RevokedStapled
11761#else
11762#define MAYBE_RevokedStapled RevokedStapled
11763#endif
11764TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0311765 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011766 LOG(WARNING)
11767 << "Skipping test because system doesn't support OCSP stapling";
11768 return;
11769 }
11770
11771 SpawnedTestServer::SSLOptions ssl_options(
11772 SpawnedTestServer::SSLOptions::CERT_AUTO);
11773 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11774 ssl_options.staple_ocsp_response = true;
11775 ssl_options.ocsp_server_unavailable = true;
11776
11777 CertStatus cert_status;
11778 DoConnection(ssl_options, &cert_status);
11779
11780 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11781 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11782 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11783}
11784
dadrian612337a2016-07-20 22:36:5811785static const struct OCSPVerifyTestData {
11786 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
11787 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
11788 OCSPVerifyResult::ResponseStatus response_status;
11789 bool has_revocation_status;
11790 OCSPRevocationStatus cert_status;
11791} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3111792 // 0
dadrian612337a2016-07-20 22:36:5811793 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11794 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11795 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11796 OCSPVerifyResult::PROVIDED,
11797 true,
11798 OCSPRevocationStatus::GOOD},
11799
Eric Roman8673b812017-09-20 18:57:3111800 // 1
dadrian612337a2016-07-20 22:36:5811801 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11802 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11803 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11804 OCSPVerifyResult::INVALID_DATE,
11805 false,
11806 OCSPRevocationStatus::UNKNOWN},
11807
Eric Roman8673b812017-09-20 18:57:3111808 // 2
dadrian612337a2016-07-20 22:36:5811809 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11810 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11811 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11812 OCSPVerifyResult::INVALID_DATE,
11813 false,
11814 OCSPRevocationStatus::UNKNOWN},
11815
Eric Roman8673b812017-09-20 18:57:3111816 // 3
dadrian612337a2016-07-20 22:36:5811817 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11818 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11819 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11820 OCSPVerifyResult::INVALID_DATE,
11821 false,
11822 OCSPRevocationStatus::UNKNOWN},
11823
Eric Roman8673b812017-09-20 18:57:3111824 // 4
dadrian612337a2016-07-20 22:36:5811825 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11826 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11827 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11828 OCSPVerifyResult::INVALID_DATE,
11829 false,
11830 OCSPRevocationStatus::UNKNOWN},
11831
Eric Roman8673b812017-09-20 18:57:3111832 // 5
dadrian612337a2016-07-20 22:36:5811833 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
11834 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11835 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11836 OCSPVerifyResult::ERROR_RESPONSE,
11837 false,
11838 OCSPRevocationStatus::UNKNOWN},
11839
Eric Roman8673b812017-09-20 18:57:3111840 // 6
dadrian612337a2016-07-20 22:36:5811841 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
11842 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11843 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11844 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
11845 false,
11846 OCSPRevocationStatus::UNKNOWN},
11847
Eric Roman8673b812017-09-20 18:57:3111848 // 7
dadrian612337a2016-07-20 22:36:5811849 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
11850 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11851 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11852 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
11853 false,
11854 OCSPRevocationStatus::UNKNOWN},
11855
Eric Roman8673b812017-09-20 18:57:3111856 // 8
dadrian612337a2016-07-20 22:36:5811857 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11858 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11859 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11860 OCSPVerifyResult::INVALID_DATE,
11861 false,
11862 OCSPRevocationStatus::UNKNOWN},
11863
Eric Roman8673b812017-09-20 18:57:3111864 // 9
dadrian612337a2016-07-20 22:36:5811865 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11866 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11867 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11868 OCSPVerifyResult::PROVIDED,
11869 true,
11870 OCSPRevocationStatus::UNKNOWN},
11871
Eric Roman8673b812017-09-20 18:57:3111872 // 10
dadrian612337a2016-07-20 22:36:5811873 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11874 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11875 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11876 OCSPVerifyResult::INVALID_DATE,
11877 false,
11878 OCSPRevocationStatus::UNKNOWN},
11879
Eric Roman8673b812017-09-20 18:57:3111880 // 11
dadrian612337a2016-07-20 22:36:5811881 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11882 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11883 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11884 OCSPVerifyResult::INVALID_DATE,
11885 false,
11886 OCSPRevocationStatus::UNKNOWN},
11887
Eric Roman8673b812017-09-20 18:57:3111888 // 12
dadrian612337a2016-07-20 22:36:5811889 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11890 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11891 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
11892 OCSPVerifyResult::BAD_PRODUCED_AT,
11893 false,
11894 OCSPRevocationStatus::UNKNOWN},
11895
Eric Roman8673b812017-09-20 18:57:3111896 // 13
dadrian612337a2016-07-20 22:36:5811897 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11898 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11899 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11900 OCSPVerifyResult::BAD_PRODUCED_AT,
11901 false,
11902 OCSPRevocationStatus::UNKNOWN},
11903
Eric Roman8673b812017-09-20 18:57:3111904 // 14
dadrian612337a2016-07-20 22:36:5811905 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11906 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11907 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11908 OCSPVerifyResult::BAD_PRODUCED_AT,
11909 false,
11910 OCSPRevocationStatus::UNKNOWN},
11911
Eric Roman8673b812017-09-20 18:57:3111912 // 15
dadrian612337a2016-07-20 22:36:5811913 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11914 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11915 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11916 OCSPVerifyResult::PROVIDED,
11917 true,
11918 OCSPRevocationStatus::GOOD},
11919
Eric Roman8673b812017-09-20 18:57:3111920 // 16
dadrian612337a2016-07-20 22:36:5811921 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11922 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11923 {SpawnedTestServer::SSLOptions::OCSP_OK,
11924 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11925 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11926 OCSPVerifyResult::PROVIDED,
11927 true,
11928 OCSPRevocationStatus::GOOD},
11929
Eric Roman8673b812017-09-20 18:57:3111930 // 17
dadrian612337a2016-07-20 22:36:5811931 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11932 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11933 {SpawnedTestServer::SSLOptions::OCSP_OK,
11934 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11935 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11936 OCSPVerifyResult::PROVIDED,
11937 true,
11938 OCSPRevocationStatus::GOOD},
11939
Eric Roman8673b812017-09-20 18:57:3111940 // 18
dadrian612337a2016-07-20 22:36:5811941 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11942 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11943 {SpawnedTestServer::SSLOptions::OCSP_OK,
11944 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11945 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11946 OCSPVerifyResult::PROVIDED,
11947 true,
11948 OCSPRevocationStatus::GOOD},
11949
Eric Roman8673b812017-09-20 18:57:3111950 // 19
dadrian612337a2016-07-20 22:36:5811951 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11952 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11953 {SpawnedTestServer::SSLOptions::OCSP_OK,
11954 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11955 {SpawnedTestServer::SSLOptions::OCSP_OK,
11956 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11957 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11958 OCSPVerifyResult::INVALID_DATE,
11959 false,
11960 OCSPRevocationStatus::UNKNOWN},
11961
Eric Roman8673b812017-09-20 18:57:3111962 // 20
dadrian612337a2016-07-20 22:36:5811963 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11964 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11965 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11966 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11967 {SpawnedTestServer::SSLOptions::OCSP_OK,
11968 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11969 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11970 OCSPVerifyResult::PROVIDED,
11971 true,
11972 OCSPRevocationStatus::REVOKED},
11973
Eric Roman8673b812017-09-20 18:57:3111974 // 21
dadrian612337a2016-07-20 22:36:5811975 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11976 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11977 {SpawnedTestServer::SSLOptions::OCSP_OK,
11978 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11979 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11980 OCSPVerifyResult::PROVIDED,
11981 true,
11982 OCSPRevocationStatus::UNKNOWN},
11983
Eric Roman8673b812017-09-20 18:57:3111984 // 22
dadrian612337a2016-07-20 22:36:5811985 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11986 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11987 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11988 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11989 {SpawnedTestServer::SSLOptions::OCSP_OK,
11990 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11991 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11992 OCSPVerifyResult::PROVIDED,
11993 true,
11994 OCSPRevocationStatus::UNKNOWN},
11995
Eric Roman8673b812017-09-20 18:57:3111996 // 23
dadrian612337a2016-07-20 22:36:5811997 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11998 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11999 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12000 OCSPVerifyResult::NO_MATCHING_RESPONSE,
12001 false,
12002 OCSPRevocationStatus::UNKNOWN},
12003
Eric Roman8673b812017-09-20 18:57:3112004 // 24
dadrian612337a2016-07-20 22:36:5812005 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
12006 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
12007 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12008 OCSPVerifyResult::NO_MATCHING_RESPONSE,
12009 false,
12010 OCSPRevocationStatus::UNKNOWN},
12011
Eric Roman8673b812017-09-20 18:57:3112012// These tests fail when using NSS for certificate verification, as NSS fails
12013// and doesn't return the partial path. As a result the OCSP checks being done
12014// at the CertVerifyProc layer cannot access the issuer certificate.
12015#if !defined(USE_NSS_CERTS)
12016 // 25
12017 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
12018 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
12019 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12020 OCSPVerifyResult::PROVIDED,
12021 true,
12022 OCSPRevocationStatus::REVOKED},
12023
12024 // 26
12025 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
12026 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
12027 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12028 OCSPVerifyResult::INVALID_DATE,
12029 false,
12030 OCSPRevocationStatus::UNKNOWN},
12031
12032 // 27
12033 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
12034 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
12035 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
12036 OCSPVerifyResult::INVALID_DATE,
12037 false,
12038 OCSPRevocationStatus::UNKNOWN},
12039#endif
dadrian612337a2016-07-20 22:36:5812040};
12041
12042class HTTPSOCSPVerifyTest
12043 : public HTTPSOCSPTest,
12044 public testing::WithParamInterface<OCSPVerifyTestData> {};
12045
Christos Froussios09e6ac42019-04-05 14:08:2012046// TODO(crbug.com/949958): The test is flaky on Mac
12047#if defined(OS_MACOSX)
12048#define MAYBE_VerifyResult DISABLED_VerifyResult
12049#else
12050#define MAYBE_VerifyResult VerifyResult
12051#endif
12052TEST_P(HTTPSOCSPVerifyTest, MAYBE_VerifyResult) {
dadrian612337a2016-07-20 22:36:5812053 SpawnedTestServer::SSLOptions ssl_options(
12054 SpawnedTestServer::SSLOptions::CERT_AUTO);
12055 OCSPVerifyTestData test = GetParam();
12056
12057 ssl_options.ocsp_responses = test.ocsp_responses;
12058 ssl_options.ocsp_produced = test.ocsp_produced;
12059 ssl_options.staple_ocsp_response = true;
12060
12061 SSLInfo ssl_info;
12062 OCSPErrorTestDelegate delegate;
12063 ASSERT_NO_FATAL_FAILURE(
12064 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
12065
12066 // The SSLInfo must be extracted from |delegate| on error, due to how
12067 // URLRequest caches certificate errors.
12068 if (delegate.have_certificate_errors()) {
12069 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
12070 ssl_info = delegate.ssl_info();
12071 }
12072
12073 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
12074
12075 if (test.has_revocation_status)
12076 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
12077}
12078
Victor Costan8fb98f6f2019-02-01 17:08:2912079INSTANTIATE_TEST_SUITE_P(OCSPVerify,
12080 HTTPSOCSPVerifyTest,
12081 testing::ValuesIn(kOCSPVerifyData));
dadrian612337a2016-07-20 22:36:5812082
mattm0b12a6f2016-11-29 19:57:1612083class HTTPSAIATest : public HTTPSOCSPTest {
12084 public:
Ryan Sleevi24fe2682018-08-16 21:33:4612085 CertVerifier::Config GetCertVerifierConfig() override {
12086 CertVerifier::Config config;
12087 return config;
mattm0b12a6f2016-11-29 19:57:1612088 }
12089};
12090
12091TEST_F(HTTPSAIATest, AIAFetching) {
12092 SpawnedTestServer::SSLOptions ssl_options(
12093 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
12094 SpawnedTestServer test_server(
12095 SpawnedTestServer::TYPE_HTTPS, ssl_options,
12096 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
12097 ASSERT_TRUE(test_server.Start());
12098
Ryan Sleevi5b4702a2018-04-06 22:23:5612099 // Unmark the certificate's OID as EV, which will disable revocation
12100 // checking.
12101 ev_test_policy_.reset();
12102
mattm0b12a6f2016-11-29 19:57:1612103 TestDelegate d;
12104 d.set_allow_certificate_errors(true);
12105 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612106 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
12107 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1612108
12109 r->Start();
12110 EXPECT_TRUE(r->is_pending());
12111
Wez2a31b222018-06-07 22:07:1512112 d.RunUntilComplete();
mattm0b12a6f2016-11-29 19:57:1612113
12114 EXPECT_EQ(1, d.response_started_count());
12115
12116 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4812117 EXPECT_EQ(OK, d.request_status());
12118 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12119 ASSERT_TRUE(r->ssl_info().cert);
12120 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1612121 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3412122 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1612123}
12124
[email protected]3a86a712013-07-30 07:16:2012125class HTTPSHardFailTest : public HTTPSOCSPTest {
12126 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4612127 CertVerifier::Config GetCertVerifierConfig() override {
12128 CertVerifier::Config config;
12129 config.require_rev_checking_local_anchors = true;
12130 return config;
[email protected]3a86a712013-07-30 07:16:2012131 }
12132};
12133
[email protected]3a86a712013-07-30 07:16:2012134TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
12135 if (!SystemSupportsOCSP()) {
12136 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12137 return;
12138 }
12139
12140 if (!SystemSupportsHardFailRevocationChecking()) {
12141 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
12142 << "revocation checking";
12143 return;
12144 }
12145
12146 SpawnedTestServer::SSLOptions ssl_options(
12147 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812148 ssl_options.ocsp_status =
12149 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2012150
12151 CertStatus cert_status;
12152 DoConnection(ssl_options, &cert_status);
12153
Matt Mueller36c3b102019-06-18 02:28:2012154 if (UsingBuiltinCertVerifier()) {
12155 // TODO(crbug.com/649017): Should we consider invalid response as
12156 // affirmatively revoked?
12157 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
12158 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
12159 } else {
12160 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
12161 }
[email protected]3a86a712013-07-30 07:16:2012162
12163 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0412164 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2012165 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12166}
12167
[email protected]a13234c2012-03-20 21:45:0212168class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
12169 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4612170 CertVerifier::Config GetCertVerifierConfig() override {
12171 CertVerifier::Config config;
12172 return config;
[email protected]a13234c2012-03-20 21:45:0212173 }
12174};
12175
12176TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
12177 if (!SystemSupportsOCSP()) {
12178 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12179 return;
12180 }
12181
[email protected]ce7d0cbc2013-05-03 18:57:2212182 SpawnedTestServer::SSLOptions ssl_options(
12183 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812184 ssl_options.ocsp_status =
12185 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0212186
[email protected]924e9f92012-12-16 22:00:5312187 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212188 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212189
mattmaf868e72016-09-23 23:25:2012190 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0212191 cert_status & CERT_STATUS_ALL_ERRORS);
12192
12193 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0812194 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12195 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212196}
12197
[email protected]be0fff62013-08-29 23:37:4812198TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
12199 if (!SystemSupportsOCSP()) {
12200 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12201 return;
12202 }
12203
12204 SpawnedTestServer::SSLOptions ssl_options(
12205 SpawnedTestServer::SSLOptions::CERT_AUTO);
12206 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]be0fff62013-08-29 23:37:4812207
12208 CertStatus cert_status;
12209 DoConnection(ssl_options, &cert_status);
12210
Matt Mueller36c3b102019-06-18 02:28:2012211 // Currently only works for Windows and OS X. When using NSS, it's not
12212 // possible to determine whether the check failed because of actual
12213 // revocation or because there was an OCSP failure.
12214 if (UsingBuiltinCertVerifier()) {
12215 // TODO(https://crbug.com/410574): Handle this in builtin verifier too?
12216 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12217 } else {
mattm1a282f52016-11-10 21:49:4212218#if defined(OS_WIN) || defined(OS_MACOSX)
Matt Mueller36c3b102019-06-18 02:28:2012219 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]be0fff62013-08-29 23:37:4812220#else
Matt Mueller36c3b102019-06-18 02:28:2012221 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]be0fff62013-08-29 23:37:4812222#endif
Matt Mueller36c3b102019-06-18 02:28:2012223 }
[email protected]be0fff62013-08-29 23:37:4812224
12225 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12226 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12227 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
12228}
12229
[email protected]a13234c2012-03-20 21:45:0212230TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
12231 if (!SystemSupportsOCSP()) {
12232 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12233 return;
12234 }
12235
[email protected]ce7d0cbc2013-05-03 18:57:2212236 SpawnedTestServer::SSLOptions ssl_options(
12237 SpawnedTestServer::SSLOptions::CERT_AUTO);
12238 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0212239
12240 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212241 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212242
12243 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12244
12245 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12246 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0812247 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12248 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212249}
12250
12251TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
12252 if (!SystemSupportsOCSP()) {
12253 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12254 return;
12255 }
12256
[email protected]ce7d0cbc2013-05-03 18:57:2212257 SpawnedTestServer::SSLOptions ssl_options(
12258 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812259 ssl_options.ocsp_status =
12260 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212261 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12262 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
12263 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0212264
12265 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212266 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212267
mattmaf868e72016-09-23 23:25:2012268 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0212269 cert_status & CERT_STATUS_ALL_ERRORS);
12270
12271 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0812272 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12273 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212274}
12275
[email protected]51523f52013-07-31 21:57:2812276TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
12277 if (!SystemSupportsOCSP()) {
12278 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12279 return;
12280 }
12281
12282 SpawnedTestServer::SSLOptions ssl_options(
12283 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812284 ssl_options.ocsp_status =
12285 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212286 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12287 cert_verifier_config.crl_set =
12288 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {});
12289 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2812290
12291 CertStatus cert_status;
12292 DoConnection(ssl_options, &cert_status);
12293
12294 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
12295 // revocation check for EV.
12296 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12297 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12298 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
12299 EXPECT_FALSE(
12300 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
12301}
12302
12303TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
12304 if (!SystemSupportsOCSP()) {
12305 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12306 return;
12307 }
12308
[email protected]ce7d0cbc2013-05-03 18:57:2212309 SpawnedTestServer::SSLOptions ssl_options(
12310 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812311 ssl_options.ocsp_status =
12312 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212313 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12314 cert_verifier_config.crl_set = CRLSet::EmptyCRLSetForTesting();
12315 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0212316
[email protected]51523f52013-07-31 21:57:2812317 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1212318 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212319
[email protected]51523f52013-07-31 21:57:2812320 // Even with a fresh CRLSet, we should still do online revocation checks when
12321 // the certificate chain isn't covered by the CRLSet, which it isn't in this
12322 // test.
mattmaf868e72016-09-23 23:25:2012323 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2812324 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0212325
[email protected]51523f52013-07-31 21:57:2812326 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0212327 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2812328 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212329}
12330
12331class HTTPSCRLSetTest : public HTTPSOCSPTest {
12332 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4612333 CertVerifier::Config GetCertVerifierConfig() override {
12334 CertVerifier::Config config;
12335 return config;
Ryan Sleevi5b4702a2018-04-06 22:23:5612336 }
12337
12338 void SetUp() override {
12339 HTTPSOCSPTest::SetUp();
12340
12341 // Unmark the certificate's OID as EV, which should disable revocation
12342 // checking (as per the user preference).
12343 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0212344 }
12345};
12346
12347TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2212348 SpawnedTestServer::SSLOptions ssl_options(
12349 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812350 ssl_options.ocsp_status =
12351 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2212352 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12353 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
12354 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0212355
[email protected]924e9f92012-12-16 22:00:5312356 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212357 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212358
12359 // If we're not trying EV verification then, even if the CRLSet has expired,
12360 // we don't fall back to online revocation checks.
12361 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12362 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12363 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12364}
[email protected]51523f52013-07-31 21:57:2812365
Ryan Sleevi5b4702a2018-04-06 22:23:5612366TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
12367 // Test that when online revocation checking is disabled, and the leaf
12368 // certificate is not EV, that no revocation checking actually happens.
12369 if (!SystemSupportsOCSP()) {
12370 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12371 return;
12372 }
12373
12374 SpawnedTestServer::SSLOptions ssl_options(
12375 SpawnedTestServer::SSLOptions::CERT_AUTO);
12376 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Ryan Sleevib369d712018-08-20 16:43:2212377
12378 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12379 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
12380 context_.cert_verifier()->SetConfig(cert_verifier_config);
Ryan Sleevi5b4702a2018-04-06 22:23:5612381
12382 CertStatus cert_status;
12383 DoConnection(ssl_options, &cert_status);
12384
12385 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12386
12387 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12388 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12389}
12390
[email protected]51523f52013-07-31 21:57:2812391TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2512392#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2812393 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12394 return;
12395#endif
12396
12397 SpawnedTestServer::SSLOptions ssl_options(
12398 SpawnedTestServer::SSLOptions::CERT_AUTO);
12399 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12400 ssl_options.cert_serial = 10;
Ryan Sleevib369d712018-08-20 16:43:2212401
12402 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12403 cert_verifier_config.crl_set =
12404 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {});
12405 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2812406
12407 CertStatus cert_status = 0;
12408 DoConnection(ssl_options, &cert_status);
12409
12410 // If the certificate is recorded as revoked in the CRLSet, that should be
12411 // reflected without online revocation checking.
12412 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12413 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612414 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2812415}
Adam Langleyea6d6782017-12-05 23:57:3312416
12417TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
12418#if defined(OS_ANDROID)
12419 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12420 return;
12421#endif
12422
12423 SpawnedTestServer::SSLOptions ssl_options(
12424 SpawnedTestServer::SSLOptions::CERT_AUTO);
12425 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12426 static const char kCommonName[] = "Test CN";
12427 ssl_options.cert_common_name = kCommonName;
12428
12429 {
Ryan Sleevib369d712018-08-20 16:43:2212430 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12431 cert_verifier_config.crl_set =
12432 CRLSet::ForTesting(false, nullptr, "", kCommonName, {});
12433 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3312434
12435 CertStatus cert_status = 0;
12436 DoConnection(ssl_options, &cert_status);
12437
12438 // If the certificate is recorded as revoked in the CRLSet, that should be
12439 // reflected without online revocation checking.
12440 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12441 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612442 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3312443 }
12444
12445 const uint8_t kTestServerSPKISHA256[32] = {
12446 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
12447 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
12448 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
12449 };
12450 const std::string spki_hash(
12451 reinterpret_cast<const char*>(kTestServerSPKISHA256),
12452 sizeof(kTestServerSPKISHA256));
12453
12454 {
Ryan Sleevib369d712018-08-20 16:43:2212455 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
12456 cert_verifier_config.crl_set =
12457 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash});
12458 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3312459
12460 CertStatus cert_status = 0;
12461 DoConnection(ssl_options, &cert_status);
12462
12463 // When the correct SPKI hash is specified, the connection should succeed
12464 // even though the subject is listed in the CRLSet.
12465 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12466 }
12467}
[email protected]316c1e5e2012-09-12 15:17:4412468#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2712469
Sergey Ulanovc4580e72017-09-13 23:30:1112470#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
12471 !defined(OS_FUCHSIA)
12472// FTP uses a second TCP connection with the port number allocated dynamically
12473// on the server side, so it would be hard to make RemoteTestServer proxy FTP
12474// connections reliably. FTP tests are disabled on platforms that use
12475// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3112476class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1112477 public:
[email protected]d9fca99a2012-02-24 16:16:2012478 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0512479 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5512480 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4712481 // Can't use |default_context_|'s HostResolver to set up the
12482 // FTPTransactionFactory because it hasn't been created yet.
Ryan Sleevib8449e02018-07-15 04:31:0712483 default_context().set_host_resolver(&host_resolver_);
mmenke9f2ec60c2015-06-01 20:59:4712484 }
12485
12486 // URLRequestTest interface:
12487 void SetUpFactory() override {
12488 // Add FTP support to the default URLRequestContext.
12489 job_factory_impl_->SetProtocolHandler(
Emily Stark01227982019-06-06 18:45:5612490 "ftp", FtpProtocolHandler::Create(&host_resolver_, &ftp_auth_cache_));
mmenke9f2ec60c2015-06-01 20:59:4712491 }
12492
12493 std::string GetTestFileContents() {
12494 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1912495 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4712496 path = path.Append(kTestFilePath);
12497 path = path.AppendASCII(kFtpTestFile);
12498 std::string contents;
12499 EXPECT_TRUE(base::ReadFileToString(path, &contents));
12500 return contents;
[email protected]95409e12010-08-17 20:07:1112501 }
12502
[email protected]b89ca032009-08-31 21:41:3112503 protected:
mmenke9f2ec60c2015-06-01 20:59:4712504 MockHostResolver host_resolver_;
Emily Stark01227982019-06-06 18:45:5612505 FtpAuthCache ftp_auth_cache_;
mmenke9f2ec60c2015-06-01 20:59:4712506
tommycli59a63432015-11-06 00:10:5512507 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3112508};
12509
[email protected]d2a133182012-08-05 16:44:0812510// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0912511TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0812512 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0812513
12514 TestDelegate d;
12515 {
Ryan Sleevib8449e02018-07-15 04:31:0712516 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612517 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912518 r->Start();
12519 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0812520
Wez2a31b222018-06-07 22:07:1512521 d.RunUntilComplete();
[email protected]d2a133182012-08-05 16:44:0812522
[email protected]f7022f32014-08-21 16:32:1912523 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5012524 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0812525 }
12526}
12527
mmenke9f2ec60c2015-06-01 20:59:4712528TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5512529 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112530
[email protected]a25e90e2009-09-09 17:05:3712531 TestDelegate d;
12532 {
Ryan Sleevib8449e02018-07-15 04:31:0712533 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612534 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
12535 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912536 r->Start();
12537 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712538
Wez2a31b222018-06-07 22:07:1512539 d.RunUntilComplete();
[email protected]a25e90e2009-09-09 17:05:3712540
[email protected]f7022f32014-08-21 16:32:1912541 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712542 EXPECT_EQ(1, d.response_started_count());
12543 EXPECT_FALSE(d.received_data_before_response());
12544 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5512545 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712546 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512547 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712548 r->GetResponseRemoteEndpoint().port());
[email protected]a25e90e2009-09-09 17:05:3712549 }
12550}
12551
mmenke9f2ec60c2015-06-01 20:59:4712552TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5512553 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112554
[email protected]dd265012009-01-08 20:45:2712555 TestDelegate d;
12556 {
Ryan Sleevib8449e02018-07-15 04:31:0712557 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612558 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
12559 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912560 r->Start();
12561 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712562
Wez2a31b222018-06-07 22:07:1512563 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712564
[email protected]f7022f32014-08-21 16:32:1912565 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712566 EXPECT_EQ(1, d.response_started_count());
12567 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712568 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512569 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712570 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512571 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712572 r->GetResponseRemoteEndpoint().port());
[email protected]dd265012009-01-08 20:45:2712573 }
12574}
12575
Mike West80462a12018-11-27 16:05:0612576TEST_F(URLRequestTestFTP, FTPMimeType) {
12577 ASSERT_TRUE(ftp_test_server_.Start());
12578
12579 struct {
12580 const char* path;
12581 const char* mime;
12582 } test_cases[] = {
12583 {"/", "text/vnd.chromium.ftp-dir"},
12584 {kFtpTestFile, "application/octet-stream"},
12585 };
12586
12587 for (const auto test : test_cases) {
12588 TestDelegate d;
12589
12590 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
12591 ftp_test_server_.GetURL(test.path), DEFAULT_PRIORITY, &d,
12592 TRAFFIC_ANNOTATION_FOR_TESTS));
12593 r->Start();
12594 EXPECT_TRUE(r->is_pending());
12595
12596 d.RunUntilComplete();
12597
12598 std::string mime;
12599 r->GetMimeType(&mime);
12600 EXPECT_EQ(test.mime, mime);
12601 }
12602}
12603
mmenke9f2ec60c2015-06-01 20:59:4712604TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5512605 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112606
[email protected]dd265012009-01-08 20:45:2712607 TestDelegate d;
12608 {
Ryan Sleevib8449e02018-07-15 04:31:0712609 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512610 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12611 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612612 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912613 r->Start();
12614 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712615
Wez2a31b222018-06-07 22:07:1512616 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712617
[email protected]f7022f32014-08-21 16:32:1912618 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4712619 EXPECT_EQ(1, d.response_started_count());
12620 EXPECT_FALSE(d.received_data_before_response());
12621 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512622 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712623 r->GetResponseRemoteEndpoint().ToStringWithoutPort());
tommycli59a63432015-11-06 00:10:5512624 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
Tsuyoshi Horo01faed62019-02-20 22:11:3712625 r->GetResponseRemoteEndpoint().port());
[email protected]58e32bb2013-01-21 18:23:2512626
12627 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1912628 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2512629 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2712630 }
12631}
12632
mmenke9f2ec60c2015-06-01 20:59:4712633TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5512634 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112635
[email protected]dd265012009-01-08 20:45:2712636 TestDelegate d;
12637 {
Ryan Sleevib8449e02018-07-15 04:31:0712638 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512639 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12640 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612641 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912642 r->Start();
12643 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712644
Wez2a31b222018-06-07 22:07:1512645 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712646
[email protected]f7022f32014-08-21 16:32:1912647 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712648 EXPECT_EQ(1, d.response_started_count());
12649 EXPECT_FALSE(d.received_data_before_response());
12650 EXPECT_EQ(d.bytes_received(), 0);
12651 }
12652}
12653
mmenke9f2ec60c2015-06-01 20:59:4712654TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5512655 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112656
[email protected]8b8a197d2009-08-26 15:57:5812657 TestDelegate d;
12658 // Set correct login credentials. The delegate will be asked for them when
12659 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812660 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812661 {
Ryan Sleevib8449e02018-07-15 04:31:0712662 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512663 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12664 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612665 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912666 r->Start();
12667 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812668
Wez2a31b222018-06-07 22:07:1512669 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812670
[email protected]f7022f32014-08-21 16:32:1912671 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812672 EXPECT_EQ(1, d.response_started_count());
12673 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712674 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812675 }
12676}
12677
mmenke9f2ec60c2015-06-01 20:59:4712678TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5512679 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112680
[email protected]dd265012009-01-08 20:45:2712681 TestDelegate d;
12682 {
Ryan Sleevib8449e02018-07-15 04:31:0712683 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512684 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12685 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612686 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912687 r->Start();
12688 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712689
Wez2a31b222018-06-07 22:07:1512690 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712691
[email protected]f7022f32014-08-21 16:32:1912692 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712693 EXPECT_EQ(1, d.response_started_count());
12694 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712695 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2712696 }
12697}
[email protected]8b8a197d2009-08-26 15:57:5812698
mmenke9f2ec60c2015-06-01 20:59:4712699TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5512700 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112701
[email protected]8b8a197d2009-08-26 15:57:5812702 TestDelegate d;
12703 // Set correct login credentials. The delegate will be asked for them when
12704 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812705 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812706 {
Ryan Sleevib8449e02018-07-15 04:31:0712707 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512708 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12709 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612710 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912711 r->Start();
12712 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812713
Wez2a31b222018-06-07 22:07:1512714 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812715
[email protected]f7022f32014-08-21 16:32:1912716 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812717 EXPECT_EQ(1, d.response_started_count());
12718 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712719 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812720 }
12721}
[email protected]60a3df52009-09-22 16:13:2412722
mmenke9f2ec60c2015-06-01 20:59:4712723TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5512724 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112725
danakj8522a25b2016-04-16 00:17:3612726 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412727 {
12728 // Pass correct login identity in the URL.
Ryan Sleevib8449e02018-07-15 04:31:0712729 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512730 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12731 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612732 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912733 r->Start();
12734 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412735
Wez2a31b222018-06-07 22:07:1512736 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412737
[email protected]f7022f32014-08-21 16:32:1912738 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412739 EXPECT_EQ(1, d->response_started_count());
12740 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712741 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412742 }
12743
12744 d.reset(new TestDelegate);
12745 {
12746 // This request should use cached identity from previous request.
Ryan Sleevib8449e02018-07-15 04:31:0712747 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612748 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12749 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
mmenke9f2ec60c2015-06-01 20:59:4712762TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5512763 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112764
danakj8522a25b2016-04-16 00:17:3612765 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412766 // Set correct login credentials. The delegate will be asked for them when
12767 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812768 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2412769 {
Ryan Sleevib8449e02018-07-15 04:31:0712770 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5512771 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12772 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612773 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912774 r->Start();
12775 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412776
Wez2a31b222018-06-07 22:07:1512777 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412778
[email protected]f7022f32014-08-21 16:32:1912779 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412780 EXPECT_EQ(1, d->response_started_count());
12781 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712782 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412783 }
12784
12785 // Use a new delegate without explicit credentials. The cached ones should be
12786 // used.
12787 d.reset(new TestDelegate);
12788 {
12789 // Don't pass wrong credentials in the URL, they would override valid cached
12790 // ones.
Ryan Sleevib8449e02018-07-15 04:31:0712791 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612792 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12793 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912794 r->Start();
12795 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412796
Wez2a31b222018-06-07 22:07:1512797 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412798
[email protected]f7022f32014-08-21 16:32:1912799 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412800 EXPECT_EQ(1, d->response_started_count());
12801 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712802 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412803 }
12804}
ricea3a1c71f2016-06-17 10:05:2612805
12806TEST_F(URLRequestTestFTP, RawBodyBytes) {
12807 ASSERT_TRUE(ftp_test_server_.Start());
12808
12809 TestDelegate d;
12810 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612811 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12812 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2612813 req->Start();
Wez2a31b222018-06-07 22:07:1512814 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:2612815
12816 EXPECT_EQ(6, req->GetRawBodyBytes());
12817}
12818
Matt Menkebeb95e8a2019-07-15 06:04:0912819TEST_F(URLRequestTestFTP, FtpAuthCancellation) {
Emily Stark6668e092019-06-20 18:36:3812820 ftp_test_server_.set_no_anonymous_ftp_user(true);
12821 ASSERT_TRUE(ftp_test_server_.Start());
12822 TestDelegate d;
12823 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
12824 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12825 TRAFFIC_ANNOTATION_FOR_TESTS));
12826 req->Start();
12827 d.RunUntilComplete();
12828
12829 ASSERT_TRUE(d.auth_required_called());
Emily Stark89a3247d2019-06-26 18:07:4012830 EXPECT_EQ(OK, d.request_status());
Emily Stark6668e092019-06-20 18:36:3812831 EXPECT_TRUE(req->auth_challenge_info());
Emily Stark89a3247d2019-06-26 18:07:4012832 std::string mime_type;
12833 req->GetMimeType(&mime_type);
12834 EXPECT_EQ("text/plain", mime_type);
12835 EXPECT_EQ("", d.data_received());
12836 EXPECT_EQ(-1, req->GetExpectedContentSize());
Emily Stark6668e092019-06-20 18:36:3812837}
12838
Matt Menkef1b97e02019-05-13 23:52:4112839class URLRequestTestFTPOverHttpProxy : public URLRequestTestFTP {
12840 public:
12841 // Test interface:
12842 void SetUp() override {
12843 proxy_resolution_service_ = ProxyResolutionService::CreateFixed(
12844 "localhost", TRAFFIC_ANNOTATION_FOR_TESTS);
12845 default_context_->set_proxy_resolution_service(
12846 proxy_resolution_service_.get());
12847 URLRequestTestFTP::SetUp();
12848 }
12849
12850 private:
12851 std::unique_ptr<ProxyResolutionService> proxy_resolution_service_;
12852};
12853
12854// Check that FTP is not supported over an HTTP proxy.
12855TEST_F(URLRequestTestFTPOverHttpProxy, Fails) {
12856 TestDelegate delegate;
12857 std::unique_ptr<URLRequest> request(
12858 default_context_->CreateRequest(GURL("ftp://foo.test/"), DEFAULT_PRIORITY,
12859 &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12860 request->Start();
12861 delegate.RunUntilComplete();
12862
12863 EXPECT_THAT(delegate.request_status(), IsError(ERR_NO_SUPPORTED_PROXIES));
12864}
12865
brettwa1228ebb2016-10-28 03:51:3412866#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5112867
ttuttlec0c828492015-05-15 01:25:5512868TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
12869 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712870 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612871 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512872
12873 EXPECT_FALSE(req->response_info().network_accessed);
12874
12875 req->Start();
Wez2a31b222018-06-07 22:07:1512876 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512877
12878 EXPECT_EQ(1, default_network_delegate_.completed_requests());
12879 EXPECT_FALSE(req->response_info().network_accessed);
12880}
12881
12882TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
12883 MockHostResolver host_resolver;
12884 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
12885 TestURLRequestContext context(true);
12886 context.set_network_delegate(&network_delegate);
12887 context.set_host_resolver(&host_resolver);
12888 host_resolver.rules()->AddSimulatedFailure("*");
12889 context.Init();
12890
12891 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612892 std::unique_ptr<URLRequest> req(
12893 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
12894 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512895
12896 EXPECT_FALSE(req->response_info().network_accessed);
12897
12898 req->Start();
Wez2a31b222018-06-07 22:07:1512899 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512900 EXPECT_TRUE(req->response_info().network_accessed);
12901}
12902
mmenkeed0498b2015-12-08 23:20:4212903// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2212904// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4212905TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2212906 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0712907 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612908 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
12909 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2212910
danakj8522a25b2016-04-16 00:17:3612911 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2212912 req.get(), &default_network_delegate_,
12913 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4212914 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
12915 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2212916
12917 req->Start();
12918 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2212919 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5012920 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2212921 EXPECT_EQ(0, d.received_redirect_count());
12922}
12923
Andrey Kosyakov2e893e62017-08-31 17:00:5212924TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412925 ASSERT_TRUE(http_test_server()->Start());
12926 TestURLRequestContext context;
12927 GURL url(http_test_server()->GetURL("/cachetime"));
12928 TestDelegate delegate;
12929 HttpRequestHeaders extra_headers;
12930 extra_headers.SetHeader("X-Foo", "bar");
12931
12932 {
Andrey Kosyakov2e893e62017-08-31 17:00:5212933 HttpRawRequestHeaders raw_req_headers;
12934 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12935
Andrey Kosyakov83a6eee2017-08-14 19:20:0412936 std::unique_ptr<URLRequest> r(context.CreateRequest(
12937 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12938 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212939 r->SetRequestHeadersCallback(base::Bind(
12940 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
12941 r->SetResponseHeadersCallback(base::Bind(
12942 [](scoped_refptr<const HttpResponseHeaders>* left,
12943 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12944 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412945 r->Start();
12946 while (!delegate.response_started_count())
12947 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5212948 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412949 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212950 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412951 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212952 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412953 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212954 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
12955 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
12956 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
12957 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412958 }
12959 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412960 std::unique_ptr<URLRequest> r(context.CreateRequest(
12961 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12962 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212963 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412964 FAIL() << "Callback should not be called unless request is sent";
12965 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212966 r->SetResponseHeadersCallback(
12967 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
12968 FAIL() << "Callback should not be called unless request is sent";
12969 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412970 r->Start();
Wez2a31b222018-06-07 22:07:1512971 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412972 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412973 }
12974}
12975
Andrey Kosyakov2e893e62017-08-31 17:00:5212976TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412977 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5212978 HttpRawRequestHeaders raw_req_headers;
12979 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12980
Andrey Kosyakov83a6eee2017-08-14 19:20:0412981 TestURLRequestContext context;
12982 TestDelegate delegate;
12983 HttpRequestHeaders extra_headers;
12984 extra_headers.SetHeader("X-Foo", "bar");
Andrey Kosyakov83a6eee2017-08-14 19:20:0412985 GURL url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:0712986 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0412987 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12988 r->SetExtraRequestHeaders(extra_headers);
12989 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5212990 base::Unretained(&raw_req_headers)));
12991 r->SetResponseHeadersCallback(base::Bind(
12992 [](scoped_refptr<const HttpResponseHeaders>* left,
12993 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12994 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412995 r->Start();
Wez0e717112018-06-18 23:09:2212996 delegate.RunUntilRedirect();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412997
12998 ASSERT_EQ(1, delegate.received_redirect_count());
12999 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5213000 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413001 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5213002 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413003 EXPECT_EQ("gzip, deflate", value);
13004 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5213005 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
13006 raw_req_headers.request_line());
13007 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
13008 EXPECT_EQ(302, raw_resp_headers->response_code());
13009 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0413010
Andrey Kosyakov2e893e62017-08-31 17:00:5213011 raw_req_headers = HttpRawRequestHeaders();
13012 raw_resp_headers = nullptr;
Arthur Sonzognib8465ff72019-01-04 18:44:3513013 r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
13014 base::nullopt /* modified_headers */);
Wez2a31b222018-06-07 22:07:1513015 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5213016 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413017 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5213018 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413019 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5213020 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
13021 raw_req_headers.request_line());
13022 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0413023}
13024
Andrey Kosyakov2e893e62017-08-31 17:00:5213025TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0413026 TestDelegate request_delegate;
13027
Ryan Sleevib8449e02018-07-15 04:31:0713028 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0413029 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
13030 TRAFFIC_ANNOTATION_FOR_TESTS));
13031 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
13032 FAIL() << "Callback should not be called unless request is sent";
13033 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5213034 r->SetResponseHeadersCallback(
13035 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
13036 FAIL() << "Callback should not be called unless request is sent";
13037 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413038 r->Start();
Wez2a31b222018-06-07 22:07:1513039 request_delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0413040 EXPECT_FALSE(r->is_pending());
13041}
13042
Andrey Kosyakov2e893e62017-08-31 17:00:5213043TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0413044 ASSERT_TRUE(http_test_server()->Start());
13045 GURL url(http_test_server()->GetURL("/auth-basic"));
13046
13047 TestURLRequestContext context;
13048 TestDelegate delegate;
13049
13050 delegate.set_credentials(AuthCredentials(kUser, kSecret));
13051 HttpRequestHeaders extra_headers;
13052 extra_headers.SetHeader("X-Foo", "bar");
13053
Andrey Kosyakov2e893e62017-08-31 17:00:5213054 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
13055 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0413056
Andrey Kosyakov2e893e62017-08-31 17:00:5213057 using RespHeadersVector =
13058 std::vector<scoped_refptr<const HttpResponseHeaders>>;
13059 RespHeadersVector raw_resp_headers;
13060
13061 auto req_headers_callback = base::Bind(
13062 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
13063 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
13064 },
13065 &raw_req_headers);
13066 auto resp_headers_callback = base::Bind(
13067 [](RespHeadersVector* vec,
13068 scoped_refptr<const HttpResponseHeaders> headers) {
13069 vec->push_back(headers);
13070 },
13071 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0413072 std::unique_ptr<URLRequest> r(context.CreateRequest(
13073 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
13074 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5213075 r->SetRequestHeadersCallback(req_headers_callback);
13076 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0413077 r->Start();
Wez2a31b222018-06-07 22:07:1513078 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0413079 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5213080 ASSERT_EQ(raw_req_headers.size(), 2u);
13081 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0413082 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5213083 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
13084 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413085 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5213086 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
13087 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413088 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5213089 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
13090 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
13091 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
13092 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
13093
13094 std::unique_ptr<URLRequest> r2(context.CreateRequest(
13095 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
13096 r2->SetExtraRequestHeaders(extra_headers);
13097 r2->SetRequestHeadersCallback(req_headers_callback);
13098 r2->SetResponseHeadersCallback(resp_headers_callback);
13099 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
13100 r2->Start();
Wez2a31b222018-06-07 22:07:1513101 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5213102 EXPECT_FALSE(r2->is_pending());
13103 ASSERT_EQ(raw_req_headers.size(), 3u);
13104 ASSERT_EQ(raw_resp_headers.size(), 3u);
13105 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
13106 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
13107 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
13108 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0413109}
13110
Andrey Kosyakov2e893e62017-08-31 17:00:5213111TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0413112 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
13113 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0713114 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0413115 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13116 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5213117 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0413118 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5213119 r->SetResponseHeadersCallback(
13120 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
13121 FAIL() << "Callback should not be called for non-HTTP schemes";
13122 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0413123 r->Start();
Wez2a31b222018-06-07 22:07:1513124 d.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0413125 EXPECT_FALSE(r->is_pending());
13126}
13127
Carlos ILaef65d62018-06-04 21:24:1313128TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
13129 TestDelegate d;
13130 BlockingNetworkDelegate network_delegate(
13131 BlockingNetworkDelegate::SYNCHRONOUS);
13132 const GURL kOriginalUrl("https://original.test");
13133 const GURL kRedirectUrl("http://redirect.test");
13134 network_delegate.set_redirect_url(kRedirectUrl);
13135 TestURLRequestContext context(true /* delay_initialization */);
13136 context.set_network_delegate(&network_delegate);
13137 context.Init();
13138
13139 std::unique_ptr<URLRequest> r(context.CreateRequest(
13140 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13141 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1313142 r->Start();
Wez0e717112018-06-18 23:09:2213143 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313144 GURL::Replacements replacements;
13145 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
13146 // was set.
13147 replacements.SetSchemeStr("https");
13148 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
13149 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4413150 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313151}
13152
13153TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
13154 TestDelegate d;
13155 BlockingNetworkDelegate network_delegate(
13156 BlockingNetworkDelegate::SYNCHRONOUS);
13157 const GURL kOriginalUrl("https://original.test");
13158 const GURL kRedirectUrl("http://redirect.test:80");
13159 network_delegate.set_redirect_url(kRedirectUrl);
13160 TestURLRequestContext context(true /* delay_initialization */);
13161 context.set_network_delegate(&network_delegate);
13162 context.Init();
13163
13164 std::unique_ptr<URLRequest> r(context.CreateRequest(
13165 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13166 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1313167 r->Start();
Wez0e717112018-06-18 23:09:2213168 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313169 GURL::Replacements replacements;
13170 // The URL host should have not been changed.
13171 EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
13172 // The scheme should now be https, and the effective port should now be 443.
13173 EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
13174 EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
Carlos IL0d67fc72018-06-22 17:18:4413175 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313176}
13177
13178TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
13179 TestDelegate d;
13180 BlockingNetworkDelegate network_delegate(
13181 BlockingNetworkDelegate::SYNCHRONOUS);
13182 const GURL kOriginalUrl("https://original.test");
13183 const GURL kRedirectUrl("http://redirect.test:1234");
13184 network_delegate.set_redirect_url(kRedirectUrl);
13185 TestURLRequestContext context(true /* delay_initialization */);
13186 context.set_network_delegate(&network_delegate);
13187 context.Init();
13188
13189 std::unique_ptr<URLRequest> r(context.CreateRequest(
13190 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13191 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1313192 r->Start();
Wez0e717112018-06-18 23:09:2213193 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313194 GURL::Replacements replacements;
13195 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
13196 // was set, nonstandard port should not have been modified.
13197 replacements.SetSchemeStr("https");
13198 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
13199 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4413200 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313201}
13202
13203TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
13204 TestDelegate d;
13205 BlockingNetworkDelegate network_delegate(
13206 BlockingNetworkDelegate::SYNCHRONOUS);
13207 const GURL kOriginalUrl("https://original.test");
13208 const GURL kRedirectUrl("http://redirect.test");
13209 network_delegate.set_redirect_url(kRedirectUrl);
13210 TestURLRequestContext context(true /* delay_initialization */);
13211 context.set_network_delegate(&network_delegate);
13212 context.Init();
13213 std::unique_ptr<URLRequest> r(context.CreateRequest(
13214 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
13215 r->set_upgrade_if_insecure(false);
Carlos ILaef65d62018-06-04 21:24:1313216 r->Start();
Wez0e717112018-06-18 23:09:2213217 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1313218 // The redirect URL should not be changed if the upgrade_if_insecure flag is
13219 // not set.
13220 EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4413221 EXPECT_FALSE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1313222}
13223
Paul Jensen60e45532018-02-19 16:04:1813224// Test that URLRequests get properly tagged.
13225#if defined(OS_ANDROID)
13226TEST_F(URLRequestTestHTTP, TestTagging) {
Peter Collingbourne8ccab722019-02-12 18:10:4813227 if (!CanGetTaggedBytes()) {
13228 DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
13229 return;
13230 }
13231
Paul Jensen60e45532018-02-19 16:04:1813232 ASSERT_TRUE(http_test_server()->Start());
13233
13234 // The tag under which the system reports untagged traffic.
13235 static const int32_t UNTAGGED_TAG = 0;
13236
13237 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
13238
13239 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
13240 TestDelegate delegate;
Ryan Sleevib8449e02018-07-15 04:31:0713241 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Paul Jensen60e45532018-02-19 16:04:1813242 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
13243 TRAFFIC_ANNOTATION_FOR_TESTS));
13244 EXPECT_EQ(SocketTag(), req->socket_tag());
13245 req->Start();
Wez2a31b222018-06-07 22:07:1513246 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1813247
13248 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
13249
13250 int32_t tag_val1 = 0x12345678;
13251 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
13252 old_traffic = GetTaggedBytes(tag_val1);
13253
13254 // Test specific tag value.
Ryan Sleevib8449e02018-07-15 04:31:0713255 req = default_context().CreateRequest(http_test_server()->GetURL("/"),
13256 DEFAULT_PRIORITY, &delegate,
13257 TRAFFIC_ANNOTATION_FOR_TESTS);
Paul Jensen60e45532018-02-19 16:04:1813258 req->set_socket_tag(tag1);
13259 EXPECT_EQ(tag1, req->socket_tag());
13260 req->Start();
Wez2a31b222018-06-07 22:07:1513261 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1813262
13263 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
13264}
13265#endif
13266
Steven Valdez1c1859172019-04-10 15:33:2813267// Provides a response to the 0RTT request indicating whether it was received
13268// as early data, sending HTTP_TOO_EARLY if enabled.
13269class ZeroRTTResponse : public test_server::BasicHttpResponse {
13270 public:
13271 ZeroRTTResponse(bool zero_rtt, bool send_too_early)
13272 : zero_rtt_(zero_rtt), send_too_early_(send_too_early) {}
13273 ~ZeroRTTResponse() override {}
13274
13275 void SendResponse(const test_server::SendBytesCallback& send,
13276 const test_server::SendCompleteCallback& done) override {
13277 AddCustomHeader("Vary", "Early-Data");
13278 set_content_type("text/plain");
13279 AddCustomHeader("Cache-Control", "no-cache");
13280 if (zero_rtt_) {
13281 if (send_too_early_)
13282 set_code(HTTP_TOO_EARLY);
13283 set_content("1");
13284 } else {
13285 set_content("0");
13286 }
13287
13288 // Since the EmbeddedTestServer doesn't keep the socket open by default,
13289 // it is explicitly kept alive to allow the remaining leg of the 0RTT
13290 // handshake to be received after the early data.
13291 send.Run(ToResponseString(), base::DoNothing());
13292 }
13293
13294 private:
13295 bool zero_rtt_;
13296 bool send_too_early_;
13297
13298 DISALLOW_COPY_AND_ASSIGN(ZeroRTTResponse);
13299};
13300
13301std::unique_ptr<test_server::HttpResponse> HandleZeroRTTRequest(
13302 const test_server::HttpRequest& request) {
13303 if (request.GetURL().path() != "/zerortt")
13304 return nullptr;
13305 auto iter = request.headers.find("Early-Data");
13306 bool zero_rtt = iter != request.headers.end() && iter->second == "1";
13307 return std::make_unique<ZeroRTTResponse>(zero_rtt, false);
13308}
13309
13310class HTTPSEarlyDataTest : public TestWithScopedTaskEnvironment {
13311 public:
13312 HTTPSEarlyDataTest()
13313 : context_(true), test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
13314 auto params = std::make_unique<HttpNetworkSession::Params>();
13315 params->enable_early_data = true;
13316 context_.set_http_network_session_params(std::move(params));
13317
13318 context_.set_network_delegate(&network_delegate_);
13319 cert_verifier_.set_default_result(OK);
13320 context_.set_cert_verifier(&cert_verifier_);
13321
David Benjamin151ec6b2019-08-02 19:38:5213322 SSLContextConfig config;
13323 config.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
13324 ssl_config_service_ = std::make_unique<TestSSLConfigService>(config);
Steven Valdez1c1859172019-04-10 15:33:2813325 context_.set_ssl_config_service(ssl_config_service_.get());
13326
13327 context_.Init();
13328
13329 ssl_config_.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
13330 ssl_config_.early_data_enabled = true;
13331 test_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config_);
13332 test_server_.AddDefaultHandlers(
13333 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
13334 test_server_.RegisterRequestHandler(
13335 base::BindRepeating(&HandleZeroRTTRequest));
13336 }
13337
13338 ~HTTPSEarlyDataTest() override = default;
13339
13340 void ResetSSLConfig(net::EmbeddedTestServer::ServerCertificate cert,
13341 uint16_t version) {
13342 ssl_config_.version_max = version;
13343 test_server_.ResetSSLConfig(cert, ssl_config_);
13344 }
13345
13346 protected:
13347 MockCertVerifier cert_verifier_;
13348 TestNetworkDelegate network_delegate_; // Must outlive URLRequest.
13349 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
13350 TestURLRequestContext context_;
13351
13352 SSLServerConfig ssl_config_;
13353 EmbeddedTestServer test_server_;
13354};
13355
13356// TLSEarlyDataTest tests that we handle early data correctly.
13357TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTest) {
13358 ASSERT_TRUE(test_server_.Start());
13359 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13360
13361 {
13362 TestDelegate d;
13363 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13364 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13365 TRAFFIC_ANNOTATION_FOR_TESTS));
13366 r->Start();
13367 EXPECT_TRUE(r->is_pending());
13368
13369 base::RunLoop().Run();
13370
13371 EXPECT_EQ(1, d.response_started_count());
13372
13373 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13374 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13375 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13376 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13377 r->ssl_info().cert.get()));
13378
13379 // The Early-Data header should be omitted in the initial request, and the
13380 // handler should return "0".
13381 EXPECT_EQ("0", d.data_received());
13382 }
13383
13384 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13385
13386 {
13387 TestDelegate d;
13388 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13389 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13390 TRAFFIC_ANNOTATION_FOR_TESTS));
13391
13392 r->Start();
13393 EXPECT_TRUE(r->is_pending());
13394
13395 base::RunLoop().Run();
13396
13397 EXPECT_EQ(1, d.response_started_count());
13398
13399 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13400 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13401 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13402 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13403 r->ssl_info().cert.get()));
13404
13405 // The Early-Data header should be a single '1' in the resumed request, and
13406 // the handler should return "1".
13407 EXPECT_EQ("1", d.data_received());
13408 }
13409}
13410
13411// TLSEarlyDataTest tests that we handle early data correctly for POST.
13412TEST_F(HTTPSEarlyDataTest, TLSEarlyDataPOSTTest) {
13413 ASSERT_TRUE(test_server_.Start());
13414 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13415
13416 {
13417 TestDelegate d;
13418 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13419 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13420 TRAFFIC_ANNOTATION_FOR_TESTS));
13421 r->Start();
13422 EXPECT_TRUE(r->is_pending());
13423
13424 base::RunLoop().Run();
13425
13426 EXPECT_EQ(1, d.response_started_count());
13427
13428 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13429 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13430 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13431 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13432 r->ssl_info().cert.get()));
13433
13434 // The Early-Data header should be omitted in the initial request, and the
13435 // handler should return "0".
13436 EXPECT_EQ("0", d.data_received());
13437 }
13438
13439 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13440
13441 {
13442 TestDelegate d;
13443 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13444 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13445 TRAFFIC_ANNOTATION_FOR_TESTS));
13446 r->set_method("POST");
13447 r->Start();
13448 EXPECT_TRUE(r->is_pending());
13449
13450 base::RunLoop().Run();
13451
13452 EXPECT_EQ(1, d.response_started_count());
13453
13454 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13455 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13456 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13457 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13458 r->ssl_info().cert.get()));
13459
13460 // The Early-Data header should be omitted in the request, since we don't
13461 // send POSTs over early data, and the handler should return "0".
13462 EXPECT_EQ("0", d.data_received());
13463 }
13464}
13465
13466std::unique_ptr<test_server::HttpResponse> HandleTooEarly(
13467 bool* sent_425,
13468 const test_server::HttpRequest& request) {
13469 if (request.GetURL().path() != "/tooearly")
13470 return nullptr;
13471 auto iter = request.headers.find("Early-Data");
13472 bool zero_rtt = iter != request.headers.end() && iter->second == "1";
13473 if (zero_rtt)
13474 *sent_425 = true;
13475 return std::make_unique<ZeroRTTResponse>(zero_rtt, true);
13476}
13477
13478// Test that we handle 425 (Too Early) correctly.
13479TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTooEarlyTest) {
13480 bool sent_425 = false;
13481 test_server_.RegisterRequestHandler(
13482 base::BindRepeating(&HandleTooEarly, base::Unretained(&sent_425)));
13483 ASSERT_TRUE(test_server_.Start());
13484 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13485
13486 {
13487 TestDelegate d;
13488 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13489 test_server_.GetURL("/tooearly"), DEFAULT_PRIORITY, &d,
13490 TRAFFIC_ANNOTATION_FOR_TESTS));
13491 r->Start();
13492 EXPECT_TRUE(r->is_pending());
13493
13494 d.RunUntilComplete();
13495
13496 EXPECT_EQ(1, d.response_started_count());
13497
13498 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13499 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13500 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13501 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13502 r->ssl_info().cert.get()));
13503
13504 // The Early-Data header should be omitted in the initial request, and the
13505 // handler should return "0".
13506 EXPECT_EQ("0", d.data_received());
13507 EXPECT_FALSE(sent_425);
13508 }
13509
13510 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13511
13512 {
13513 TestDelegate d;
13514 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13515 test_server_.GetURL("/tooearly"), DEFAULT_PRIORITY, &d,
13516 TRAFFIC_ANNOTATION_FOR_TESTS));
13517
13518 r->Start();
13519 EXPECT_TRUE(r->is_pending());
13520
13521 d.RunUntilComplete();
13522
13523 EXPECT_EQ(1, d.response_started_count());
13524
13525 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13526 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13527 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13528 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13529 r->ssl_info().cert.get()));
13530
13531 // The resumption request will encounter a 425 error and retry without early
13532 // data, and the handler should return "0".
13533 EXPECT_EQ("0", d.data_received());
13534 EXPECT_TRUE(sent_425);
13535 }
13536}
13537
13538// TLSEarlyDataRejectTest tests that we gracefully handle an early data reject
13539// and retry without early data.
13540TEST_F(HTTPSEarlyDataTest, TLSEarlyDataRejectTest) {
13541 ASSERT_TRUE(test_server_.Start());
13542 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13543
13544 {
13545 TestDelegate d;
13546 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13547 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13548 TRAFFIC_ANNOTATION_FOR_TESTS));
13549
13550 r->Start();
13551 EXPECT_TRUE(r->is_pending());
13552
13553 d.RunUntilComplete();
13554
13555 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13556 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13557 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13558 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13559 r->ssl_info().cert.get()));
13560
13561 // The Early-Data header should be omitted in the initial request, and the
13562 // handler should return "0".
13563 EXPECT_EQ("0", d.data_received());
13564 }
13565
13566 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13567
13568 // The certificate in the resumption is changed to confirm that the
13569 // certificate change is observed.
13570 scoped_refptr<X509Certificate> old_cert = test_server_.GetCertificate();
13571 ResetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED,
13572 SSL_PROTOCOL_VERSION_TLS1_3);
13573
13574 {
13575 TestDelegate d;
13576 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13577 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13578 TRAFFIC_ANNOTATION_FOR_TESTS));
13579
13580 r->Start();
13581 EXPECT_TRUE(r->is_pending());
13582
13583 d.RunUntilComplete();
13584
13585 EXPECT_EQ(1, d.response_started_count());
13586
13587 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13588 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13589 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13590 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13591 r->ssl_info().cert.get()));
13592 EXPECT_FALSE(old_cert->EqualsIncludingChain(r->ssl_info().cert.get()));
13593
13594 // The Early-Data header should be omitted in the rejected request, and the
13595 // handler should return "0".
13596 EXPECT_EQ("0", d.data_received());
13597 }
13598}
13599
13600// TLSEarlyDataTLS12RejectTest tests that we gracefully handle an early data
13601// reject from a TLS 1.2 server and retry without early data.
13602TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTLS12RejectTest) {
13603 ASSERT_TRUE(test_server_.Start());
13604 context_.http_transaction_factory()->GetSession()->ClearSSLSessionCache();
13605
13606 {
13607 TestDelegate d;
13608 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13609 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13610 TRAFFIC_ANNOTATION_FOR_TESTS));
13611
13612 r->Start();
13613 EXPECT_TRUE(r->is_pending());
13614
13615 d.RunUntilComplete();
13616
13617 EXPECT_EQ(1, d.response_started_count());
13618
13619 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
13620 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13621 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13622 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13623 r->ssl_info().cert.get()));
13624
13625 // The Early-Data header should be omitted in the initial request, and the
13626 // handler should return "0".
13627 EXPECT_EQ("0", d.data_received());
13628 }
13629
13630 context_.http_transaction_factory()->GetSession()->CloseAllConnections();
13631
13632 // The certificate in the resumption is changed to confirm that the
13633 // certificate change is observed.
13634 scoped_refptr<X509Certificate> old_cert = test_server_.GetCertificate();
13635 ResetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED,
13636 SSL_PROTOCOL_VERSION_TLS1_2);
13637
13638 {
13639 TestDelegate d;
13640 std::unique_ptr<URLRequest> r(context_.CreateRequest(
13641 test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
13642 TRAFFIC_ANNOTATION_FOR_TESTS));
13643
13644 r->Start();
13645 EXPECT_TRUE(r->is_pending());
13646
13647 d.RunUntilComplete();
13648
13649 EXPECT_EQ(1, d.response_started_count());
13650
13651 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_2,
13652 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
13653 EXPECT_TRUE(r->ssl_info().unverified_cert.get());
13654 EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
13655 r->ssl_info().cert.get()));
13656 EXPECT_FALSE(old_cert->EqualsIncludingChain(r->ssl_info().cert.get()));
13657
13658 // The Early-Data header should be omitted in the rejected request, and the
13659 // handler should return "0".
13660 EXPECT_EQ("0", d.data_received());
13661 }
13662}
13663
Emily Stark08f6c972019-05-28 17:24:2713664// Tests that AuthChallengeInfo is available on the request.
13665TEST_F(URLRequestTestHTTP, AuthChallengeInfo) {
13666 ASSERT_TRUE(http_test_server()->Start());
13667 GURL url(http_test_server()->GetURL("/auth-basic"));
13668
13669 TestURLRequestContext context;
13670 TestDelegate delegate;
13671
13672 std::unique_ptr<URLRequest> r(context.CreateRequest(
13673 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
13674 r->Start();
13675 delegate.RunUntilComplete();
13676 ASSERT_TRUE(r->auth_challenge_info().has_value());
13677 EXPECT_FALSE(r->auth_challenge_info()->is_proxy);
13678 EXPECT_EQ(url::Origin::Create(url), r->auth_challenge_info()->challenger);
13679 EXPECT_EQ("basic", r->auth_challenge_info()->scheme);
13680 EXPECT_EQ("testrealm", r->auth_challenge_info()->realm);
13681 EXPECT_EQ("Basic realm=\"testrealm\"", r->auth_challenge_info()->challenge);
13682 EXPECT_EQ("/auth-basic", r->auth_challenge_info()->path);
13683}
13684
[email protected]7461a402011-03-24 23:19:5113685} // namespace net