blob: 565edf1e7414350f79e65383199057184bcd5af1 [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
[email protected]ea224582008-12-07 20:25:469#include "build/build_config.h"
10
[email protected]9396b252008-09-29 17:29:3811#if defined(OS_WIN)
robliaoeb9bfd642017-05-18 17:35:1612#include <objbase.h>
[email protected]aa84a7e2012-03-15 21:29:0613#include <shlobj.h>
Fan Yang5a88d5d2017-10-24 01:14:2914#include <windows.h>
Robert Liaoc88f99d12017-10-17 21:48:3315#include <wrl/client.h>
[email protected]9396b252008-09-29 17:29:3816#endif
17
tbansalea2fb8c2015-05-22 22:23:0018#include <stdint.h>
19
initial.commit586acc5fe2008-07-26 22:42:5220#include <algorithm>
avibf0746c2015-12-09 19:53:1421#include <limits>
Devlin Cronine4bcb40e2018-06-05 18:02:4722#include <memory>
initial.commit586acc5fe2008-07-26 22:42:5223
nharperb7441ef2016-01-25 23:54:1424#include "base/base64url.h"
[email protected]218aa6a12011-09-13 17:38:3825#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5826#include "base/compiler_specific.h"
mmenke9f2ec60c2015-06-01 20:59:4727#include "base/files/file_path.h"
thestigd8df0332014-09-04 06:33:2928#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0729#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2830#include "base/format_macros.h"
estark06e0dac2015-08-07 21:56:0131#include "base/json/json_reader.h"
skyostil4891b25b2015-06-11 11:43:4532#include "base/location.h"
Avi Drissman13fc8932015-12-20 04:40:4633#include "base/macros.h"
[email protected]084262c2011-12-01 21:12:4734#include "base/memory/weak_ptr.h"
Alexander Timin4f9c35c2018-11-01 20:15:2035#include "base/message_loop/message_loop.h"
initial.commit586acc5fe2008-07-26 22:42:5236#include "base/path_service.h"
mmenkefb18c772015-09-30 22:22:5037#include "base/power_monitor/power_monitor.h"
38#include "base/power_monitor/power_monitor_source.h"
[email protected]255620da2013-08-19 13:14:2939#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4540#include "base/single_thread_task_runner.h"
[email protected]4dc3ad4f2013-06-11 07:15:5041#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5542#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2243#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2244#include "base/strings/string_util.h"
45#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0546#include "base/strings/utf_string_conversions.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"
initial.commit586acc5fe2008-07-26 22:42:5255#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2556#include "net/base/load_timing_info.h"
57#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0658#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5259#include "net/base/net_module.h"
Lily Houghton582d4622018-01-22 22:43:4060#include "net/base/proxy_server.h"
[email protected]2ca01e52013-10-31 22:05:1961#include "net/base/request_priority.h"
zhongyi18ddddd2017-02-03 19:06:3662#include "net/base/test_completion_callback.h"
[email protected]f288ef02012-12-15 20:28:2863#include "net/base/upload_bytes_element_reader.h"
64#include "net/base/upload_data_stream.h"
65#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4466#include "net/base/url_util.h"
Ryan Sleevib369d712018-08-20 16:43:2267#include "net/cert/crl_set.h"
rsleevid6de8302016-06-21 01:33:2068#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4769#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3670#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1171#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2472#include "net/cert/mock_cert_verifier.h"
zhongyi18ddddd2017-02-03 19:06:3673#include "net/cert/multi_log_ct_verifier.h"
eranmdcec9632016-10-10 14:16:1074#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1175#include "net/cert/test_root_certs.h"
[email protected]aa84a7e2012-03-15 21:29:0676#include "net/cookies/cookie_monster.h"
77#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5278#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5379#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3880#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5281#include "net/http/http_cache.h"
82#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1983#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2584#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2185#include "net/http/http_response_headers.h"
zhongyi18ddddd2017-02-03 19:06:3686#include "net/http/http_server_properties_impl.h"
[email protected]e50efea2014-03-24 18:41:0087#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0088#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1989#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5190#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4691#include "net/log/test_net_log_entry.h"
92#include "net/log/test_net_log_util.h"
Scott Violet0caaaf432018-03-24 00:43:5993#include "net/net_buildflags.h"
Lily Houghtonffe89daa02018-03-09 18:30:0394#include "net/proxy_resolution/proxy_resolution_service.h"
Ryan Hamiltona3ee93a72018-08-01 22:03:0895#include "net/quic/mock_crypto_client_stream_factory.h"
96#include "net/quic/quic_server_info.h"
zhongyi18ddddd2017-02-03 19:06:3697#include "net/socket/socket_test_util.h"
[email protected]c3456bb2011-12-12 22:22:1998#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:1499#include "net/ssl/channel_id_service.h"
David Benjamin76a40ad2018-02-24 22:22:08100#include "net/ssl/client_cert_identity_test_util.h"
nharperb7441ef2016-01-25 23:54:14101#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:57102#include "net/ssl/ssl_connection_status_flags.h"
David Benjamin76a40ad2018-02-24 22:22:08103#include "net/ssl/ssl_private_key.h"
tommycli59a63432015-11-06 00:10:55104#include "net/ssl/ssl_server_config.h"
[email protected]6e7845ae2013-03-29 21:48:11105#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:36106#include "net/test/embedded_test_server/embedded_test_server.h"
107#include "net/test/embedded_test_server/http_request.h"
108#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:01109#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21110#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43111#include "net/test/test_data_directory.h"
Bence Béky98447b12018-05-08 03:14:01112#include "net/test/test_with_scoped_task_environment.h"
mmenkefb18c772015-09-30 22:22:50113#include "net/test/url_request/url_request_failed_job.h"
Carlos ILaef65d62018-06-04 21:24:13114#include "net/test/url_request/url_request_mock_http_job.h"
rhalavatib7bd7c792017-04-27 05:25:16115#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34116#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43117#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52118#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50119#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14120#include "net/url_request/url_request_http_job.h"
Thiemo Nagel0793b9c532018-04-18 16:57:58121#include "net/url_request/url_request_http_job_histogram.h"
bengr1bf8e942014-11-07 01:36:50122#include "net/url_request/url_request_intercepting_job_factory.h"
123#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49124#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51125#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47126#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44127#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01128#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52129#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15130#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52131
Eric Romanefddd0a2017-10-10 02:14:25132#if defined(OS_FUCHSIA)
133#define USE_BUILTIN_CERT_VERIFIER
134#endif
135
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)
mmenke9f2ec60c2015-06-01 20:59:47143#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29144#include "net/url_request/ftp_protocol_handler.h"
145#endif
146
[email protected]dffe8242012-03-20 15:14:27147#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48148#include "base/win/scoped_com_initializer.h"
[email protected]dffe8242012-03-20 15:14:27149#endif
150
mmenkefd9d15c2017-06-29 13:45:54151#if BUILDFLAG(ENABLE_REPORTING)
Julia Tuttlecba7d222018-02-23 19:37:27152#include "net/network_error_logging/network_error_logging_service.h"
mmenkefd9d15c2017-06-29 13:45:54153#endif // BUILDFLAG(ENABLE_REPORTING)
154
Matt Muellerfb271992018-01-30 18:10:48155#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:25156#include "net/cert/cert_net_fetcher.h"
157#include "net/cert_net/cert_net_fetcher_impl.h"
158#endif
159
160#if defined(USE_NSS_CERTS)
161#include "net/cert_net/nss_ocsp.h"
162#endif
163
robpercival214763f2016-07-01 23:27:01164using net::test::IsError;
165using net::test::IsOk;
166
[email protected]ad65a3e2013-12-25 18:18:01167using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33168using base::Time;
halton.huoe4e45742014-12-08 07:55:46169using std::string;
[email protected]e1acf6f2008-10-27 20:43:33170
[email protected]7461a402011-03-24 23:19:51171namespace net {
172
initial.commit586acc5fe2008-07-26 22:42:52173namespace {
174
Martijn Croonenb1383da2017-10-11 11:56:35175namespace test_default {
176#include "net/http/transport_security_state_static_unittest_default.h"
xunjieli815ad5b2017-07-18 15:51:35177}
178
[email protected]42cba2fb2013-03-29 19:58:57179const base::string16 kChrome(ASCIIToUTF16("chrome"));
180const base::string16 kSecret(ASCIIToUTF16("secret"));
181const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44182
mmenke9f2ec60c2015-06-01 20:59:47183const base::FilePath::CharType kTestFilePath[] =
184 FILE_PATH_LITERAL("net/data/url_request_unittest");
185
Sergey Ulanovc4580e72017-09-13 23:30:11186#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
187 !defined(OS_FUCHSIA)
mmenke9f2ec60c2015-06-01 20:59:47188// Test file used in most FTP tests.
189const char kFtpTestFile[] = "BullRunSpeech.txt";
190#endif
191
[email protected]2bba3252013-04-08 19:50:59192// Tests load timing information in the case a fresh connection was used, with
193// no proxy.
[email protected]cba24642014-08-15 20:49:59194void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25195 int connect_timing_flags) {
196 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19197 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25198
199 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
200 EXPECT_FALSE(load_timing_info.request_start.is_null());
201
202 EXPECT_LE(load_timing_info.request_start,
203 load_timing_info.connect_timing.connect_start);
204 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
205 connect_timing_flags);
206 EXPECT_LE(load_timing_info.connect_timing.connect_end,
207 load_timing_info.send_start);
208 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
209 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
210
[email protected]58e32bb2013-01-21 18:23:25211 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
212 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
213}
214
[email protected]2bba3252013-04-08 19:50:59215// Same as above, but with proxy times.
216void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59217 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59218 int connect_timing_flags) {
219 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19220 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59221
222 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
223 EXPECT_FALSE(load_timing_info.request_start.is_null());
224
225 EXPECT_LE(load_timing_info.request_start,
226 load_timing_info.proxy_resolve_start);
227 EXPECT_LE(load_timing_info.proxy_resolve_start,
228 load_timing_info.proxy_resolve_end);
229 EXPECT_LE(load_timing_info.proxy_resolve_end,
230 load_timing_info.connect_timing.connect_start);
231 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
232 connect_timing_flags);
233 EXPECT_LE(load_timing_info.connect_timing.connect_end,
234 load_timing_info.send_start);
235 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
236 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
237}
238
239// Same as above, but with a reused socket and proxy times.
240void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59241 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59242 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19243 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59244
245 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
246 EXPECT_FALSE(load_timing_info.request_start.is_null());
247
248 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
249
250 EXPECT_LE(load_timing_info.request_start,
251 load_timing_info.proxy_resolve_start);
252 EXPECT_LE(load_timing_info.proxy_resolve_start,
253 load_timing_info.proxy_resolve_end);
254 EXPECT_LE(load_timing_info.proxy_resolve_end,
255 load_timing_info.send_start);
256 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
257 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
258}
259
brettwa1228ebb2016-10-28 03:51:34260#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25261// Tests load timing information in the case of a cache hit, when no cache
262// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17263base::StringPiece TestNetResourceProvider(int key) {
264 return "header";
265}
266
267void FillBuffer(char* buffer, size_t len) {
268 static bool called = false;
269 if (!called) {
270 called = true;
271 int seed = static_cast<int>(Time::Now().ToInternalValue());
272 srand(seed);
273 }
274
275 for (size_t i = 0; i < len; i++) {
276 buffer[i] = static_cast<char>(rand());
277 if (!buffer[i])
278 buffer[i] = 'g';
279 }
280}
xunjielia6888202015-04-14 21:34:25281#endif
[email protected]e3a85452013-11-14 01:46:17282
[email protected]3b23a222013-05-15 21:33:25283void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59284 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25285 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19286 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25287
288 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
289 EXPECT_FALSE(load_timing_info.request_start.is_null());
290
291 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
292 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
293 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
294 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
295
296 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
297 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
298}
299
Sergey Ulanovc4580e72017-09-13 23:30:11300#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
301 !defined(OS_FUCHSIA)
[email protected]3b23a222013-05-15 21:33:25302// Tests load timing in the case that there is no HTTP response. This can be
303// used to test in the case of errors or non-HTTP requests.
304void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59305 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25306 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19307 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25308
309 // Only the request times should be non-null.
310 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
311 EXPECT_FALSE(load_timing_info.request_start.is_null());
312
313 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
314
315 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
316 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
317 EXPECT_TRUE(load_timing_info.send_start.is_null());
318 EXPECT_TRUE(load_timing_info.send_end.is_null());
319 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
320}
xunjielia6888202015-04-14 21:34:25321#endif
[email protected]58e32bb2013-01-21 18:23:25322
mmenkefb18c772015-09-30 22:22:50323// Test power monitor source that can simulate entering suspend mode. Can't use
324// the one in base/ because it insists on bringing its own MessageLoop.
325class TestPowerMonitorSource : public base::PowerMonitorSource {
326 public:
Chris Watkins7a41d3552017-12-01 02:13:27327 TestPowerMonitorSource() = default;
328 ~TestPowerMonitorSource() override = default;
mmenkefb18c772015-09-30 22:22:50329
Colin Blundellc46597f2018-06-14 16:43:10330 void Shutdown() override {}
331
mmenkefb18c772015-09-30 22:22:50332 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
333
334 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
335
336 bool IsOnBatteryPowerImpl() override { return false; }
337
338 private:
339 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
340};
341
mmenkeed0498b2015-12-08 23:20:42342// Job that allows monitoring of its priority.
343class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
344 public:
345 // The latest priority of the job is always written to |request_priority_|.
346 PriorityMonitoringURLRequestJob(URLRequest* request,
347 NetworkDelegate* network_delegate,
348 RequestPriority* request_priority)
349 : URLRequestTestJob(request, network_delegate),
350 request_priority_(request_priority) {
351 *request_priority_ = DEFAULT_PRIORITY;
352 }
353
354 void SetPriority(RequestPriority priority) override {
355 *request_priority_ = priority;
356 URLRequestTestJob::SetPriority(priority);
357 }
358
359 private:
360 RequestPriority* const request_priority_;
361};
362
[email protected]71c64f62008-11-15 04:36:51363// Do a case-insensitive search through |haystack| for |needle|.
364bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50365 std::string::const_iterator it = std::search(
366 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
367 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51368 return it != haystack.end();
369}
370
danakj8522a25b2016-04-16 00:17:36371std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
372 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28373 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48374 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23375}
376
[email protected]96adadb2010-08-28 01:16:17377// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51378void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17379 // -1 means unknown. 0 means no encryption.
380 EXPECT_GT(ssl_info.security_bits, 0);
381
382 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14383 uint16_t cipher_suite =
384 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29385 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17386}
387
[email protected]79e1fd62013-06-20 06:50:04388void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
389 const GURL& host_url) {
390 std::string sent_value;
391
392 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
393 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
394
395 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
396 EXPECT_EQ("keep-alive", sent_value);
397}
398
[email protected]dc5a5cf2012-09-26 02:49:30399// A network delegate that allows the user to choose a subset of request stages
400// to block in. When blocking, the delegate can do one of the following:
401// * synchronously return a pre-specified error code, or
402// * asynchronously return that value via an automatically called callback,
403// or
404// * block and wait for the user to do a callback.
405// Additionally, the user may also specify a redirect URL -- then each request
406// with the current URL different from the redirect target will be redirected
407// to that target, in the on-before-URL-request stage, independent of whether
408// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12409class BlockingNetworkDelegate : public TestNetworkDelegate {
410 public:
[email protected]dc5a5cf2012-09-26 02:49:30411 // Stages in which the delegate can block.
412 enum Stage {
[email protected]9045b8822012-01-13 20:35:35413 NOT_BLOCKED = 0,
414 ON_BEFORE_URL_REQUEST = 1 << 0,
415 ON_BEFORE_SEND_HEADERS = 1 << 1,
416 ON_HEADERS_RECEIVED = 1 << 2,
417 ON_AUTH_REQUIRED = 1 << 3
418 };
419
[email protected]dc5a5cf2012-09-26 02:49:30420 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59421 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30422 enum BlockMode {
423 SYNCHRONOUS, // No callback, returns specified return values.
424 AUTO_CALLBACK, // |this| posts a task to run the callback using the
425 // specified return codes.
426 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
427 // |auth_retval_| are ignored. In every blocking stage the
428 // message loop is quit.
429 };
430
431 // Creates a delegate which does not block at all.
432 explicit BlockingNetworkDelegate(BlockMode block_mode);
433
Wez2a31b222018-06-07 22:07:15434 // Runs the message loop until the delegate blocks.
435 void RunUntilBlocked();
436
[email protected]dc5a5cf2012-09-26 02:49:30437 // For users to trigger a callback returning |response|.
438 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
439 // Only call if |block_mode_| == USER_CALLBACK.
440 void DoCallback(int response);
441 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
442
443 // Setters.
444 void set_retval(int retval) {
445 ASSERT_NE(USER_CALLBACK, block_mode_);
446 ASSERT_NE(ERR_IO_PENDING, retval);
447 ASSERT_NE(OK, retval);
448 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35449 }
450
[email protected]dc5a5cf2012-09-26 02:49:30451 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
452 // |auth_credentials_| will be passed with the response.
453 void set_auth_retval(AuthRequiredResponse auth_retval) {
454 ASSERT_NE(USER_CALLBACK, block_mode_);
455 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
456 auth_retval_ = auth_retval;
457 }
458 void set_auth_credentials(const AuthCredentials& auth_credentials) {
459 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35460 }
461
[email protected]dc5a5cf2012-09-26 02:49:30462 void set_redirect_url(const GURL& url) {
463 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35464 }
465
[email protected]dc5a5cf2012-09-26 02:49:30466 void set_block_on(int block_on) {
467 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35468 }
469
[email protected]dc5a5cf2012-09-26 02:49:30470 // Allows the user to check in which state did we block.
471 Stage stage_blocked_for_callback() const {
472 EXPECT_EQ(USER_CALLBACK, block_mode_);
473 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35474 }
475
476 private:
Wez2a31b222018-06-07 22:07:15477 void OnBlocked();
478
David Benjamind1f287bf2018-06-12 01:57:20479 void RunCallback(int response, CompletionOnceCallback callback);
480 void RunAuthCallback(AuthRequiredResponse response, AuthCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30481
[email protected]9045b8822012-01-13 20:35:35482 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20483 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20484 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:20485 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35486
ryansturm2343cb62016-06-15 01:09:00487 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20488 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:00489 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35490
dchengb03027d2014-10-21 12:00:20491 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35492 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20493 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32494 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16495 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13496 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35497
dchengb03027d2014-10-21 12:00:20498 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35499 URLRequest* request,
500 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20501 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:13502 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35503
[email protected]dc5a5cf2012-09-26 02:49:30504 // Resets the callbacks and |stage_blocked_for_callback_|.
505 void Reset();
[email protected]9045b8822012-01-13 20:35:35506
[email protected]dc5a5cf2012-09-26 02:49:30507 // Checks whether we should block in |stage|. If yes, returns an error code
508 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
David Benjamind1f287bf2018-06-12 01:57:20509 int MaybeBlockStage(Stage stage, CompletionOnceCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30510
511 // Configuration parameters, can be adjusted by public methods:
512 const BlockMode block_mode_;
513
514 // Values returned on blocking stages when mode is SYNCHRONOUS or
515 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
516 int retval_; // To be returned in non-auth stages.
517 AuthRequiredResponse auth_retval_;
518
[email protected]5f714132014-03-26 10:41:16519 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30520 int block_on_; // Bit mask: in which stages to block.
521
522 // |auth_credentials_| will be copied to |*target_auth_credential_| on
523 // callback.
524 AuthCredentials auth_credentials_;
525 AuthCredentials* target_auth_credentials_;
526
527 // Internal variables, not set by not the user:
528 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
529 // USER_CALLBACK).
530 Stage stage_blocked_for_callback_;
531
532 // Callback objects stored during blocking stages.
David Benjamind1f287bf2018-06-12 01:57:20533 CompletionOnceCallback callback_;
[email protected]9045b8822012-01-13 20:35:35534 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30535
Wez2a31b222018-06-07 22:07:15536 // Closure to run to exit RunUntilBlocked().
537 base::OnceClosure on_blocked_;
538
[email protected]dc5a5cf2012-09-26 02:49:30539 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
540
541 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35542};
543
[email protected]dc5a5cf2012-09-26 02:49:30544BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
545 : block_mode_(block_mode),
546 retval_(OK),
547 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
548 block_on_(0),
549 target_auth_credentials_(NULL),
550 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32551 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30552}
553
Wez2a31b222018-06-07 22:07:15554void BlockingNetworkDelegate::RunUntilBlocked() {
555 base::RunLoop run_loop;
556 on_blocked_ = run_loop.QuitClosure();
557 run_loop.Run();
558}
559
[email protected]dc5a5cf2012-09-26 02:49:30560void BlockingNetworkDelegate::DoCallback(int response) {
561 ASSERT_EQ(USER_CALLBACK, block_mode_);
562 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
563 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20564 CompletionOnceCallback callback = std::move(callback_);
[email protected]dc5a5cf2012-09-26 02:49:30565 Reset();
Wez2a31b222018-06-07 22:07:15566
567 // |callback| may trigger completion of a request, so post it as a task, so
568 // it will run under a subsequent TestDelegate::RunUntilComplete() loop.
569 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20570 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
571 weak_factory_.GetWeakPtr(), response,
572 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30573}
574
575void BlockingNetworkDelegate::DoAuthCallback(
576 NetworkDelegate::AuthRequiredResponse response) {
577 ASSERT_EQ(USER_CALLBACK, block_mode_);
578 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20579 AuthCallback auth_callback = std::move(auth_callback_);
[email protected]dc5a5cf2012-09-26 02:49:30580 Reset();
David Benjamind1f287bf2018-06-12 01:57:20581 RunAuthCallback(response, std::move(auth_callback));
[email protected]dc5a5cf2012-09-26 02:49:30582}
583
Wez2a31b222018-06-07 22:07:15584void BlockingNetworkDelegate::OnBlocked() {
585 // If this fails due to |on_blocked_| being null then OnBlocked() was run by
586 // a RunLoop other than RunUntilBlocked(), indicating a bug in the calling
587 // test.
588 std::move(on_blocked_).Run();
589}
590
[email protected]dc5a5cf2012-09-26 02:49:30591void BlockingNetworkDelegate::RunCallback(int response,
David Benjamind1f287bf2018-06-12 01:57:20592 CompletionOnceCallback callback) {
593 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30594}
595
596void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
David Benjamind1f287bf2018-06-12 01:57:20597 AuthCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30598 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
599 ASSERT_TRUE(target_auth_credentials_ != NULL);
600 *target_auth_credentials_ = auth_credentials_;
601 }
David Benjamind1f287bf2018-06-12 01:57:20602 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30603}
604
David Benjamind1f287bf2018-06-12 01:57:20605int BlockingNetworkDelegate::OnBeforeURLRequest(URLRequest* request,
606 CompletionOnceCallback callback,
607 GURL* new_url) {
[email protected]dc5a5cf2012-09-26 02:49:30608 if (redirect_url_ == request->url())
609 return OK; // We've already seen this request and redirected elsewhere.
610
David Benjamind1f287bf2018-06-12 01:57:20611 // TestNetworkDelegate always completes synchronously.
612 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
613 request, base::NullCallback(), new_url));
[email protected]dc5a5cf2012-09-26 02:49:30614
615 if (!redirect_url_.is_empty())
616 *new_url = redirect_url_;
617
David Benjamind1f287bf2018-06-12 01:57:20618 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30619}
620
ryansturm2343cb62016-06-15 01:09:00621int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30622 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20623 CompletionOnceCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30624 HttpRequestHeaders* headers) {
David Benjamind1f287bf2018-06-12 01:57:20625 // TestNetworkDelegate always completes synchronously.
626 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
627 request, base::NullCallback(), headers));
[email protected]dc5a5cf2012-09-26 02:49:30628
David Benjamind1f287bf2018-06-12 01:57:20629 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30630}
631
632int BlockingNetworkDelegate::OnHeadersReceived(
633 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20634 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32635 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16636 scoped_refptr<HttpResponseHeaders>* override_response_headers,
637 GURL* allowed_unsafe_redirect_url) {
David Benjamind1f287bf2018-06-12 01:57:20638 // TestNetworkDelegate always completes synchronously.
639 CHECK_NE(ERR_IO_PENDING,
640 TestNetworkDelegate::OnHeadersReceived(
641 request, base::NullCallback(), original_response_headers,
642 override_response_headers, allowed_unsafe_redirect_url));
[email protected]dc5a5cf2012-09-26 02:49:30643
David Benjamind1f287bf2018-06-12 01:57:20644 return MaybeBlockStage(ON_HEADERS_RECEIVED, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30645}
646
647NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
648 URLRequest* request,
649 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20650 AuthCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30651 AuthCredentials* credentials) {
David Benjamind1f287bf2018-06-12 01:57:20652 // TestNetworkDelegate always completes synchronously.
653 CHECK_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING,
654 TestNetworkDelegate::OnAuthRequired(
655 request, auth_info, base::NullCallback(), credentials));
[email protected]dc5a5cf2012-09-26 02:49:30656 // Check that the user has provided callback for the previous blocked stage.
657 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
658
659 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
660 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
661 }
662
663 target_auth_credentials_ = credentials;
664
665 switch (block_mode_) {
666 case SYNCHRONOUS:
667 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
668 *target_auth_credentials_ = auth_credentials_;
669 return auth_retval_;
670
671 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45672 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20673 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunAuthCallback,
674 weak_factory_.GetWeakPtr(), auth_retval_,
675 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30676 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
677
678 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20679 auth_callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30680 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
Wez2a31b222018-06-07 22:07:15681 // We may reach here via a callback prior to RunUntilBlocked(), so post
682 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45683 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15684 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
685 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30686 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
687 }
688 NOTREACHED();
689 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
690}
691
692void BlockingNetworkDelegate::Reset() {
693 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
694 stage_blocked_for_callback_ = NOT_BLOCKED;
695 callback_.Reset();
696 auth_callback_.Reset();
697}
698
699int BlockingNetworkDelegate::MaybeBlockStage(
700 BlockingNetworkDelegate::Stage stage,
David Benjamind1f287bf2018-06-12 01:57:20701 CompletionOnceCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30702 // Check that the user has provided callback for the previous blocked stage.
703 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
704
705 if ((block_on_ & stage) == 0) {
706 return OK;
707 }
708
709 switch (block_mode_) {
710 case SYNCHRONOUS:
711 EXPECT_NE(OK, retval_);
712 return retval_;
713
714 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45715 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20716 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
717 weak_factory_.GetWeakPtr(), retval_,
718 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30719 return ERR_IO_PENDING;
720
721 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20722 callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30723 stage_blocked_for_callback_ = stage;
Wez2a31b222018-06-07 22:07:15724 // We may reach here via a callback prior to RunUntilBlocked(), so post
725 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45726 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15727 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
728 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30729 return ERR_IO_PENDING;
730 }
731 NOTREACHED();
732 return 0;
733}
734
[email protected]d5a4dd62012-05-23 01:41:04735class TestURLRequestContextWithProxy : public TestURLRequestContext {
736 public:
737 // Does not own |delegate|.
738 TestURLRequestContextWithProxy(const std::string& proxy,
739 NetworkDelegate* delegate)
740 : 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);
745 Init();
746 }
Chris Watkins7a41d3552017-12-01 02:13:27747 ~TestURLRequestContextWithProxy() override = default;
[email protected]d5a4dd62012-05-23 01:41:04748};
749
stefanocsbd5be5202016-06-10 03:37:55750// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01751// URI and report to be sent.
752class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55753 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01754 public:
Chris Watkins7a41d3552017-12-01 02:13:27755 MockCertificateReportSender() = default;
756 ~MockCertificateReportSender() override = default;
estark06e0dac2015-08-07 21:56:01757
meacer5d4dc5a2017-04-27 20:37:48758 void Send(const GURL& report_uri,
759 base::StringPiece content_type,
760 base::StringPiece report,
761 const base::Callback<void()>& success_callback,
762 const base::Callback<void(const GURL&, int, int)>& error_callback)
763 override {
estark06e0dac2015-08-07 21:56:01764 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44765 report.CopyToString(&latest_report_);
766 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01767 }
estark06e0dac2015-08-07 21:56:01768 const GURL& latest_report_uri() { return latest_report_uri_; }
769 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44770 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01771
772 private:
773 GURL latest_report_uri_;
774 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44775 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01776};
777
dadrian612337a2016-07-20 22:36:58778// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
779// This is needed because after the certificate failure, the URLRequest will
780// retry the connection, and return a partial SSLInfo with a cached cert status.
781// The partial SSLInfo does not have the OCSP information filled out.
782class OCSPErrorTestDelegate : public TestDelegate {
783 public:
784 void OnSSLCertificateError(URLRequest* request,
785 const SSLInfo& ssl_info,
786 bool fatal) override {
787 ssl_info_ = ssl_info;
788 on_ssl_certificate_error_called_ = true;
789 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
790 }
791
792 bool on_ssl_certificate_error_called() {
793 return on_ssl_certificate_error_called_;
794 }
795
796 SSLInfo ssl_info() { return ssl_info_; }
797
798 private:
799 bool on_ssl_certificate_error_called_ = false;
800 SSLInfo ssl_info_;
801};
802
[email protected]d5a4dd62012-05-23 01:41:04803} // namespace
804
[email protected]a592c0432012-12-01 18:10:29805// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
Bence Béky98447b12018-05-08 03:14:01806class URLRequestTest : public PlatformTest, public WithScopedTaskEnvironment {
[email protected]abb26092010-11-11 22:19:00807 public:
Ryan Sleevib8449e02018-07-15 04:31:07808 URLRequestTest()
809 : default_context_(std::make_unique<TestURLRequestContext>(true)) {
810 default_context_->set_network_delegate(&default_network_delegate_);
811 default_context_->set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50812 job_factory_impl_ = new URLRequestJobFactoryImpl();
813 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50814 }
bengr1bf8e942014-11-07 01:36:50815
dcheng67be2b1f2014-10-27 21:47:29816 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18817 // URLRequestJobs may post clean-up tasks on destruction.
818 base::RunLoop().RunUntilIdle();
Martijn Croonenb1383da2017-10-11 11:56:35819
820 SetTransportSecurityStateSourceForTesting(nullptr);
[email protected]e4034ad2013-09-20 08:36:18821 }
[email protected]87a09a92011-07-14 15:50:50822
dcheng2339883c2014-12-23 00:23:05823 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50824 SetUpFactory();
Ryan Sleevib8449e02018-07-15 04:31:07825 default_context_->set_job_factory(job_factory_.get());
826 default_context_->Init();
bengr1bf8e942014-11-07 01:36:50827 PlatformTest::SetUp();
828 }
829
Ryan Sleevib8449e02018-07-15 04:31:07830 void TearDown() override { default_context_.reset(); }
831
bengr1bf8e942014-11-07 01:36:50832 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20833 job_factory_impl_->SetProtocolHandler(
Bence Béky8f9d7d3952017-10-09 19:58:04834 "data", std::make_unique<DataProtocolHandler>());
brettwa1228ebb2016-10-28 03:51:34835#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50836 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19837 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07838 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50839#endif
840 }
841
842 TestNetworkDelegate* default_network_delegate() {
843 return &default_network_delegate_;
844 }
845
Ryan Sleevib8449e02018-07-15 04:31:07846 TestURLRequestContext& default_context() const { return *default_context_; }
bengr1bf8e942014-11-07 01:36:50847
[email protected]3c5ca8c2011-09-29 01:14:51848 // Adds the TestJobInterceptor to the default context.
849 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23850 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20851 job_factory_impl_->SetProtocolHandler("http", nullptr);
852 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36853 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23854 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51855 }
856
Sergey Ulanov2e49f492017-09-14 19:37:51857 // Creates a temp test file and writes |data| to the file. The file will be
858 // deleted after the test completes.
859 void CreateTestFile(const char* data,
860 size_t data_size,
861 base::FilePath* test_file) {
862 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
863 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
864 // now, Mac and Android bots return a path with a symbolic link.
865 base::FilePath absolute_temp_dir =
866 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
867
868 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
869 ASSERT_EQ(static_cast<int>(data_size),
870 base::WriteFile(*test_file, data, data_size));
871 }
872
[email protected]87a09a92011-07-14 15:50:50873 protected:
vishal.b62985ca92015-04-17 08:45:51874 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24875 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50876 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36877 std::unique_ptr<URLRequestJobFactory> job_factory_;
Ryan Sleevib8449e02018-07-15 04:31:07878 std::unique_ptr<TestURLRequestContext> default_context_;
Sergey Ulanov2e49f492017-09-14 19:37:51879 base::ScopedTempDir temp_dir_;
[email protected]7a0bb4bf2008-11-19 21:41:48880};
881
satoruxddac0442017-05-29 06:06:18882// This NetworkDelegate is picky about what files are accessible. Only
883// whitelisted files are allowed.
884class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
885 public:
Chris Watkins7a41d3552017-12-01 02:13:27886 CookieBlockingNetworkDelegate() = default;
887 ;
satoruxddac0442017-05-29 06:06:18888
889 // Adds |directory| to the access white list.
890 void AddToWhitelist(const base::FilePath& directory) {
891 whitelist_.insert(directory);
892 }
893
894 private:
895 // Returns true if |path| matches the white list.
896 bool OnCanAccessFileInternal(const base::FilePath& path) const {
897 for (const auto& directory : whitelist_) {
898 if (directory == path || directory.IsParent(path))
899 return true;
900 }
901 return false;
902 }
903
904 // Returns true only if both |original_path| and |absolute_path| match the
905 // white list.
906 bool OnCanAccessFile(const URLRequest& request,
907 const base::FilePath& original_path,
908 const base::FilePath& absolute_path) const override {
909 return (OnCanAccessFileInternal(original_path) &&
910 OnCanAccessFileInternal(absolute_path));
911 }
912
913 std::set<base::FilePath> whitelist_;
914
915 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
916};
917
[email protected]316c1e5e2012-09-12 15:17:44918TEST_F(URLRequestTest, AboutBlankTest) {
919 TestDelegate d;
920 {
rhalavatib7bd7c792017-04-27 05:25:16921 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:07922 default_context().CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
923 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44924
[email protected]f7022f32014-08-21 16:32:19925 r->Start();
926 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44927
Wez2a31b222018-06-07 22:07:15928 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44929
[email protected]f7022f32014-08-21 16:32:19930 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44931 EXPECT_FALSE(d.received_data_before_response());
932 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19933 EXPECT_EQ("", r->GetSocketAddress().host());
934 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04935
936 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19937 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44938 }
939}
940
941TEST_F(URLRequestTest, DataURLImageTest) {
942 TestDelegate d;
943 {
944 // Use our nice little Chrome logo.
Ryan Sleevib8449e02018-07-15 04:31:07945 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
danakj8522a25b2016-04-16 00:17:36946 GURL("data:image/png;base64,"
947 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
948 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
949 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
950 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
951 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
952 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
953 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
954 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
955 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
956 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
957 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
958 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
959 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
960 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
961 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
962 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
963 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
964 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
965 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16966 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44967
[email protected]f7022f32014-08-21 16:32:19968 r->Start();
969 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44970
Wez2a31b222018-06-07 22:07:15971 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44972
[email protected]f7022f32014-08-21 16:32:19973 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44974 EXPECT_FALSE(d.received_data_before_response());
975 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19976 EXPECT_EQ("", r->GetSocketAddress().host());
977 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04978
979 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19980 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44981 }
982}
983
brettwa1228ebb2016-10-28 03:51:34984#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44985TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51986 const char kTestFileContent[] = "Hello";
987 base::FilePath test_file;
988 ASSERT_NO_FATAL_FAILURE(
989 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04990
Sergey Ulanov2e49f492017-09-14 19:37:51991 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:44992
993 TestDelegate d;
994 {
Ryan Sleevib8449e02018-07-15 04:31:07995 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:51996 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44997
[email protected]f7022f32014-08-21 16:32:19998 r->Start();
999 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441000
Wez2a31b222018-06-07 22:07:151001 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441002
[email protected]f7022f32014-08-21 16:32:191003 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441004 EXPECT_EQ(1, d.response_started_count());
1005 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:511006 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
[email protected]f7022f32014-08-21 16:32:191007 EXPECT_EQ("", r->GetSocketAddress().host());
1008 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:041009
1010 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:191011 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:441012 }
1013}
1014
[email protected]ba40bb762012-12-17 07:11:041015TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:511016 const char kTestFileContent[] = "Hello";
1017 base::FilePath test_file;
1018 ASSERT_NO_FATAL_FAILURE(
1019 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
1020
1021 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:041022
1023 TestDelegate d;
1024 {
Ryan Sleevib8449e02018-07-15 04:31:071025 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511026 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:041027
[email protected]f7022f32014-08-21 16:32:191028 r->Start();
1029 EXPECT_TRUE(r->is_pending());
1030 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:041031 }
[email protected]79e1fd62013-06-20 06:50:041032 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:041033 // destroyed.
[email protected]255620da2013-08-19 13:14:291034 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041035}
1036
[email protected]316c1e5e2012-09-12 15:17:441037TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1038 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361039 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441040 FillBuffer(buffer.get(), buffer_size);
1041
Sergey Ulanov2e49f492017-09-14 19:37:511042 base::FilePath test_file;
1043 ASSERT_NO_FATAL_FAILURE(
1044 CreateTestFile(buffer.get(), buffer_size, &test_file));
1045 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441046
1047 const size_t first_byte_position = 500;
1048 const size_t last_byte_position = buffer_size - first_byte_position;
1049 const size_t content_length = last_byte_position - first_byte_position + 1;
1050 std::string partial_buffer_string(buffer.get() + first_byte_position,
1051 buffer.get() + last_byte_position + 1);
1052
1053 TestDelegate d;
1054 {
Ryan Sleevib8449e02018-07-15 04:31:071055 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161056 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441057
1058 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381059 headers.SetHeader(
1060 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591061 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381062 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191063 r->SetExtraRequestHeaders(headers);
1064 r->Start();
1065 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441066
Wez2a31b222018-06-07 22:07:151067 d.RunUntilComplete();
1068
[email protected]f7022f32014-08-21 16:32:191069 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441070 EXPECT_EQ(1, d.response_started_count());
1071 EXPECT_FALSE(d.received_data_before_response());
1072 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1073 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1074 EXPECT_TRUE(partial_buffer_string == d.data_received());
1075 }
[email protected]316c1e5e2012-09-12 15:17:441076}
1077
1078TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1079 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361080 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441081 FillBuffer(buffer.get(), buffer_size);
1082
Sergey Ulanov2e49f492017-09-14 19:37:511083 base::FilePath test_file;
1084 ASSERT_NO_FATAL_FAILURE(
1085 CreateTestFile(buffer.get(), buffer_size, &test_file));
1086 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441087
1088 const size_t first_byte_position = 500;
1089 const size_t last_byte_position = buffer_size - 1;
1090 const size_t content_length = last_byte_position - first_byte_position + 1;
1091 std::string partial_buffer_string(buffer.get() + first_byte_position,
1092 buffer.get() + last_byte_position + 1);
1093
1094 TestDelegate d;
1095 {
Ryan Sleevib8449e02018-07-15 04:31:071096 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161097 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441098
1099 HttpRequestHeaders headers;
1100 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591101 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381102 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191103 r->SetExtraRequestHeaders(headers);
1104 r->Start();
1105 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441106
[email protected]255620da2013-08-19 13:14:291107 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191108 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441109 EXPECT_EQ(1, d.response_started_count());
1110 EXPECT_FALSE(d.received_data_before_response());
1111 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1112 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1113 EXPECT_TRUE(partial_buffer_string == d.data_received());
1114 }
[email protected]316c1e5e2012-09-12 15:17:441115}
1116
1117TEST_F(URLRequestTest, FileTestMultipleRanges) {
1118 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361119 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441120 FillBuffer(buffer.get(), buffer_size);
1121
Sergey Ulanov2e49f492017-09-14 19:37:511122 base::FilePath test_file;
1123 ASSERT_NO_FATAL_FAILURE(
1124 CreateTestFile(buffer.get(), buffer_size, &test_file));
1125 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441126
1127 TestDelegate d;
1128 {
Ryan Sleevib8449e02018-07-15 04:31:071129 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161130 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441131
1132 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381133 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191134 r->SetExtraRequestHeaders(headers);
1135 r->Start();
1136 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441137
Wez2a31b222018-06-07 22:07:151138 d.RunUntilComplete();
1139
[email protected]316c1e5e2012-09-12 15:17:441140 EXPECT_TRUE(d.request_failed());
1141 }
[email protected]316c1e5e2012-09-12 15:17:441142}
1143
[email protected]3ca8b362013-11-11 22:18:071144TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511145 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071146 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511147 ASSERT_NO_FATAL_FAILURE(
1148 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1149
satoruxddac0442017-05-29 06:06:181150 // The directory part of the path returned from CreateTemporaryFileInDir()
1151 // can be slightly different from |absolute_temp_dir| on Windows.
1152 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1153 // Hence the test should use the directory name of |test_file|, rather than
1154 // |absolute_temp_dir|, for whitelisting.
1155 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591156 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071157 {
1158 TestDelegate d;
satoruxddac0442017-05-29 06:06:181159 CookieBlockingNetworkDelegate network_delegate;
1160 network_delegate.AddToWhitelist(real_temp_dir);
Ryan Sleevib8449e02018-07-15 04:31:071161 default_context().set_network_delegate(&network_delegate);
1162 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161163 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191164 r->Start();
Wez2a31b222018-06-07 22:07:151165 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181166 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071167 EXPECT_FALSE(d.request_failed());
1168 EXPECT_EQ(test_data, d.data_received());
1169 }
1170
1171 {
1172 TestDelegate d;
satoruxddac0442017-05-29 06:06:181173 CookieBlockingNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:071174 default_context().set_network_delegate(&network_delegate);
1175 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161176 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191177 r->Start();
Wez2a31b222018-06-07 22:07:151178 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181179 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071180 EXPECT_TRUE(d.request_failed());
1181 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181182 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071183 }
1184}
1185
Wez35539132018-07-17 11:26:051186#if defined(OS_POSIX) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181187
1188TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511189 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181190 // Get an absolute path since temp_dir can contain a symbolic link.
1191 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511192 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181193
1194 // Create a good directory (will be whitelisted) and a good file.
1195 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1196 ASSERT_TRUE(base::CreateDirectory(good_dir));
1197 base::FilePath good_file;
1198 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1199 std::string good_data("good");
1200 base::WriteFile(good_file, good_data.data(), good_data.size());
1201 // See the comment in AllowFileURLs() for why this is done.
1202 base::FilePath real_good_dir = good_file.DirName();
1203
1204 // Create a bad directory (will not be whitelisted) and a bad file.
1205 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1206 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1207 base::FilePath bad_file;
1208 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1209 std::string bad_data("bad");
1210 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1211
1212 // This symlink will point to the good file. Access to the symlink will be
1213 // allowed as both the symlink and the destination file are in the same
1214 // good directory.
1215 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1216 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1217 GURL good_file_url = FilePathToFileURL(good_symlink);
1218 // This symlink will point to the bad file. Even though the symlink is in
1219 // the good directory, access to the symlink will be rejected since it
1220 // points to the bad file.
1221 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1222 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1223 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1224
1225 CookieBlockingNetworkDelegate network_delegate;
1226 network_delegate.AddToWhitelist(real_good_dir);
1227 {
1228 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071229 default_context().set_network_delegate(&network_delegate);
1230 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371231 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181232 r->Start();
Wez2a31b222018-06-07 22:07:151233 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181234 // good_file_url should be allowed.
1235 EXPECT_FALSE(d.request_failed());
1236 EXPECT_EQ(good_data, d.data_received());
1237 }
1238
1239 {
1240 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071241 default_context().set_network_delegate(&network_delegate);
1242 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371243 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181244 r->Start();
Wez2a31b222018-06-07 22:07:151245 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181246 // bad_file_url should be rejected.
1247 EXPECT_TRUE(d.request_failed());
1248 EXPECT_EQ("", d.data_received());
1249 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1250 }
1251}
1252
1253TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511254 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181255 // Get an absolute path since temp_dir can contain a symbolic link.
1256 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511257 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181258
1259 // Create a good directory (will be whitelisted).
1260 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1261 ASSERT_TRUE(base::CreateDirectory(good_dir));
1262
1263 // Create a bad directory (will not be whitelisted).
1264 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1265 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1266
1267 // This symlink will point to the good directory. Access to the symlink
1268 // will be allowed as the symlink is in the good dir that'll be white
1269 // listed.
1270 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1271 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1272 GURL good_file_url = FilePathToFileURL(good_symlink);
1273 // This symlink will point to the bad directory. Even though the symlink is
1274 // in the good directory, access to the symlink will be rejected since it
1275 // points to the bad directory.
1276 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1277 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1278 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1279
1280 CookieBlockingNetworkDelegate network_delegate;
1281 network_delegate.AddToWhitelist(good_dir);
1282 {
1283 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071284 default_context().set_network_delegate(&network_delegate);
1285 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371286 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181287 r->Start();
Wez2a31b222018-06-07 22:07:151288 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181289 // good_file_url should be allowed.
1290 EXPECT_FALSE(d.request_failed());
1291 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1292 }
1293
1294 {
1295 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071296 default_context().set_network_delegate(&network_delegate);
1297 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Ramin Halavati91cbba342017-07-19 13:13:371298 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181299 r->Start();
Wez2a31b222018-06-07 22:07:151300 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181301 // bad_file_url should be rejected.
1302 EXPECT_TRUE(d.request_failed());
1303 EXPECT_EQ("", d.data_received());
1304 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1305 }
1306}
1307
Wez35539132018-07-17 11:26:051308#endif // defined(OS_POSIX)
[email protected]316c1e5e2012-09-12 15:17:441309
1310TEST_F(URLRequestTest, FileDirCancelTest) {
1311 // Put in mock resource provider.
1312 NetModule::SetResourceProvider(TestNetResourceProvider);
1313
1314 TestDelegate d;
1315 {
[email protected]6cdfd7f2013-02-08 20:40:151316 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:191317 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
[email protected]316c1e5e2012-09-12 15:17:441318 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1319 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1320
Ryan Sleevib8449e02018-07-15 04:31:071321 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161322 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1323 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191324 req->Start();
1325 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441326
1327 d.set_cancel_in_received_data_pending(true);
1328
Wez2a31b222018-06-07 22:07:151329 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441330 }
1331
1332 // Take out mock resource provider.
1333 NetModule::SetResourceProvider(NULL);
1334}
1335
[email protected]5f9581402013-10-30 13:08:321336TEST_F(URLRequestTest, FileDirOutputSanity) {
1337 // Verify the general sanity of the the output of the file:
1338 // directory lister by checking for the output of a known existing
1339 // file.
1340 const char sentinel_name[] = "filedir-sentinel";
1341
1342 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191343 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471344 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321345
1346 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161347 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071348 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1349 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191350 req->Start();
Wez2a31b222018-06-07 22:07:151351 d.RunUntilComplete();
[email protected]5f9581402013-10-30 13:08:321352
1353 // Generate entry for the sentinel file.
1354 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581355 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491356 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321357 EXPECT_GT(info.size, 0);
1358 std::string sentinel_output = GetDirectoryListingEntry(
1359 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181360 std::string(sentinel_name), false /* is_dir */, info.size,
1361
[email protected]5f9581402013-10-30 13:08:321362 info.last_modified);
1363
1364 ASSERT_LT(0, d.bytes_received());
1365 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501366 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321367 // Check for the entry generated for the "sentinel" file.
1368 const std::string& data = d.data_received();
1369 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1370}
1371
[email protected]316c1e5e2012-09-12 15:17:441372TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1373 // There is an implicit redirect when loading a file path that matches a
1374 // directory and does not end with a slash. Ensure that following such
1375 // redirects does not crash. See http://crbug.com/18686.
1376
[email protected]6cdfd7f2013-02-08 20:40:151377 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191378 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471379 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441380
1381 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161382 std::unique_ptr<URLRequest> req(
Ryan Sleevib8449e02018-07-15 04:31:071383 default_context().CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1384 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191385 req->Start();
Wez2a31b222018-06-07 22:07:151386 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441387
1388 ASSERT_EQ(1, d.received_redirect_count());
1389 ASSERT_LT(0, d.bytes_received());
1390 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501391 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441392}
1393
1394#if defined(OS_WIN)
1395// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1396TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1397 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:071398 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161399 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191400 req->Start();
Wez2a31b222018-06-07 22:07:151401 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441402
1403 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501404 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441405}
[email protected]5ecf7cb282014-05-11 01:49:551406#endif // defined(OS_WIN)
1407
brettwa1228ebb2016-10-28 03:51:341408#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551409
1410TEST_F(URLRequestTest, InvalidUrlTest) {
1411 TestDelegate d;
1412 {
rhalavatib7bd7c792017-04-27 05:25:161413 std::unique_ptr<URLRequest> r(
Ryan Sleevib8449e02018-07-15 04:31:071414 default_context().CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1415 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551416
[email protected]f7022f32014-08-21 16:32:191417 r->Start();
1418 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551419
Wez2a31b222018-06-07 22:07:151420 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551421 EXPECT_TRUE(d.request_failed());
1422 }
1423}
1424
jochen0e3b3a62014-09-16 18:31:231425TEST_F(URLRequestTest, InvalidReferrerTest) {
1426 TestURLRequestContext context;
1427 TestNetworkDelegate network_delegate;
1428 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1429 context.set_network_delegate(&network_delegate);
1430 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361431 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161432 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1433 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231434 req->SetReferrer("https://somewhere.com/");
1435
1436 req->Start();
Wez2a31b222018-06-07 22:07:151437 d.RunUntilComplete();
jochen0e3b3a62014-09-16 18:31:231438 EXPECT_TRUE(d.request_failed());
1439}
1440
[email protected]5ecf7cb282014-05-11 01:49:551441#if defined(OS_WIN)
1442TEST_F(URLRequestTest, ResolveShortcutTest) {
1443 base::FilePath app_path;
Avi Drissman5c80d832018-05-01 17:01:191444 base::PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471445 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551446 app_path = app_path.AppendASCII("with-headers.html");
1447
1448 std::wstring lnk_path = app_path.value() + L".lnk";
1449
1450 base::win::ScopedCOMInitializer com_initializer;
1451
1452 // Temporarily create a shortcut for test
1453 {
Robert Liaoc88f99d12017-10-17 21:48:331454 Microsoft::WRL::ComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161455 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
1456 CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
Robert Liaoc88f99d12017-10-17 21:48:331457 Microsoft::WRL::ComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001458 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
[email protected]5ecf7cb282014-05-11 01:49:551459 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1460 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1461 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1462 }
1463
1464 TestDelegate d;
1465 {
Ryan Sleevib8449e02018-07-15 04:31:071466 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161467 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1468 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551469
[email protected]f7022f32014-08-21 16:32:191470 r->Start();
1471 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551472
Wez2a31b222018-06-07 22:07:151473 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551474
1475 WIN32_FILE_ATTRIBUTE_DATA data;
1476 GetFileAttributesEx(app_path.value().c_str(),
1477 GetFileExInfoStandard, &data);
1478 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1479 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1480 FILE_ATTRIBUTE_NORMAL, NULL);
1481 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361482 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551483 DWORD read_size;
1484 BOOL result;
1485 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1486 &read_size, NULL);
1487 std::string content(buffer.get(), read_size);
1488 CloseHandle(file);
1489
[email protected]f7022f32014-08-21 16:32:191490 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551491 EXPECT_EQ(1, d.received_redirect_count());
1492 EXPECT_EQ(content, d.data_received());
1493 }
1494
1495 // Clean the shortcut
1496 DeleteFile(lnk_path.c_str());
1497}
1498#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441499
1500// Custom URLRequestJobs for use with interceptor tests
1501class RestartTestJob : public URLRequestTestJob {
1502 public:
1503 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1504 : URLRequestTestJob(request, network_delegate, true) {}
1505 protected:
dchengb03027d2014-10-21 12:00:201506 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441507 private:
Chris Watkins7a41d3552017-12-01 02:13:271508 ~RestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441509};
1510
1511class CancelTestJob : public URLRequestTestJob {
1512 public:
1513 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1514 : URLRequestTestJob(request, network_delegate, true) {}
1515 protected:
dchengb03027d2014-10-21 12:00:201516 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441517 private:
Chris Watkins7a41d3552017-12-01 02:13:271518 ~CancelTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441519};
1520
1521class CancelThenRestartTestJob : public URLRequestTestJob {
1522 public:
1523 explicit CancelThenRestartTestJob(URLRequest* request,
1524 NetworkDelegate* network_delegate)
1525 : URLRequestTestJob(request, network_delegate, true) {
1526 }
1527 protected:
dchengb03027d2014-10-21 12:00:201528 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441529 request_->Cancel();
1530 this->NotifyRestartRequired();
1531 }
1532 private:
Chris Watkins7a41d3552017-12-01 02:13:271533 ~CancelThenRestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441534};
1535
bengr1bf8e942014-11-07 01:36:501536// An Interceptor for use with interceptor tests.
1537class MockURLRequestInterceptor : public URLRequestInterceptor {
1538 public:
1539 // Static getters for canned response header and data strings.
1540 static std::string ok_data() {
1541 return URLRequestTestJob::test_data_1();
1542 }
1543
1544 static std::string ok_headers() {
1545 return URLRequestTestJob::test_headers();
1546 }
1547
1548 static std::string redirect_data() {
1549 return std::string();
1550 }
1551
1552 static std::string redirect_headers() {
1553 return URLRequestTestJob::test_redirect_headers();
1554 }
1555
1556 static std::string error_data() {
1557 return std::string("ohhh nooooo mr. bill!");
1558 }
1559
1560 static std::string error_headers() {
1561 return URLRequestTestJob::test_error_headers();
1562 }
1563
1564 MockURLRequestInterceptor()
1565 : intercept_main_request_(false), restart_main_request_(false),
1566 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1567 simulate_main_network_error_(false),
1568 intercept_redirect_(false), cancel_redirect_request_(false),
1569 intercept_final_response_(false), cancel_final_request_(false),
1570 use_url_request_http_job_(false),
1571 did_intercept_main_(false), did_restart_main_(false),
1572 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1573 did_simulate_error_main_(false),
1574 did_intercept_redirect_(false), did_cancel_redirect_(false),
1575 did_intercept_final_(false), did_cancel_final_(false) {
1576 }
1577
Chris Watkins7a41d3552017-12-01 02:13:271578 ~MockURLRequestInterceptor() override = default;
bengr1bf8e942014-11-07 01:36:501579
1580 // URLRequestInterceptor implementation:
1581 URLRequestJob* MaybeInterceptRequest(
1582 URLRequest* request,
1583 NetworkDelegate* network_delegate) const override {
1584 if (restart_main_request_) {
1585 restart_main_request_ = false;
1586 did_restart_main_ = true;
1587 return new RestartTestJob(request, network_delegate);
1588 }
1589 if (cancel_main_request_) {
1590 cancel_main_request_ = false;
1591 did_cancel_main_ = true;
1592 return new CancelTestJob(request, network_delegate);
1593 }
1594 if (cancel_then_restart_main_request_) {
1595 cancel_then_restart_main_request_ = false;
1596 did_cancel_then_restart_main_ = true;
1597 return new CancelThenRestartTestJob(request, network_delegate);
1598 }
1599 if (simulate_main_network_error_) {
1600 simulate_main_network_error_ = false;
1601 did_simulate_error_main_ = true;
1602 if (use_url_request_http_job_) {
1603 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1604 }
1605 // This job will result in error since the requested URL is not one of the
1606 // URLs supported by these tests.
1607 return new URLRequestTestJob(request, network_delegate, true);
1608 }
1609 if (!intercept_main_request_)
1610 return nullptr;
1611 intercept_main_request_ = false;
1612 did_intercept_main_ = true;
1613 URLRequestTestJob* job = new URLRequestTestJob(request,
1614 network_delegate,
1615 main_headers_,
1616 main_data_,
1617 true);
1618 job->set_load_timing_info(main_request_load_timing_info_);
1619 return job;
1620 }
1621
1622 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1623 NetworkDelegate* network_delegate,
1624 const GURL& location) const override {
1625 if (cancel_redirect_request_) {
1626 cancel_redirect_request_ = false;
1627 did_cancel_redirect_ = true;
1628 return new CancelTestJob(request, network_delegate);
1629 }
1630 if (!intercept_redirect_)
1631 return nullptr;
1632 intercept_redirect_ = false;
1633 did_intercept_redirect_ = true;
1634 if (use_url_request_http_job_) {
1635 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1636 }
1637 return new URLRequestTestJob(request,
1638 network_delegate,
1639 redirect_headers_,
1640 redirect_data_,
1641 true);
1642 }
1643
1644 URLRequestJob* MaybeInterceptResponse(
1645 URLRequest* request,
1646 NetworkDelegate* network_delegate) const override {
1647 if (cancel_final_request_) {
1648 cancel_final_request_ = false;
1649 did_cancel_final_ = true;
1650 return new CancelTestJob(request, network_delegate);
1651 }
1652 if (!intercept_final_response_)
1653 return nullptr;
1654 intercept_final_response_ = false;
1655 did_intercept_final_ = true;
1656 if (use_url_request_http_job_) {
1657 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1658 }
1659 return new URLRequestTestJob(request,
1660 network_delegate,
1661 final_headers_,
1662 final_data_,
1663 true);
1664 }
1665
1666 void set_intercept_main_request(bool intercept_main_request) {
1667 intercept_main_request_ = intercept_main_request;
1668 }
1669
1670 void set_main_headers(const std::string& main_headers) {
1671 main_headers_ = main_headers;
1672 }
1673
1674 void set_main_data(const std::string& main_data) {
1675 main_data_ = main_data;
1676 }
1677
1678 void set_main_request_load_timing_info(
1679 const LoadTimingInfo& main_request_load_timing_info) {
1680 main_request_load_timing_info_ = main_request_load_timing_info;
1681 }
1682
1683 void set_restart_main_request(bool restart_main_request) {
1684 restart_main_request_ = restart_main_request;
1685 }
1686
1687 void set_cancel_main_request(bool cancel_main_request) {
1688 cancel_main_request_ = cancel_main_request;
1689 }
1690
1691 void set_cancel_then_restart_main_request(
1692 bool cancel_then_restart_main_request) {
1693 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1694 }
1695
1696 void set_simulate_main_network_error(bool simulate_main_network_error) {
1697 simulate_main_network_error_ = simulate_main_network_error;
1698 }
1699
1700 void set_intercept_redirect(bool intercept_redirect) {
1701 intercept_redirect_ = intercept_redirect;
1702 }
1703
1704 void set_redirect_headers(const std::string& redirect_headers) {
1705 redirect_headers_ = redirect_headers;
1706 }
1707
1708 void set_redirect_data(const std::string& redirect_data) {
1709 redirect_data_ = redirect_data;
1710 }
1711
1712 void set_cancel_redirect_request(bool cancel_redirect_request) {
1713 cancel_redirect_request_ = cancel_redirect_request;
1714 }
1715
1716 void set_intercept_final_response(bool intercept_final_response) {
1717 intercept_final_response_ = intercept_final_response;
1718 }
1719
1720 void set_final_headers(const std::string& final_headers) {
1721 final_headers_ = final_headers;
1722 }
1723
1724 void set_final_data(const std::string& final_data) {
1725 final_data_ = final_data;
1726 }
1727
1728 void set_cancel_final_request(bool cancel_final_request) {
1729 cancel_final_request_ = cancel_final_request;
1730 }
1731
1732 void set_use_url_request_http_job(bool use_url_request_http_job) {
1733 use_url_request_http_job_ = use_url_request_http_job;
1734 }
1735
1736 bool did_intercept_main() const {
1737 return did_intercept_main_;
1738 }
1739
1740 bool did_restart_main() const {
1741 return did_restart_main_;
1742 }
1743
1744 bool did_cancel_main() const {
1745 return did_cancel_main_;
1746 }
1747
1748 bool did_cancel_then_restart_main() const {
1749 return did_cancel_then_restart_main_;
1750 }
1751
1752 bool did_simulate_error_main() const {
1753 return did_simulate_error_main_;
1754 }
1755
1756 bool did_intercept_redirect() const {
1757 return did_intercept_redirect_;
1758 }
1759
1760 bool did_cancel_redirect() const {
1761 return did_cancel_redirect_;
1762 }
1763
1764 bool did_intercept_final() const {
1765 return did_intercept_final_;
1766 }
1767
1768 bool did_cancel_final() const {
1769 return did_cancel_final_;
1770 }
1771
1772 private:
1773 // Indicate whether to intercept the main request, and if so specify the
1774 // response to return and the LoadTimingInfo to use.
1775 mutable bool intercept_main_request_;
1776 mutable std::string main_headers_;
1777 mutable std::string main_data_;
1778 mutable LoadTimingInfo main_request_load_timing_info_;
1779
1780 // These indicate actions that can be taken within MaybeInterceptRequest.
1781 mutable bool restart_main_request_;
1782 mutable bool cancel_main_request_;
1783 mutable bool cancel_then_restart_main_request_;
1784 mutable bool simulate_main_network_error_;
1785
1786 // Indicate whether to intercept redirects, and if so specify the response to
1787 // return.
1788 mutable bool intercept_redirect_;
1789 mutable std::string redirect_headers_;
1790 mutable std::string redirect_data_;
1791
1792 // Cancel the request within MaybeInterceptRedirect.
1793 mutable bool cancel_redirect_request_;
1794
1795 // Indicate whether to intercept the final response, and if so specify the
1796 // response to return.
1797 mutable bool intercept_final_response_;
1798 mutable std::string final_headers_;
1799 mutable std::string final_data_;
1800
1801 // Cancel the final request within MaybeInterceptResponse.
1802 mutable bool cancel_final_request_;
1803
1804 // Instruct the interceptor to use a real URLRequestHTTPJob.
1805 mutable bool use_url_request_http_job_;
1806
1807 // These indicate if the interceptor did something or not.
1808 mutable bool did_intercept_main_;
1809 mutable bool did_restart_main_;
1810 mutable bool did_cancel_main_;
1811 mutable bool did_cancel_then_restart_main_;
1812 mutable bool did_simulate_error_main_;
1813 mutable bool did_intercept_redirect_;
1814 mutable bool did_cancel_redirect_;
1815 mutable bool did_intercept_final_;
1816 mutable bool did_cancel_final_;
1817};
1818
1819// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1820class URLRequestInterceptorTest : public URLRequestTest {
1821 public:
1822 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1823 }
1824
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);
2136 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2137 return load_timing;
2138}
2139
2140// Same as above, but in the case of a reused socket.
2141LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2142 bool used_proxy) {
2143 LoadTimingInfo load_timing;
2144 load_timing.socket_log_id = 1;
2145 load_timing.socket_reused = true;
2146
2147 if (used_proxy) {
2148 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2149 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2150 }
2151
2152 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2153 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2154 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2155 return load_timing;
2156}
2157
bengr1bf8e942014-11-07 01:36:502158LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2159 const LoadTimingInfo& job_load_timing,
2160 const URLRequestContext& context,
2161 MockURLRequestInterceptor* interceptor) {
2162 interceptor->set_intercept_main_request(true);
2163 interceptor->set_main_request_load_timing_info(job_load_timing);
2164 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162165 std::unique_ptr<URLRequest> req(
2166 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2167 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502168 req->Start();
Wez2a31b222018-06-07 22:07:152169 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502170
2171 LoadTimingInfo resulting_load_timing;
2172 req->GetLoadTimingInfo(&resulting_load_timing);
2173
2174 // None of these should be modified by the URLRequest.
2175 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2176 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2177 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2178 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
2179 EXPECT_EQ(job_load_timing.receive_headers_end,
2180 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572181 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2182 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502183
2184 return resulting_load_timing;
2185}
2186
[email protected]2bba3252013-04-08 19:50:592187// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502188TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592189 base::TimeTicks now = base::TimeTicks::Now();
2190 LoadTimingInfo job_load_timing =
2191 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2192
[email protected]2ca01e52013-10-31 22:05:192193 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502194 RunURLRequestInterceptorLoadTimingTest(
2195 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592196
2197 // Nothing should have been changed by the URLRequest.
2198 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2199 load_timing_result.proxy_resolve_start);
2200 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2201 load_timing_result.proxy_resolve_end);
2202 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2203 load_timing_result.connect_timing.dns_start);
2204 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2205 load_timing_result.connect_timing.dns_end);
2206 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2207 load_timing_result.connect_timing.connect_start);
2208 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2209 load_timing_result.connect_timing.connect_end);
2210 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2211 load_timing_result.connect_timing.ssl_start);
2212 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2213 load_timing_result.connect_timing.ssl_end);
2214
2215 // Redundant sanity check.
2216 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2217}
2218
2219// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502220TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592221 base::TimeTicks now = base::TimeTicks::Now();
2222 LoadTimingInfo job_load_timing =
2223 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2224
[email protected]2ca01e52013-10-31 22:05:192225 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502226 RunURLRequestInterceptorLoadTimingTest(
2227 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592228
2229 // Nothing should have been changed by the URLRequest.
2230 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2231 load_timing_result.proxy_resolve_start);
2232 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2233 load_timing_result.proxy_resolve_end);
2234 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2235 load_timing_result.connect_timing.dns_start);
2236 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2237 load_timing_result.connect_timing.dns_end);
2238 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2239 load_timing_result.connect_timing.connect_start);
2240 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2241 load_timing_result.connect_timing.connect_end);
2242 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2243 load_timing_result.connect_timing.ssl_start);
2244 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2245 load_timing_result.connect_timing.ssl_end);
2246
2247 // Redundant sanity check.
2248 TestLoadTimingNotReusedWithProxy(load_timing_result,
2249 CONNECT_TIMING_HAS_SSL_TIMES);
2250}
2251
2252// Make sure that URLRequest correctly adjusts proxy times when they're before
2253// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102254// the case of reusing a SPDY session. The connected socket is not considered
2255// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592256//
2257// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502258TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592259 base::TimeTicks now = base::TimeTicks::Now();
2260 LoadTimingInfo job_load_timing =
2261 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2262 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2263 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2264 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2265 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2266 job_load_timing.connect_timing.connect_start =
2267 now - base::TimeDelta::FromDays(2);
2268 job_load_timing.connect_timing.connect_end =
2269 now - base::TimeDelta::FromDays(1);
2270
[email protected]2ca01e52013-10-31 22:05:192271 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502272 RunURLRequestInterceptorLoadTimingTest(
2273 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592274
2275 // Proxy times, connect times, and DNS times should all be replaced with
2276 // request_start.
2277 EXPECT_EQ(load_timing_result.request_start,
2278 load_timing_result.proxy_resolve_start);
2279 EXPECT_EQ(load_timing_result.request_start,
2280 load_timing_result.proxy_resolve_end);
2281 EXPECT_EQ(load_timing_result.request_start,
2282 load_timing_result.connect_timing.dns_start);
2283 EXPECT_EQ(load_timing_result.request_start,
2284 load_timing_result.connect_timing.dns_end);
2285 EXPECT_EQ(load_timing_result.request_start,
2286 load_timing_result.connect_timing.connect_start);
2287 EXPECT_EQ(load_timing_result.request_start,
2288 load_timing_result.connect_timing.connect_end);
2289
2290 // Other times should have been left null.
2291 TestLoadTimingNotReusedWithProxy(load_timing_result,
2292 CONNECT_TIMING_HAS_DNS_TIMES);
2293}
2294
2295// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502296TEST_F(URLRequestInterceptorTest,
2297 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592298 base::TimeTicks now = base::TimeTicks::Now();
2299 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2300 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2301 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2302
[email protected]2ca01e52013-10-31 22:05:192303 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502304 RunURLRequestInterceptorLoadTimingTest(
2305 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592306
2307 // Proxy times and connect times should all be replaced with request_start.
2308 EXPECT_EQ(load_timing_result.request_start,
2309 load_timing_result.proxy_resolve_start);
2310 EXPECT_EQ(load_timing_result.request_start,
2311 load_timing_result.proxy_resolve_end);
2312
2313 // Other times should have been left null.
2314 TestLoadTimingReusedWithProxy(load_timing_result);
2315}
2316
2317// Make sure that URLRequest correctly adjusts connect times when they're before
2318// |request_start|, due to reusing a connected socket. The connected socket is
2319// not considered reused in this test (May be a preconnect).
2320//
2321// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502322TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592323 base::TimeTicks now = base::TimeTicks::Now();
2324 LoadTimingInfo job_load_timing =
2325 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2326 job_load_timing.connect_timing.connect_start =
2327 now - base::TimeDelta::FromDays(1);
2328 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2329 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2330 job_load_timing.connect_timing.connect_end =
2331 now - base::TimeDelta::FromDays(4);
2332
[email protected]2ca01e52013-10-31 22:05:192333 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502334 RunURLRequestInterceptorLoadTimingTest(
2335 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592336
2337 // Connect times, and SSL times should be replaced with request_start.
2338 EXPECT_EQ(load_timing_result.request_start,
2339 load_timing_result.connect_timing.connect_start);
2340 EXPECT_EQ(load_timing_result.request_start,
2341 load_timing_result.connect_timing.ssl_start);
2342 EXPECT_EQ(load_timing_result.request_start,
2343 load_timing_result.connect_timing.ssl_end);
2344 EXPECT_EQ(load_timing_result.request_start,
2345 load_timing_result.connect_timing.connect_end);
2346
2347 // Other times should have been left null.
2348 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2349}
2350
2351// Make sure that URLRequest correctly adjusts connect times when they're before
2352// |request_start|, due to reusing a connected socket in the case that there
2353// are also proxy times. The connected socket is not considered reused in this
2354// test (May be a preconnect).
2355//
2356// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502357TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592358 base::TimeTicks now = base::TimeTicks::Now();
2359 LoadTimingInfo job_load_timing =
2360 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2361 job_load_timing.connect_timing.connect_start =
2362 now - base::TimeDelta::FromDays(1);
2363 job_load_timing.connect_timing.connect_end =
2364 now - base::TimeDelta::FromDays(2);
2365
[email protected]2ca01e52013-10-31 22:05:192366 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502367 RunURLRequestInterceptorLoadTimingTest(
2368 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592369
2370 // Connect times should be replaced with proxy_resolve_end.
2371 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2372 load_timing_result.connect_timing.connect_start);
2373 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2374 load_timing_result.connect_timing.connect_end);
2375
2376 // Other times should have been left null.
2377 TestLoadTimingNotReusedWithProxy(load_timing_result,
2378 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2379}
2380
[email protected]316c1e5e2012-09-12 15:17:442381// Check that two different URL requests have different identifiers.
2382TEST_F(URLRequestTest, Identifiers) {
2383 TestDelegate d;
2384 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362385 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162386 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2387 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362388 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162389 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2390 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442391
mmenke19378d22014-09-09 04:12:592392 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442393}
2394
blundellb8163592f2015-12-16 14:22:422395#if defined(OS_IOS)
2396// TODO(droger): Check that a failure to connect to the proxy is reported to
2397// the network delegate. crbug.com/496743
2398#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2399#else
2400#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2401#endif
2402TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442403 MockHostResolver host_resolver;
2404 host_resolver.rules()->AddSimulatedFailure("*");
2405
[email protected]ceefd7fd2012-11-29 00:36:242406 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442407 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2408
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.
[email protected]d8fc4722014-06-13 13:17:152419 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472420 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502421 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442422
2423 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012424 EXPECT_THAT(network_delegate.last_error(),
2425 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442426 EXPECT_EQ(1, network_delegate.completed_requests());
2427}
2428
[email protected]cba24642014-08-15 20:49:592429// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442430// content is empty.
2431TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2432 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072433 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162434 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192435 req->Start();
Wez2a31b222018-06-07 22:07:152436 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442437 EXPECT_EQ("", d.data_received());
2438 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2439}
2440
[email protected]5033ab82013-03-22 20:17:462441// Make sure that SetPriority actually sets the URLRequest's priority
2442// correctly, both before and after start.
2443TEST_F(URLRequestTest, SetPriorityBasic) {
2444 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072445 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162446 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2447 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192448 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462449
[email protected]f7022f32014-08-21 16:32:192450 req->SetPriority(LOW);
2451 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462452
[email protected]f7022f32014-08-21 16:32:192453 req->Start();
2454 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462455
[email protected]f7022f32014-08-21 16:32:192456 req->SetPriority(MEDIUM);
2457 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462458}
2459
2460// Make sure that URLRequest calls SetPriority on a job before calling
2461// Start on it.
2462TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2463 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072464 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162465 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2466 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192467 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462468
mmenkeed0498b2015-12-08 23:20:422469 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362470 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422471 req.get(), &default_network_delegate_, &job_priority));
2472 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2473 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462474
[email protected]f7022f32014-08-21 16:32:192475 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462476
[email protected]f7022f32014-08-21 16:32:192477 req->Start();
mmenkeed0498b2015-12-08 23:20:422478 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462479}
2480
2481// Make sure that URLRequest passes on its priority updates to its
2482// job.
2483TEST_F(URLRequestTest, SetJobPriority) {
2484 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072485 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162486 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2487 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462488
mmenkeed0498b2015-12-08 23:20:422489 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362490 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422491 req.get(), &default_network_delegate_, &job_priority));
2492 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462493
[email protected]f7022f32014-08-21 16:32:192494 req->SetPriority(LOW);
2495 req->Start();
mmenkeed0498b2015-12-08 23:20:422496 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462497
[email protected]f7022f32014-08-21 16:32:192498 req->SetPriority(MEDIUM);
2499 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422500 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462501}
2502
[email protected]bb1c4662013-11-14 00:00:072503// Setting the IGNORE_LIMITS load flag should be okay if the priority
2504// is MAXIMUM_PRIORITY.
2505TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2506 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072507 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162508 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2509 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192510 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072511
mmenkeed0498b2015-12-08 23:20:422512 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362513 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422514 req.get(), &default_network_delegate_, &job_priority));
2515 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072516
[email protected]f7022f32014-08-21 16:32:192517 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2518 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072519
[email protected]f7022f32014-08-21 16:32:192520 req->SetPriority(MAXIMUM_PRIORITY);
2521 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072522
[email protected]f7022f32014-08-21 16:32:192523 req->Start();
2524 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422525 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072526}
2527
nick5d570de92015-05-04 20:16:162528namespace {
2529
2530// Less verbose way of running a simple testserver for the tests below.
David Benjamin42116f62017-11-20 21:45:392531class HttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442532 public:
David Benjamin42116f62017-11-20 21:45:392533 explicit HttpTestServer(const base::FilePath& document_root) {
tommycli59a63432015-11-06 00:10:552534 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272535 }
tommycli59a63432015-11-06 00:10:552536
David Benjamin42116f62017-11-20 21:45:392537 HttpTestServer() { AddDefaultHandlers(base::FilePath()); }
tommycli59a63432015-11-06 00:10:552538};
tommyclieae5f75f2015-11-05 19:07:272539
nick5d570de92015-05-04 20:16:162540} // namespace
2541
[email protected]f2f31b32013-01-16 23:24:092542TEST_F(URLRequestTest, DelayedCookieCallback) {
David Benjamin42116f62017-11-20 21:45:392543 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442544 ASSERT_TRUE(test_server.Start());
2545
2546 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362547 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502548 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442549
2550 // Set up a cookie.
2551 {
2552 TestNetworkDelegate network_delegate;
2553 context.set_network_delegate(&network_delegate);
2554 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362555 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552556 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162557 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192558 req->Start();
Wez2a31b222018-06-07 22:07:152559 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442560 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2561 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2562 EXPECT_EQ(1, network_delegate.set_cookie_count());
2563 }
2564
2565 // Verify that the cookie is set.
2566 {
2567 TestNetworkDelegate network_delegate;
2568 context.set_network_delegate(&network_delegate);
2569 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362570 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162571 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2572 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192573 req->Start();
Wez2a31b222018-06-07 22:07:152574 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442575
2576 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2577 != std::string::npos);
2578 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2579 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2580 }
2581}
2582
[email protected]f2f31b32013-01-16 23:24:092583TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392584 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442585 ASSERT_TRUE(test_server.Start());
2586
2587 // Set up a cookie.
2588 {
2589 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072590 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442591 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072592 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552593 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162594 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192595 req->Start();
Wez2a31b222018-06-07 22:07:152596 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442597 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2598 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2599 }
2600
2601 // Verify that the cookie is set.
2602 {
2603 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072604 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442605 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072606 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162607 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2608 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192609 req->Start();
Wez2a31b222018-06-07 22:07:152610 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442611
2612 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2613 != std::string::npos);
2614 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2615 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2616 }
2617
2618 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2619 {
2620 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072621 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442622 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072623 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162624 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2625 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192626 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2627 req->Start();
Wez2a31b222018-06-07 22:07:152628 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442629
2630 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2631 == std::string::npos);
2632
2633 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2634 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2635 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2636 }
2637}
2638
2639TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392640 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442641 ASSERT_TRUE(test_server.Start());
2642
2643 // Set up a cookie.
2644 {
2645 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072646 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442647 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072648 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552649 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162650 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192651 req->Start();
Wez2a31b222018-06-07 22:07:152652 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442653
2654 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2655 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2656 EXPECT_EQ(1, network_delegate.set_cookie_count());
2657 }
2658
2659 // Try to set-up another cookie and update the previous cookie.
2660 {
2661 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072662 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442663 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072664 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552665 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162666 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192667 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2668 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442669
Wez2a31b222018-06-07 22:07:152670 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442671
2672 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2673 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2674 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2675 EXPECT_EQ(0, network_delegate.set_cookie_count());
2676 }
2677
2678 // Verify the cookies weren't saved or updated.
2679 {
2680 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072681 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442682 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072683 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162684 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2685 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192686 req->Start();
Wez2a31b222018-06-07 22:07:152687 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442688
2689 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2690 == std::string::npos);
2691 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2692 != std::string::npos);
2693
2694 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2695 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2696 EXPECT_EQ(0, network_delegate.set_cookie_count());
2697 }
2698}
2699
2700TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392701 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442702 ASSERT_TRUE(test_server.Start());
2703
2704 // Set up a cookie.
2705 {
2706 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072707 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442708 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072709 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552710 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162711 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192712 req->Start();
Wez2a31b222018-06-07 22:07:152713 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442714
2715 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2716 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2717 }
2718
2719 // Verify that the cookie is set.
2720 {
2721 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072722 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442723 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072724 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162725 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2726 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192727 req->Start();
Wez2a31b222018-06-07 22:07:152728 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442729
2730 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2731 != std::string::npos);
2732
2733 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2734 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182735 TestNetLogEntry::List entries;
2736 net_log_.GetEntries(&entries);
2737 for (const auto& entry : entries) {
2738 EXPECT_NE(entry.type,
2739 NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE);
2740 }
[email protected]316c1e5e2012-09-12 15:17:442741 }
2742
2743 // Verify that the cookie isn't sent.
2744 {
2745 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072746 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442747 TestDelegate d;
2748 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
Ryan Sleevib8449e02018-07-15 04:31:072749 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162750 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2751 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192752 req->Start();
Wez2a31b222018-06-07 22:07:152753 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442754
2755 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2756 == std::string::npos);
2757
[email protected]22e045f2013-09-20 03:54:032758 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442759 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182760 TestNetLogEntry::List entries;
2761 net_log_.GetEntries(&entries);
2762 ExpectLogContainsSomewhereAfter(
2763 entries, 0, NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE,
2764 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442765 }
2766}
2767
marqf14fff8d2015-12-02 15:52:292768// TODO(crbug.com/564656) This test is flaky on iOS.
2769#if defined(OS_IOS)
2770#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2771#else
2772#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2773#endif
[email protected]316c1e5e2012-09-12 15:17:442774TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392775 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442776 ASSERT_TRUE(test_server.Start());
2777
2778 // Set up a cookie.
2779 {
2780 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072781 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442782 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072783 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552784 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162785 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192786 req->Start();
Wez2a31b222018-06-07 22:07:152787 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442788
2789 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2790 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182791 TestNetLogEntry::List entries;
2792 net_log_.GetEntries(&entries);
2793 for (const auto& entry : entries) {
2794 EXPECT_NE(entry.type,
2795 NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE);
2796 }
[email protected]316c1e5e2012-09-12 15:17:442797 }
2798
2799 // Try to set-up another cookie and update the previous cookie.
2800 {
2801 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072802 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442803 TestDelegate d;
2804 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:072805 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552806 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162807 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192808 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442809
Wez2a31b222018-06-07 22:07:152810 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442811
2812 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2813 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
Helen Li830d5708d62018-08-22 16:29:182814 TestNetLogEntry::List entries;
2815 net_log_.GetEntries(&entries);
2816 ExpectLogContainsSomewhereAfter(
2817 entries, 0, NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE,
2818 NetLogEventPhase::NONE);
[email protected]316c1e5e2012-09-12 15:17:442819 }
2820
2821 // Verify the cookies weren't saved or updated.
2822 {
2823 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072824 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442825 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072826 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162827 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2828 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192829 req->Start();
Wez2a31b222018-06-07 22:07:152830 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442831
2832 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2833 == std::string::npos);
2834 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2835 != std::string::npos);
2836
2837 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2838 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2839 }
2840}
2841
2842TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:392843 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442844 ASSERT_TRUE(test_server.Start());
2845
2846 // Set up an empty cookie.
2847 {
2848 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072849 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442850 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072851 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162852 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
2853 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192854 req->Start();
Wez2a31b222018-06-07 22:07:152855 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442856
2857 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2858 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2859 EXPECT_EQ(0, network_delegate.set_cookie_count());
2860 }
2861}
2862
2863TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:392864 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442865 ASSERT_TRUE(test_server.Start());
2866
2867 // Set up a cookie.
2868 {
2869 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072870 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442871 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072872 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552873 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162874 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192875 req->Start();
Wez2a31b222018-06-07 22:07:152876 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442877
2878 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2879 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2880 }
2881
2882 // Verify that the cookie is set.
2883 {
2884 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072885 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442886 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072887 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162888 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2889 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192890 req->Start();
Wez2a31b222018-06-07 22:07:152891 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442892
2893 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2894 != std::string::npos);
2895
2896 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2897 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2898 }
2899
2900 // Verify that the cookie isn't sent.
2901 {
2902 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072903 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442904 TestDelegate d;
2905 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
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("Cookie: CookieToNotSend=1")
2913 == std::string::npos);
2914
[email protected]22e045f2013-09-20 03:54:032915 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442916 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2917 }
2918}
2919
2920TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:392921 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442922 ASSERT_TRUE(test_server.Start());
2923
2924 // Set up a cookie.
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;
Ryan Sleevib8449e02018-07-15 04:31:072929 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552930 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162931 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192932 req->Start();
Wez2a31b222018-06-07 22:07:152933 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442934
2935 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2936 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2937 }
2938
2939 // Try to set-up another cookie and update the previous cookie.
2940 {
2941 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072942 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442943 TestDelegate d;
2944 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
Ryan Sleevib8449e02018-07-15 04:31:072945 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:552946 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162947 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192948 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442949
Wez2a31b222018-06-07 22:07:152950 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442951
2952 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2953 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2954 }
2955
2956 // Verify the cookies weren't saved or updated.
2957 {
2958 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072959 default_context().set_network_delegate(&network_delegate);
[email protected]316c1e5e2012-09-12 15:17:442960 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072961 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162962 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2963 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192964 req->Start();
Wez2a31b222018-06-07 22:07:152965 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442966
2967 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2968 == std::string::npos);
2969 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2970 != std::string::npos);
2971
2972 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2973 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2974 }
2975}
2976
mkwstc5fa7762016-03-28 09:28:232977TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:392978 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:262979 ASSERT_TRUE(test_server.Start());
2980
mkwst202534e32016-01-15 16:07:152981 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:072982 default_context().set_network_delegate(&network_delegate);
mkwst202534e32016-01-15 16:07:152983
mkwstf71d0bd2016-03-21 14:15:242984 const std::string kHost = "example.test";
2985 const std::string kSubHost = "subdomain.example.test";
2986 const std::string kCrossHost = "cross-origin.test";
2987
2988 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262989 {
mkwst3f3daac2015-02-26 20:15:262990 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:072991 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242992 test_server.GetURL(kHost,
2993 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2994 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:162995 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst3f3daac2015-02-26 20:15:262996 req->Start();
Wez2a31b222018-06-07 22:07:152997 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:262998 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2999 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:243000 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:263001 }
3002
mkwstf71d0bd2016-03-21 14:15:243003 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:263004 {
mkwst3f3daac2015-02-26 20:15:263005 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073006 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163007 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3008 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463009 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463010 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:263011 req->Start();
Wez2a31b222018-06-07 22:07:153012 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263013
mkwstf71d0bd2016-03-21 14:15:243014 EXPECT_NE(std::string::npos,
3015 d.data_received().find("StrictSameSiteCookie=1"));
3016 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263017 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3018 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3019 }
3020
clamyfd58ca072016-12-21 17:18:323021 // Verify that both cookies are sent when the request has no initiator (can
3022 // happen for main frame browser-initiated navigations).
3023 {
3024 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073025 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163026 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3027 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463028 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:323029 req->Start();
Wez2a31b222018-06-07 22:07:153030 d.RunUntilComplete();
clamyfd58ca072016-12-21 17:18:323031
3032 EXPECT_NE(std::string::npos,
3033 d.data_received().find("StrictSameSiteCookie=1"));
3034 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3035 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3036 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3037 }
3038
mkwstf71d0bd2016-03-21 14:15:243039 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263040 {
mkwst3f3daac2015-02-26 20:15:263041 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073042 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163043 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3044 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463045 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463046 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153047 req->Start();
Wez2a31b222018-06-07 22:07:153048 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153049
mkwstf71d0bd2016-03-21 14:15:243050 EXPECT_NE(std::string::npos,
3051 d.data_received().find("StrictSameSiteCookie=1"));
3052 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153053 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3054 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3055 }
3056
mkwstf71d0bd2016-03-21 14:15:243057 // Verify that neither cookie is not sent for cross-site requests.
3058 {
3059 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073060 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163061 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3062 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463063 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463064 req->set_initiator(
3065 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243066 req->Start();
Wez2a31b222018-06-07 22:07:153067 d.RunUntilComplete();
mkwstf71d0bd2016-03-21 14:15:243068
3069 EXPECT_EQ(std::string::npos,
3070 d.data_received().find("StrictSameSiteCookie=1"));
3071 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3072 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3073 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3074 }
3075
3076 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153077 // method is "safe".
3078 {
3079 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073080 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163081 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3082 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463083 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463084 req->set_initiator(
3085 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243086 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153087 req->Start();
Wez2a31b222018-06-07 22:07:153088 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153089
mkwstf71d0bd2016-03-21 14:15:243090 EXPECT_EQ(std::string::npos,
3091 d.data_received().find("StrictSameSiteCookie=1"));
3092 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153093 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3094 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3095 }
3096
mkwstf71d0bd2016-03-21 14:15:243097 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153098 // method is unsafe (e.g. POST).
3099 {
3100 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073101 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163102 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3103 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463104 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463105 req->set_initiator(
3106 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153107 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263108 req->Start();
Wez2a31b222018-06-07 22:07:153109 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263110
mkwstf71d0bd2016-03-21 14:15:243111 EXPECT_EQ(std::string::npos,
3112 d.data_received().find("StrictSameSiteCookie=1"));
3113 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263114 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3115 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3116 }
3117}
3118
estark557a5eb82015-12-01 22:57:103119// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363120TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553121 EmbeddedTestServer http_server;
3122 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363123 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553124 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3125 https_server.AddDefaultHandlers(
3126 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3127 ASSERT_TRUE(http_server.Start());
3128 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363129
estarkb15166b2015-12-18 16:56:383130 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363131 TestURLRequestContext context(true);
3132 context.set_network_delegate(&network_delegate);
3133 context.Init();
3134
estarkb15166b2015-12-18 16:56:383135 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363136 {
3137 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363138 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103139 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163140 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363141 req->Start();
Wez2a31b222018-06-07 22:07:153142 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363143 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3144 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3145 }
3146
3147 // Verify that the cookie is not set.
3148 {
3149 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363150 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163151 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3152 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363153 req->Start();
Wez2a31b222018-06-07 22:07:153154 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363155
jww79aceda2015-12-07 01:56:343156 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3157 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363158 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3159 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3160 }
3161}
3162
estarkb15166b2015-12-18 16:56:383163TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553164 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3165 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363166 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553167 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363168
3169 TestNetworkDelegate network_delegate;
3170 TestURLRequestContext context(true);
3171 context.set_network_delegate(&network_delegate);
3172 context.Init();
3173
estarkb15166b2015-12-18 16:56:383174 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363175 {
3176 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163177 std::unique_ptr<URLRequest> req(context.CreateRequest(
3178 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3179 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363180 req->Start();
Wez2a31b222018-06-07 22:07:153181 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583182 EXPECT_EQ(0, network_delegate.set_cookie_count());
estarkcd39c11f2015-10-19 19:46:363183 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3184 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3185 }
3186
3187 // Verify that the cookie is not set.
3188 {
3189 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363190 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163191 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3192 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363193 req->Start();
Wez2a31b222018-06-07 22:07:153194 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363195
jww79aceda2015-12-07 01:56:343196 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363197 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3198 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3199 }
3200}
3201
estarkb15166b2015-12-18 16:56:383202TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553203 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3204 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363205 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553206 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363207
estarkb15166b2015-12-18 16:56:383208 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363209 TestURLRequestContext context(true);
3210 context.set_network_delegate(&network_delegate);
3211 context.Init();
3212
estarkb15166b2015-12-18 16:56:383213 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363214 {
3215 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363216 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103217 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163218 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363219 req->Start();
Wez2a31b222018-06-07 22:07:153220 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363221 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3222 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3223 }
3224
3225 // Verify that the cookie is set.
3226 {
3227 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363228 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163229 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3230 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363231 req->Start();
Wez2a31b222018-06-07 22:07:153232 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363233
jww79aceda2015-12-07 01:56:343234 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3235 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3236 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3237 }
3238}
3239
3240// Tests that secure cookies can't be set on non-secure origins if strict secure
3241// cookies are enabled.
3242TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3243 EmbeddedTestServer http_server;
3244 http_server.AddDefaultHandlers(
3245 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3246 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3247 https_server.AddDefaultHandlers(
3248 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3249 ASSERT_TRUE(http_server.Start());
3250 ASSERT_TRUE(https_server.Start());
3251
Matt Menkebe9b6eb2018-10-18 12:11:443252 TestNetworkDelegate network_delegate;
jww79aceda2015-12-07 01:56:343253 TestURLRequestContext context(true);
3254 context.set_network_delegate(&network_delegate);
3255 context.Init();
3256
3257 // Try to set a Secure cookie, with experimental features enabled.
3258 {
3259 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363260 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343261 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163262 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343263 req->Start();
Wez2a31b222018-06-07 22:07:153264 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343265 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3266 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3267 }
3268
3269 // Verify that the cookie is not set.
3270 {
3271 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363272 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163273 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3274 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343275 req->Start();
Wez2a31b222018-06-07 22:07:153276 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343277
3278 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3279 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3280 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3281 }
3282}
3283
Thiemo Nagel0793b9c532018-04-18 16:57:583284// The parameter is true for same-site and false for cross-site requests.
3285class URLRequestTestParameterizedSameSite
3286 : public URLRequestTest,
3287 public ::testing::WithParamInterface<bool> {
3288 protected:
3289 URLRequestTestParameterizedSameSite() {
3290 auto params = std::make_unique<HttpNetworkSession::Params>();
3291 params->ignore_certificate_errors = true;
3292 context_.set_http_network_session_params(std::move(params));
3293 context_.set_network_delegate(&network_delegate_);
3294 https_server_.AddDefaultHandlers(
3295 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3296 EXPECT_TRUE(https_server_.Start());
3297 }
3298
3299 // To be called after configuration of |context_| has been finalized.
3300 void InitContext() { context_.Init(); }
3301
3302 const std::string kHost_ = "example.test";
3303 const std::string kCrossHost_ = "cross-site.test";
3304 TestURLRequestContext context_{true};
3305 TestNetworkDelegate network_delegate_;
3306 base::HistogramTester histograms_;
3307 EmbeddedTestServer https_server_{EmbeddedTestServer::TYPE_HTTPS};
3308};
3309
3310INSTANTIATE_TEST_CASE_P(URLRequestTest,
3311 URLRequestTestParameterizedSameSite,
3312 ::testing::Bool());
3313
3314TEST_P(URLRequestTestParameterizedSameSite, CookieAgeMetrics) {
3315 const bool same_site = GetParam();
3316 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3317 InitContext();
3318
Mike West86149882017-07-28 10:41:493319 EmbeddedTestServer http_server;
3320 http_server.AddDefaultHandlers(
3321 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
Thiemo Nagel23e0b322018-04-18 12:46:543322 ASSERT_TRUE(http_server.Start());
3323
Thiemo Nagel0793b9c532018-04-18 16:57:583324 // Set two test cookies.
Thiemo Nagel23e0b322018-04-18 12:46:543325 {
3326 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583327 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3328 http_server.GetURL(kHost_, "/set-cookie?cookie=value&cookie2=value2"),
Thiemo Nagel23e0b322018-04-18 12:46:543329 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3330 req->Start();
Wez2a31b222018-06-07 22:07:153331 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583332 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3333 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3334 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3335 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3336 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 0);
3337 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3338 0);
3339 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3340 0);
3341 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3342 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 0);
Thiemo Nagel23e0b322018-04-18 12:46:543343 }
3344
Thiemo Nagel0793b9c532018-04-18 16:57:583345 // Make a secure request.
Thiemo Nagel23e0b322018-04-18 12:46:543346 {
3347 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583348 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3349 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3350 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3351 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103352 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583353 url::Origin::Create(https_server_.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103354 req->Start();
Wez2a31b222018-06-07 22:07:153355 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583356 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3357 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3358 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3359 !same_site);
3360 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3361 same_site);
3362 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3363 0);
3364 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3365 0);
3366 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3367 same_site ? 0 : 2);
3368 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3369 same_site ? 2 : 0);
3370 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3371 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
Mohsen Izadiad6f7592018-04-18 15:57:103372 }
3373
Thiemo Nagel0793b9c532018-04-18 16:57:583374 // Make a non-secure request.
Mohsen Izadiad6f7592018-04-18 15:57:103375 {
3376 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583377 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3378 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
Mohsen Izadiad6f7592018-04-18 15:57:103379 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel0793b9c532018-04-18 16:57:583380 req->set_site_for_cookies(http_server.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103381 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583382 url::Origin::Create(http_server.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103383 req->Start();
Wez2a31b222018-06-07 22:07:153384 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583385 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest",
3386 !same_site);
3387 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest",
3388 same_site);
3389 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3390 !same_site);
3391 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3392 same_site);
3393 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3394 same_site ? 0 : 2);
3395 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3396 same_site ? 2 : 0);
3397 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3398 same_site ? 0 : 2);
3399 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3400 same_site ? 2 : 0);
3401 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3402 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
3403 }
3404}
3405
3406// Cookies with secure attribute (no HSTS) --> k1pSecureAttribute
3407TEST_P(URLRequestTestParameterizedSameSite,
3408 CookieNetworkSecurityMetricSecureAttribute) {
3409 const bool same_site = GetParam();
3410 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3411 InitContext();
3412
3413 // Set cookies.
3414 {
3415 TestDelegate d;
3416 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3417 https_server_.GetURL(kHost_,
3418 "/set-cookie?session-cookie=value;Secure&"
3419 "longlived-cookie=value;Secure;domain=" +
3420 kHost_ + ";Max-Age=360000"),
3421 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3422 req->Start();
Wez2a31b222018-06-07 22:07:153423 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583424 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3425 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3426 }
3427
3428 // Verify that the cookies fall into the correct metrics bucket.
3429 {
3430 TestDelegate d;
3431 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3432 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3433 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3434 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3435 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3436 req->Start();
Wez2a31b222018-06-07 22:07:153437 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583438 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3439 // Static cast of boolean required for MSVC 1911.
3440 histograms_.ExpectBucketCount(
3441 "Cookie.NetworkSecurity",
3442 static_cast<int>(CookieNetworkSecurity::k1pSecureAttribute) |
3443 static_cast<int>(!same_site),
3444 2);
3445 }
3446}
3447
3448// Short-lived host cookie --> k1pHSTSHostCookie
3449TEST_P(URLRequestTestParameterizedSameSite,
3450 CookieNetworkSecurityMetricShortlivedHostCookie) {
3451 const bool same_site = GetParam();
3452 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3453
3454 TransportSecurityState transport_security_state;
3455 transport_security_state.AddHSTS(
3456 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3457 false /* include_subdomains */);
3458 context_.set_transport_security_state(&transport_security_state);
3459 InitContext();
3460
3461 // Set cookie.
3462 {
3463 TestDelegate d;
3464 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3465 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;Max-Age=3600"),
3466 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3467 req->Start();
Wez2a31b222018-06-07 22:07:153468 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583469 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3470 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3471 }
3472
3473 // Verify that the cookie falls into the correct metrics bucket.
3474 {
3475 TestDelegate d;
3476 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3477 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3478 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3479 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3480 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3481 req->Start();
Wez2a31b222018-06-07 22:07:153482 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583483 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3484 // Static cast of boolean required for MSVC 1911.
3485 histograms_.ExpectBucketCount(
3486 "Cookie.NetworkSecurity",
3487 static_cast<int>(CookieNetworkSecurity::k1pHSTSHostCookie) |
3488 static_cast<int>(!same_site),
3489 1);
3490 }
3491}
3492
3493// Long-lived (either due to expiry or due to being a session cookie) host
3494// cookies --> k1pExpiringHSTSHostCookie
3495TEST_P(URLRequestTestParameterizedSameSite,
3496 CookieNetworkSecurityMetricLonglivedHostCookie) {
3497 const bool same_site = GetParam();
3498 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3499
3500 TransportSecurityState transport_security_state;
3501 transport_security_state.AddHSTS(
3502 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3503 false /* include_subdomains */);
3504 context_.set_transport_security_state(&transport_security_state);
3505 InitContext();
3506
3507 // Set cookies.
3508 {
3509 TestDelegate d;
3510 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3511 https_server_.GetURL(kHost_,
3512 "/set-cookie?session-cookie=value&"
3513 "longlived-cookie=value;Max-Age=360000"),
3514 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3515 req->Start();
Wez2a31b222018-06-07 22:07:153516 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583517 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3518 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3519 }
3520
3521 // Verify that the cookies fall into the correct metrics bucket.
3522 {
3523 TestDelegate d;
3524 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3525 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3526 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3527 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3528 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3529 req->Start();
Wez2a31b222018-06-07 22:07:153530 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583531 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3532 // Static cast of boolean required for MSVC 1911.
3533 histograms_.ExpectBucketCount(
3534 "Cookie.NetworkSecurity",
3535 static_cast<int>(CookieNetworkSecurity::k1pExpiringHSTSHostCookie) |
3536 static_cast<int>(!same_site),
3537 2);
3538 }
3539}
3540
3541// Domain cookie with HSTS subdomains with cookie expiry before HSTS expiry -->
3542// k1pHSTSSubdomainsIncluded
3543TEST_P(URLRequestTestParameterizedSameSite,
3544 CookieNetworkSecurityMetricShortlivedDomainCookie) {
3545 const bool same_site = GetParam();
3546 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3547
3548 TransportSecurityState transport_security_state;
3549 transport_security_state.AddHSTS(
3550 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3551 true /* include_subdomains */);
3552 context_.set_transport_security_state(&transport_security_state);
3553 InitContext();
3554
3555 // Set cookie.
3556 {
3557 TestDelegate d;
3558 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3559 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3560 kHost_ + ";Max-Age=3600"),
3561 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3562 req->Start();
Wez2a31b222018-06-07 22:07:153563 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583564 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3565 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3566 }
3567
3568 // Verify that the cookie falls into the correct metrics bucket.
3569 {
3570 TestDelegate d;
3571 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3572 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3573 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3574 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3575 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3576 req->Start();
Wez2a31b222018-06-07 22:07:153577 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583578 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3579 // Static cast of boolean required for MSVC 1911.
3580 histograms_.ExpectBucketCount(
3581 "Cookie.NetworkSecurity",
3582 static_cast<int>(CookieNetworkSecurity::k1pHSTSSubdomainsIncluded) |
3583 static_cast<int>(!same_site),
3584 1);
3585 }
3586}
3587
3588// Long-lived (either due to expiry or due to being a session cookie) domain
3589// cookies with HSTS subdomains --> k1pExpiringHSTSSubdomainsIncluded
3590TEST_P(URLRequestTestParameterizedSameSite,
3591 CookieNetworkSecurityMetricLonglivedDomainCookie) {
3592 const bool same_site = GetParam();
3593 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3594
3595 TransportSecurityState transport_security_state;
3596 transport_security_state.AddHSTS(
3597 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3598 true /* include_subdomains */);
3599 context_.set_transport_security_state(&transport_security_state);
3600 InitContext();
3601
3602 // Set cookies.
3603 {
3604 TestDelegate d;
3605 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3606 https_server_.GetURL(
3607 kHost_, "/set-cookie?session-cookie=value;domain=" + kHost_ + "&" +
3608 "longlived-cookie=value;domain=" + kHost_ +
3609 ";Max-Age=360000"),
3610 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3611 req->Start();
Wez2a31b222018-06-07 22:07:153612 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583613 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3614 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3615 }
3616
3617 // Verify that the cookies fall into the correct metrics bucket.
3618 {
3619 TestDelegate d;
3620 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3621 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3622 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3623 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3624 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3625 req->Start();
Wez2a31b222018-06-07 22:07:153626 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583627 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3628 // Static cast of boolean required for MSVC 1911.
3629 histograms_.ExpectBucketCount(
3630 "Cookie.NetworkSecurity",
3631 static_cast<int>(
3632 CookieNetworkSecurity::k1pExpiringHSTSSubdomainsIncluded) |
3633 static_cast<int>(!same_site),
3634 2);
3635 }
3636}
3637
3638// Domain cookie with HSTS subdomains not included --> k1pHSTSSpoofable
3639TEST_P(URLRequestTestParameterizedSameSite,
3640 CookieNetworkSecurityMetricSpoofableDomainCookie) {
3641 const bool same_site = GetParam();
3642 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3643
3644 TransportSecurityState transport_security_state;
3645 transport_security_state.AddHSTS(
3646 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3647 false /* include_subdomains */);
3648 context_.set_transport_security_state(&transport_security_state);
3649 InitContext();
3650
3651 // Set cookie.
3652 {
3653 TestDelegate d;
3654 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3655 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3656 kHost_ + ";Max-Age=3600"),
3657 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3658 req->Start();
Wez2a31b222018-06-07 22:07:153659 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583660 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3661 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3662 }
3663
3664 // Verify that the cookie falls into the correct metrics bucket.
3665 {
3666 TestDelegate d;
3667 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3668 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3669 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3670 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3671 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3672 req->Start();
Wez2a31b222018-06-07 22:07:153673 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583674 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3675 // Static cast of boolean required for MSVC 1911.
3676 histograms_.ExpectBucketCount(
3677 "Cookie.NetworkSecurity",
3678 static_cast<int>(CookieNetworkSecurity::k1pHSTSSpoofable) |
3679 static_cast<int>(!same_site),
3680 1);
3681 }
3682}
3683
3684// Cookie without HSTS --> k1p(Non)SecureConnection
3685TEST_P(URLRequestTestParameterizedSameSite, CookieNetworkSecurityMetricNoHSTS) {
3686 const bool same_site = GetParam();
3687 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3688 InitContext();
3689
3690 EmbeddedTestServer http_server;
3691 http_server.AddDefaultHandlers(
3692 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3693 ASSERT_TRUE(http_server.Start());
3694
3695 // Set cookies.
3696 {
3697 TestDelegate d;
3698 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3699 https_server_.GetURL(kHost_,
3700 "/set-cookie?cookie=value;domain=" + kHost_ +
3701 ";Max-Age=3600&host-cookie=value"),
3702 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3703 req->Start();
Wez2a31b222018-06-07 22:07:153704 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583705 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3706 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3707 }
3708
3709 // Verify that the cookie falls into the correct metrics bucket.
3710 {
3711 TestDelegate d;
3712 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3713 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3714 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3715 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3716 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3717 req->Start();
Wez2a31b222018-06-07 22:07:153718 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583719 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3720 // Static cast of boolean required for MSVC 1911.
3721 histograms_.ExpectBucketCount(
3722 "Cookie.NetworkSecurity",
3723 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3724 static_cast<int>(!same_site),
3725 2);
3726 }
3727
3728 // Verify that the cookie falls into the correct metrics bucket.
3729 {
3730 TestDelegate d;
3731 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3732 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3733 TRAFFIC_ANNOTATION_FOR_TESTS));
3734 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3735 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3736 req->Start();
Wez2a31b222018-06-07 22:07:153737 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583738 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 4);
3739 // Static cast of boolean required for MSVC 1911.
3740 histograms_.ExpectBucketCount(
3741 "Cookie.NetworkSecurity",
3742 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3743 static_cast<int>(!same_site),
3744 2);
3745 // Static cast of boolean required for MSVC 1911.
3746 histograms_.ExpectBucketCount(
3747 "Cookie.NetworkSecurity",
3748 static_cast<int>(CookieNetworkSecurity::k1pNonsecureConnection) |
3749 static_cast<int>(!same_site),
3750 2);
Mike West86149882017-07-28 10:41:493751 }
3752}
3753
mmenkefb18c772015-09-30 22:22:503754// Tests that a request is cancelled while entering suspend mode. Uses mocks
3755// rather than a spawned test server because the connection used to talk to
3756// the test server is affected by entering suspend mode on Android.
3757TEST_F(URLRequestTest, CancelOnSuspend) {
3758 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363759 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503760
3761 URLRequestFailedJob::AddUrlHandler();
3762
3763 TestDelegate d;
3764 // Request that just hangs.
3765 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
Ryan Sleevib8449e02018-07-15 04:31:073766 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163767 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mmenkefb18c772015-09-30 22:22:503768 r->Start();
3769
3770 power_monitor_source->Suspend();
3771 // Wait for the suspend notification to cause the request to fail.
Wez2a31b222018-06-07 22:07:153772 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:503773 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503774 EXPECT_TRUE(d.request_failed());
3775 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3776
3777 URLRequestFilter::GetInstance()->ClearHandlers();
3778
3779 // Shouldn't be needed, but just in case.
3780 power_monitor_source->Resume();
3781}
3782
[email protected]5095cd72012-11-01 10:29:163783// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3784// value for the |fixed_date| argument given to the constructor.
3785class FixedDateNetworkDelegate : public TestNetworkDelegate {
3786 public:
3787 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3788 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:273789 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:163790
[email protected]cba24642014-08-15 20:49:593791 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203792 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593793 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:203794 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:593795 const HttpResponseHeaders* original_response_headers,
3796 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133797 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163798
3799 private:
3800 std::string fixed_date_;
3801
3802 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3803};
3804
3805int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593806 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:203807 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:593808 const HttpResponseHeaders* original_response_headers,
3809 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163810 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593811 HttpResponseHeaders* new_response_headers =
3812 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163813
3814 new_response_headers->RemoveHeader("Date");
3815 new_response_headers->AddHeader("Date: " + fixed_date_);
3816
3817 *override_response_headers = new_response_headers;
David Benjamind1f287bf2018-06-12 01:57:203818 return TestNetworkDelegate::OnHeadersReceived(
3819 request, std::move(callback), original_response_headers,
3820 override_response_headers, allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163821}
3822
3823// Test that cookie expiration times are adjusted for server/client clock
3824// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3825// headers by defaulting to GMT. (crbug.com/135131)
3826TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:393827 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:163828 ASSERT_TRUE(test_server.Start());
3829
3830 // Set up an expired cookie.
3831 {
3832 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073833 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:163834 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073835 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193836 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553837 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163838 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193839 req->Start();
Wez2a31b222018-06-07 22:07:153840 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163841 }
3842 // Verify that the cookie is not set.
3843 {
3844 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073845 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:163846 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073847 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163848 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3849 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193850 req->Start();
Wez2a31b222018-06-07 22:07:153851 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163852
3853 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3854 }
3855 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3856 {
3857 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
Ryan Sleevib8449e02018-07-15 04:31:073858 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:163859 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073860 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193861 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553862 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163863 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193864 req->Start();
Wez2a31b222018-06-07 22:07:153865 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163866 }
3867 // Verify that the cookie is set.
3868 {
3869 TestNetworkDelegate network_delegate;
Ryan Sleevib8449e02018-07-15 04:31:073870 default_context().set_network_delegate(&network_delegate);
[email protected]5095cd72012-11-01 10:29:163871 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073872 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163873 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3874 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193875 req->Start();
Wez2a31b222018-06-07 22:07:153876 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163877
3878 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3879 }
3880}
3881
3882
[email protected]316c1e5e2012-09-12 15:17:443883// Check that it is impossible to change the referrer in the extra headers of
3884// an URLRequest.
3885TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:393886 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443887 ASSERT_TRUE(test_server.Start());
3888
3889 // If extra headers contain referer and the request contains a referer,
3890 // only the latter shall be respected.
3891 {
3892 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073893 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163894 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3895 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193896 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443897
3898 HttpRequestHeaders headers;
3899 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193900 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443901
[email protected]f7022f32014-08-21 16:32:193902 req->Start();
Wez2a31b222018-06-07 22:07:153903 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443904
3905 EXPECT_EQ("http://foo.com/", d.data_received());
3906 }
3907
3908 // If extra headers contain a referer but the request does not, no referer
3909 // shall be sent in the header.
3910 {
3911 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073912 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163913 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3914 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:443915
3916 HttpRequestHeaders headers;
3917 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193918 req->SetExtraRequestHeaders(headers);
3919 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443920
[email protected]f7022f32014-08-21 16:32:193921 req->Start();
Wez2a31b222018-06-07 22:07:153922 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443923
3924 EXPECT_EQ("None", d.data_received());
3925 }
3926}
3927
[email protected]b89290212009-08-14 22:37:353928class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113929 public:
mmenke9f2ec60c2015-06-01 20:59:473930 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113931
[email protected]b89290212009-08-14 22:37:353932 protected:
[email protected]21184962011-10-26 00:50:303933 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3934 // |request_method| is the method to use for the initial request.
3935 // |redirect_method| is the method that is expected to be used for the second
3936 // request, after redirection.
3937 // If |include_data| is true, data is uploaded with the request. The
3938 // response body is expected to match it exactly, if and only if
3939 // |request_method| == |redirect_method|.
3940 void HTTPRedirectMethodTest(const GURL& redirect_url,
3941 const std::string& request_method,
3942 const std::string& redirect_method,
3943 bool include_data) {
3944 static const char kData[] = "hello world";
3945 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073946 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163947 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193948 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303949 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073950 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303951 HttpRequestHeaders headers;
3952 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:323953 base::NumberToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543954 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193955 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303956 }
[email protected]f7022f32014-08-21 16:32:193957 req->Start();
Wez2a31b222018-06-07 22:07:153958 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:193959 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:503960 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:303961 if (include_data) {
3962 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543963 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3964 HttpRequestHeaders::kContentLength));
3965 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3966 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303967 EXPECT_EQ(kData, d.data_received());
3968 } else {
svaldez5b3a8972015-10-09 23:23:543969 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3970 HttpRequestHeaders::kContentLength));
3971 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3972 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303973 EXPECT_NE(kData, d.data_received());
3974 }
3975 }
3976 if (HasFailure())
3977 LOG(WARNING) << "Request method was: " << request_method;
3978 }
3979
Alex Clarke1e08882b32017-10-06 14:22:403980 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
3981 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:513982 // |request_method| is the method to use for the initial request.
3983 // |redirect_method| is the method that is expected to be used for the second
3984 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:403985 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:513986 // redirection. If empty, expects that there will be no Origin header.
3987 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3988 const std::string& request_method,
3989 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:403990 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:513991 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:073992 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163993 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:513994 req->set_method(request_method);
3995 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3996 redirect_url.GetOrigin().spec(), false);
3997 req->Start();
3998
Wez2a31b222018-06-07 22:07:153999 d.RunUntilComplete();
jww5fe460ff2015-03-28 00:22:514000
4001 EXPECT_EQ(redirect_method, req->method());
4002 // Note that there is no check for request success here because, for
4003 // purposes of testing, the request very well may fail. For example, if the
4004 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
4005 // origin, there is not an HTTPS server in this unit test framework, so the
4006 // request would fail. However, that's fine, as long as the request headers
4007 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:404008 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:514009 EXPECT_FALSE(
4010 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
4011 } else {
4012 std::string origin_header;
4013 EXPECT_TRUE(req->extra_request_headers().GetHeader(
4014 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:404015 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:514016 }
4017 }
4018
[email protected]762d2db2010-01-11 19:03:014019 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:014020 const int kMsgSize = 20000; // multiple of 10
4021 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:484022 char* uploadBytes = new char[kMsgSize+1];
4023 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:014024 char marker = 'a';
4025 for (int idx = 0; idx < kMsgSize/10; idx++) {
4026 memcpy(ptr, "----------", 10);
4027 ptr += 10;
4028 if (idx % 100 == 0) {
4029 ptr--;
4030 *ptr++ = marker;
4031 if (++marker > 'z')
4032 marker = 'a';
4033 }
4034 }
4035 uploadBytes[kMsgSize] = '\0';
4036
[email protected]762d2db2010-01-11 19:03:014037 for (int i = 0; i < kIterations; ++i) {
4038 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074039 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164040 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
4041 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194042 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:014043
mmenkecbc2b712014-10-09 20:29:074044 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:014045
[email protected]f7022f32014-08-21 16:32:194046 r->Start();
4047 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:014048
Wez2a31b222018-06-07 22:07:154049 d.RunUntilComplete();
[email protected]762d2db2010-01-11 19:03:014050
maksim.sisovb53724b52016-09-16 05:30:504051 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
4052 << d.request_status();
[email protected]762d2db2010-01-11 19:03:014053
4054 EXPECT_FALSE(d.received_data_before_response());
4055 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:014056 }
4057 delete[] uploadBytes;
4058 }
4059
[email protected]ede03212012-09-07 12:52:264060 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:344061 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:074062 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:554063 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:364064 base::IntToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:164065 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:344066
[email protected]f7022f32014-08-21 16:32:194067 r->Start();
4068 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:344069
Wez2a31b222018-06-07 22:07:154070 d.RunUntilComplete();
[email protected]263163f2012-06-14 22:40:344071
maksim.sisovb53724b52016-09-16 05:30:504072 if (d.request_status() != OK) {
4073 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
4074 return false;
4075 }
[email protected]263163f2012-06-14 22:40:344076
maksim.sisovb53724b52016-09-16 05:30:504077 return true;
[email protected]263163f2012-06-14 22:40:344078 }
4079
David Benjamin42116f62017-11-20 21:45:394080 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:504081
tommycli59a63432015-11-06 00:10:554082 private:
David Benjamin42116f62017-11-20 21:45:394083 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:354084};
4085
tommycli59a63432015-11-06 00:10:554086namespace {
4087
danakj8522a25b2016-04-16 00:17:364088std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:554089 const test_server::HttpRequest& request) {
4090 if (request.headers.find("Host") == request.headers.end() ||
4091 request.headers.at("Host") != "www.redirect.com" ||
4092 request.method != test_server::METHOD_CONNECT) {
4093 return nullptr;
4094 }
4095
danakj8522a25b2016-04-16 00:17:364096 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554097 new test_server::BasicHttpResponse);
4098 http_response->set_code(HTTP_FOUND);
4099 http_response->AddCustomHeader("Location",
4100 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:484101 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554102}
4103
nharperb7441ef2016-01-25 23:54:144104class TestSSLConfigService : public SSLConfigService {
4105 public:
Nick Harper2243e8002018-09-28 20:33:264106 TestSSLConfigService()
4107 : min_version_(kDefaultSSLVersionMin),
davidben095ebb52017-04-12 22:23:344108 max_version_(kDefaultSSLVersionMax) {}
Ryan Sleevib8449e02018-07-15 04:31:074109 ~TestSSLConfigService() override = default;
nharperb7441ef2016-01-25 23:54:144110
davidben095ebb52017-04-12 22:23:344111 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:144112 void set_min_version(uint16_t version) { min_version_ = version; }
4113
nharperb7441ef2016-01-25 23:54:144114 // SSLConfigService:
4115 void GetSSLConfig(SSLConfig* config) override {
4116 *config = SSLConfig();
davidben095ebb52017-04-12 22:23:344117 config->version_min = min_version_;
4118 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:144119 }
4120
Nick Harper89bc7212018-07-31 19:07:574121 bool CanShareConnectionWithClientCerts(
4122 const std::string& hostname) const override {
4123 return false;
4124 }
4125
nharperb7441ef2016-01-25 23:54:144126 private:
nharperb7441ef2016-01-25 23:54:144127 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:344128 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:144129};
4130
Nick Harper89bc7212018-07-31 19:07:574131} // namespace
4132
nharperb7441ef2016-01-25 23:54:144133// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114134// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:554135// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:114136// follow.
[email protected]f2f31b32013-01-16 23:24:094137TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:554138 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124139 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:554140 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114141
[email protected]ceefd7fd2012-11-29 00:36:244142 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044143 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554144 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504145
[email protected]d1ec59082009-02-11 02:48:154146 TestDelegate d;
4147 {
danakj8522a25b2016-04-16 00:17:364148 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164149 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4150 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194151 r->Start();
4152 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:154153
Wez2a31b222018-06-07 22:07:154154 d.RunUntilComplete();
[email protected]d1ec59082009-02-11 02:48:154155
[email protected]d8fc4722014-06-13 13:17:154156 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474157 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504158 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084159 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:154160 // We should not have followed the redirect.
4161 EXPECT_EQ(0, d.received_redirect_count());
4162 }
4163}
4164
[email protected]8202d0c2011-02-23 08:31:144165// This is the same as the previous test, but checks that the network delegate
4166// registers the error.
[email protected]c044616e2013-02-20 02:01:264167TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554168 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144169
[email protected]ceefd7fd2012-11-29 00:36:244170 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044171 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554172 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504173
[email protected]8202d0c2011-02-23 08:31:144174 TestDelegate d;
4175 {
danakj8522a25b2016-04-16 00:17:364176 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164177 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4178 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194179 r->Start();
4180 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144181
Wez2a31b222018-06-07 22:07:154182 d.RunUntilComplete();
[email protected]8202d0c2011-02-23 08:31:144183
[email protected]d8fc4722014-06-13 13:17:154184 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474185 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:144186 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504187 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144188 // We should not have followed the redirect.
4189 EXPECT_EQ(0, d.received_redirect_count());
4190
4191 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014192 EXPECT_THAT(network_delegate.last_error(),
4193 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144194 }
4195}
4196
[email protected]dc5a5cf2012-09-26 02:49:304197// Tests that we can block and asynchronously return OK in various stages.
4198TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4199 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4200 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4201 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4202 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4203 };
4204 static const size_t blocking_stages_length = arraysize(blocking_stages);
4205
tommycli59a63432015-11-06 00:10:554206 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304207
4208 TestDelegate d;
4209 BlockingNetworkDelegate network_delegate(
4210 BlockingNetworkDelegate::USER_CALLBACK);
4211 network_delegate.set_block_on(
4212 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4213 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4214 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4215
4216 TestURLRequestContext context(true);
4217 context.set_network_delegate(&network_delegate);
4218 context.Init();
4219
4220 {
danakj8522a25b2016-04-16 00:17:364221 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164222 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4223 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304224
[email protected]f7022f32014-08-21 16:32:194225 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304226 for (size_t i = 0; i < blocking_stages_length; ++i) {
Wez2a31b222018-06-07 22:07:154227 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304228 EXPECT_EQ(blocking_stages[i],
4229 network_delegate.stage_blocked_for_callback());
4230 network_delegate.DoCallback(OK);
4231 }
Wez2a31b222018-06-07 22:07:154232 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194233 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504234 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304235 EXPECT_EQ(1, network_delegate.created_requests());
4236 EXPECT_EQ(0, network_delegate.destroyed_requests());
4237 }
4238 EXPECT_EQ(1, network_delegate.destroyed_requests());
4239}
4240
[email protected]4c76d7c2011-04-15 19:14:124241// Tests that the network delegate can block and cancel a request.
4242TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554243 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124244
4245 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304246 BlockingNetworkDelegate network_delegate(
4247 BlockingNetworkDelegate::AUTO_CALLBACK);
4248 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4249 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124250
[email protected]d5a4dd62012-05-23 01:41:044251 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554252 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504253
[email protected]4c76d7c2011-04-15 19:14:124254 {
rhalavatib7bd7c792017-04-27 05:25:164255 std::unique_ptr<URLRequest> r(
4256 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4257 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124258
[email protected]f7022f32014-08-21 16:32:194259 r->Start();
Wez2a31b222018-06-07 22:07:154260 d.RunUntilComplete();
[email protected]4c76d7c2011-04-15 19:14:124261
[email protected]d8fc4722014-06-13 13:17:154262 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474263 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504264 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124265 EXPECT_EQ(1, network_delegate.created_requests());
4266 EXPECT_EQ(0, network_delegate.destroyed_requests());
4267 }
4268 EXPECT_EQ(1, network_delegate.destroyed_requests());
4269}
4270
[email protected]b4438d32012-09-27 06:15:304271// Helper function for NetworkDelegateCancelRequestAsynchronously and
4272// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4273// delegate operating in |block_mode| and a request for |url|. It blocks the
4274// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4275void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4276 BlockingNetworkDelegate::Stage stage,
4277 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364278 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304279 BlockingNetworkDelegate network_delegate(block_mode);
4280 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4281 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364282
[email protected]b4438d32012-09-27 06:15:304283 TestURLRequestContext context(true);
4284 context.set_network_delegate(&network_delegate);
4285 context.Init();
[email protected]3cd384c602011-08-31 16:12:364286
4287 {
rhalavatib7bd7c792017-04-27 05:25:164288 std::unique_ptr<URLRequest> r(context.CreateRequest(
4289 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364290
[email protected]f7022f32014-08-21 16:32:194291 r->Start();
Wez2a31b222018-06-07 22:07:154292 d.RunUntilComplete();
[email protected]3cd384c602011-08-31 16:12:364293
[email protected]d8fc4722014-06-13 13:17:154294 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474295 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4296 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4297 EXPECT_FALSE(r->proxy_server().is_valid());
4298 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4299 EXPECT_TRUE(r->proxy_server().is_direct());
4300 } else {
4301 NOTREACHED();
4302 }
maksim.sisovb53724b52016-09-16 05:30:504303 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364304 EXPECT_EQ(1, network_delegate.created_requests());
4305 EXPECT_EQ(0, network_delegate.destroyed_requests());
4306 }
4307 EXPECT_EQ(1, network_delegate.destroyed_requests());
4308}
4309
[email protected]b4438d32012-09-27 06:15:304310// The following 3 tests check that the network delegate can cancel a request
4311// synchronously in various stages of the request.
4312TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554313 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304314 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4315 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554316 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304317}
4318
4319TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554320 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304321 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4322 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554323 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304324}
4325
4326TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554327 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304328 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4329 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554330 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304331}
4332
4333// The following 3 tests check that the network delegate can cancel a request
4334// asynchronously in various stages of the request.
4335TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554336 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304337 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4338 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554339 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304340}
4341
4342TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554343 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304344 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4345 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554346 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304347}
4348
4349TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554350 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304351 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4352 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554353 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304354}
4355
[email protected]4c76d7c2011-04-15 19:14:124356// Tests that the network delegate can block and redirect a request to a new
4357// URL.
4358TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554359 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124360
4361 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304362 BlockingNetworkDelegate network_delegate(
4363 BlockingNetworkDelegate::AUTO_CALLBACK);
4364 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
Eric Romanda790f92018-11-07 19:17:154365 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]4c76d7c2011-04-15 19:14:124366 network_delegate.set_redirect_url(redirect_url);
4367
[email protected]d5a4dd62012-05-23 01:41:044368 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554369 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504370
[email protected]4c76d7c2011-04-15 19:14:124371 {
Eric Romanda790f92018-11-07 19:17:154372 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164373 std::unique_ptr<URLRequest> r(context.CreateRequest(
4374 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124375
[email protected]6be6fa92014-08-06 23:44:564376 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194377 r->Start();
Wez0e717112018-06-18 23:09:224378 d.RunUntilRedirect();
[email protected]4c76d7c2011-04-15 19:14:124379
[email protected]6be6fa92014-08-06 23:44:564380 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194381 EXPECT_EQ(307, r->GetResponseCode());
4382 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564383 std::string location;
[email protected]f7022f32014-08-21 16:32:194384 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4385 &location));
[email protected]6be6fa92014-08-06 23:44:564386 EXPECT_EQ(redirect_url, GURL(location));
4387
4388 // Let the request finish.
Chong Zhang7607f1f2018-06-01 20:52:204389 r->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:154390 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:504391 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474392 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4393 http_test_server()->host_port_pair()),
4394 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094395 // before_send_headers_with_proxy_count only increments for headers sent
4396 // through an untunneled proxy.
4397 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554398 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4399 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274400
maksim.sisovb53724b52016-09-16 05:30:504401 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194402 EXPECT_EQ(redirect_url, r->url());
4403 EXPECT_EQ(original_url, r->original_url());
4404 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124405 EXPECT_EQ(1, network_delegate.created_requests());
4406 EXPECT_EQ(0, network_delegate.destroyed_requests());
4407 }
4408 EXPECT_EQ(1, network_delegate.destroyed_requests());
4409}
4410
[email protected]b813ed72012-04-05 08:21:364411// Tests that the network delegate can block and redirect a request to a new
4412// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4413TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554414 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364415
4416 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304417 BlockingNetworkDelegate network_delegate(
4418 BlockingNetworkDelegate::SYNCHRONOUS);
Eric Romanda790f92018-11-07 19:17:154419 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]b813ed72012-04-05 08:21:364420 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364421
[email protected]d5a4dd62012-05-23 01:41:044422 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554423 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364424
4425 {
Eric Romanda790f92018-11-07 19:17:154426 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164427 std::unique_ptr<URLRequest> r(context.CreateRequest(
4428 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364429
[email protected]6be6fa92014-08-06 23:44:564430 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194431 r->Start();
Wez0e717112018-06-18 23:09:224432 d.RunUntilRedirect();
[email protected]b813ed72012-04-05 08:21:364433
[email protected]6be6fa92014-08-06 23:44:564434 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194435 EXPECT_EQ(307, r->GetResponseCode());
4436 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564437 std::string location;
[email protected]f7022f32014-08-21 16:32:194438 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4439 &location));
[email protected]6be6fa92014-08-06 23:44:564440 EXPECT_EQ(redirect_url, GURL(location));
4441
4442 // Let the request finish.
Chong Zhang7607f1f2018-06-01 20:52:204443 r->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:154444 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564445
maksim.sisovb53724b52016-09-16 05:30:504446 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474447 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4448 http_test_server()->host_port_pair()),
4449 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094450 // before_send_headers_with_proxy_count only increments for headers sent
4451 // through an untunneled proxy.
4452 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554453 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4454 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504455 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194456 EXPECT_EQ(redirect_url, r->url());
4457 EXPECT_EQ(original_url, r->original_url());
4458 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364459 EXPECT_EQ(1, network_delegate.created_requests());
4460 EXPECT_EQ(0, network_delegate.destroyed_requests());
4461 }
4462 EXPECT_EQ(1, network_delegate.destroyed_requests());
4463}
4464
[email protected]3c5ca8c2011-09-29 01:14:514465// Tests that redirects caused by the network delegate preserve POST data.
4466TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554467 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514468
4469 const char kData[] = "hello world";
4470
4471 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304472 BlockingNetworkDelegate network_delegate(
4473 BlockingNetworkDelegate::AUTO_CALLBACK);
4474 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554475 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514476 network_delegate.set_redirect_url(redirect_url);
4477
[email protected]ef2bf422012-05-11 03:27:094478 TestURLRequestContext context(true);
4479 context.set_network_delegate(&network_delegate);
4480 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514481
4482 {
tommycli59a63432015-11-06 00:10:554483 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164484 std::unique_ptr<URLRequest> r(context.CreateRequest(
4485 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194486 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074487 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514488 HttpRequestHeaders headers;
4489 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:324490 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194491 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564492
4493 // Quit after hitting the redirect, so can check the headers.
[email protected]f7022f32014-08-21 16:32:194494 r->Start();
Wez0e717112018-06-18 23:09:224495 d.RunUntilRedirect();
[email protected]3c5ca8c2011-09-29 01:14:514496
[email protected]6be6fa92014-08-06 23:44:564497 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194498 EXPECT_EQ(307, r->GetResponseCode());
4499 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564500 std::string location;
[email protected]f7022f32014-08-21 16:32:194501 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4502 &location));
[email protected]6be6fa92014-08-06 23:44:564503 EXPECT_EQ(redirect_url, GURL(location));
4504
4505 // Let the request finish.
Chong Zhang7607f1f2018-06-01 20:52:204506 r->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:154507 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564508
maksim.sisovb53724b52016-09-16 05:30:504509 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194510 EXPECT_EQ(redirect_url, r->url());
4511 EXPECT_EQ(original_url, r->original_url());
4512 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514513 EXPECT_EQ(1, network_delegate.created_requests());
4514 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194515 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514516 EXPECT_EQ(kData, d.data_received());
4517 }
4518 EXPECT_EQ(1, network_delegate.destroyed_requests());
4519}
4520
[email protected]5f714132014-03-26 10:41:164521// Tests that the network delegate can block and redirect a request to a new
4522// URL during OnHeadersReceived.
4523TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554524 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164525
4526 TestDelegate d;
4527 BlockingNetworkDelegate network_delegate(
4528 BlockingNetworkDelegate::AUTO_CALLBACK);
4529 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
Eric Romanda790f92018-11-07 19:17:154530 GURL redirect_url("http://does.not.resolve.test/simple.html");
[email protected]5f714132014-03-26 10:41:164531 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4532
4533 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554534 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164535
4536 {
Eric Romanda790f92018-11-07 19:17:154537 GURL original_url("http://does.not.resolve.test/defaultresponse");
rhalavatib7bd7c792017-04-27 05:25:164538 std::unique_ptr<URLRequest> r(context.CreateRequest(
4539 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164540
[email protected]f7022f32014-08-21 16:32:194541 r->Start();
Wez2a31b222018-06-07 22:07:154542 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:164543
maksim.sisovb53724b52016-09-16 05:30:504544 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474545 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4546 http_test_server()->host_port_pair()),
4547 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094548 // before_send_headers_with_proxy_count only increments for headers sent
4549 // through an untunneled proxy.
4550 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554551 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4552 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194553
maksim.sisovb53724b52016-09-16 05:30:504554 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194555 EXPECT_EQ(redirect_url, r->url());
4556 EXPECT_EQ(original_url, r->original_url());
4557 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164558 EXPECT_EQ(2, network_delegate.created_requests());
4559 EXPECT_EQ(0, network_delegate.destroyed_requests());
4560 }
4561 EXPECT_EQ(1, network_delegate.destroyed_requests());
4562}
4563
[email protected]c2911d72011-10-03 22:16:364564// Tests that the network delegate can synchronously complete OnAuthRequired
4565// by taking no action. This indicates that the NetworkDelegate does not want to
4566// handle the challenge, and is passing the buck along to the
4567// URLRequest::Delegate.
4568TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554569 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364570
4571 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304572 BlockingNetworkDelegate network_delegate(
4573 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364574
[email protected]ef2bf422012-05-11 03:27:094575 TestURLRequestContext context(true);
4576 context.set_network_delegate(&network_delegate);
4577 context.Init();
[email protected]c2911d72011-10-03 22:16:364578
[email protected]f3cf9802011-10-28 18:44:584579 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364580
4581 {
tommycli59a63432015-11-06 00:10:554582 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164583 std::unique_ptr<URLRequest> r(context.CreateRequest(
4584 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194585 r->Start();
[email protected]79e1fd62013-06-20 06:50:044586
Wez2a31b222018-06-07 22:07:154587 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044588
maksim.sisovb53724b52016-09-16 05:30:504589 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194590 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044591 EXPECT_TRUE(d.auth_required_called());
4592 EXPECT_EQ(1, network_delegate.created_requests());
4593 EXPECT_EQ(0, network_delegate.destroyed_requests());
4594 }
4595 EXPECT_EQ(1, network_delegate.destroyed_requests());
4596}
4597
4598TEST_F(URLRequestTestHTTP,
4599 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554600 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044601
4602 TestDelegate d;
4603 BlockingNetworkDelegate network_delegate(
4604 BlockingNetworkDelegate::SYNCHRONOUS);
4605
4606 TestURLRequestContext context(true);
4607 context.set_network_delegate(&network_delegate);
4608 context.Init();
4609
4610 d.set_credentials(AuthCredentials(kUser, kSecret));
4611
4612 {
tommycli59a63432015-11-06 00:10:554613 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164614 std::unique_ptr<URLRequest> r(context.CreateRequest(
4615 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194616 r->Start();
[email protected]79e1fd62013-06-20 06:50:044617
Wez2a31b222018-06-07 22:07:154618 d.RunUntilComplete();
shivanisha8061c4202017-06-13 23:35:524619
[email protected]79e1fd62013-06-20 06:50:044620 {
4621 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194622 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524623 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044624 }
4625
maksim.sisovb53724b52016-09-16 05:30:504626 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194627 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364628 EXPECT_TRUE(d.auth_required_called());
4629 EXPECT_EQ(1, network_delegate.created_requests());
4630 EXPECT_EQ(0, network_delegate.destroyed_requests());
4631 }
4632 EXPECT_EQ(1, network_delegate.destroyed_requests());
4633}
4634
4635// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404636// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364637TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554638 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364639
4640 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304641 BlockingNetworkDelegate network_delegate(
4642 BlockingNetworkDelegate::SYNCHRONOUS);
4643 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364644 network_delegate.set_auth_retval(
4645 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4646
[email protected]f3cf9802011-10-28 18:44:584647 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364648
[email protected]ef2bf422012-05-11 03:27:094649 TestURLRequestContext context(true);
4650 context.set_network_delegate(&network_delegate);
4651 context.Init();
[email protected]c2911d72011-10-03 22:16:364652
4653 {
tommycli59a63432015-11-06 00:10:554654 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164655 std::unique_ptr<URLRequest> r(context.CreateRequest(
4656 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194657 r->Start();
Wez2a31b222018-06-07 22:07:154658 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364659
maksim.sisovb53724b52016-09-16 05:30:504660 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194661 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364662 EXPECT_FALSE(d.auth_required_called());
4663 EXPECT_EQ(1, network_delegate.created_requests());
4664 EXPECT_EQ(0, network_delegate.destroyed_requests());
4665 }
4666 EXPECT_EQ(1, network_delegate.destroyed_requests());
4667}
4668
[email protected]79e1fd62013-06-20 06:50:044669// Same as above, but also tests that GetFullRequestHeaders returns the proper
4670// headers (for the first or second request) when called at the proper times.
4671TEST_F(URLRequestTestHTTP,
4672 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554673 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044674
4675 TestDelegate d;
4676 BlockingNetworkDelegate network_delegate(
4677 BlockingNetworkDelegate::SYNCHRONOUS);
4678 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4679 network_delegate.set_auth_retval(
4680 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4681
4682 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4683
4684 TestURLRequestContext context(true);
4685 context.set_network_delegate(&network_delegate);
4686 context.Init();
4687
4688 {
tommycli59a63432015-11-06 00:10:554689 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164690 std::unique_ptr<URLRequest> r(context.CreateRequest(
4691 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194692 r->Start();
Wez2a31b222018-06-07 22:07:154693 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044694
maksim.sisovb53724b52016-09-16 05:30:504695 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194696 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044697 EXPECT_FALSE(d.auth_required_called());
4698 EXPECT_EQ(1, network_delegate.created_requests());
4699 EXPECT_EQ(0, network_delegate.destroyed_requests());
4700
4701 {
4702 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194703 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044704 EXPECT_TRUE(headers.HasHeader("Authorization"));
4705 }
4706 }
4707 EXPECT_EQ(1, network_delegate.destroyed_requests());
4708}
4709
[email protected]c2911d72011-10-03 22:16:364710// Tests that the network delegate can synchronously complete OnAuthRequired
4711// by cancelling authentication.
4712TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554713 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364714
4715 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304716 BlockingNetworkDelegate network_delegate(
4717 BlockingNetworkDelegate::SYNCHRONOUS);
4718 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364719 network_delegate.set_auth_retval(
4720 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4721
[email protected]ef2bf422012-05-11 03:27:094722 TestURLRequestContext context(true);
4723 context.set_network_delegate(&network_delegate);
4724 context.Init();
[email protected]c2911d72011-10-03 22:16:364725
4726 {
tommycli59a63432015-11-06 00:10:554727 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164728 std::unique_ptr<URLRequest> r(context.CreateRequest(
4729 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194730 r->Start();
Wez2a31b222018-06-07 22:07:154731 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364732
maksim.sisovb53724b52016-09-16 05:30:504733 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194734 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364735 EXPECT_FALSE(d.auth_required_called());
4736 EXPECT_EQ(1, network_delegate.created_requests());
4737 EXPECT_EQ(0, network_delegate.destroyed_requests());
4738 }
4739 EXPECT_EQ(1, network_delegate.destroyed_requests());
4740}
4741
4742// Tests that the network delegate can asynchronously complete OnAuthRequired
4743// by taking no action. This indicates that the NetworkDelegate does not want
4744// to handle the challenge, and is passing the buck along to the
4745// URLRequest::Delegate.
4746TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554747 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364748
4749 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304750 BlockingNetworkDelegate network_delegate(
4751 BlockingNetworkDelegate::AUTO_CALLBACK);
4752 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364753
[email protected]ef2bf422012-05-11 03:27:094754 TestURLRequestContext context(true);
4755 context.set_network_delegate(&network_delegate);
4756 context.Init();
[email protected]c2911d72011-10-03 22:16:364757
[email protected]f3cf9802011-10-28 18:44:584758 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364759
4760 {
tommycli59a63432015-11-06 00:10:554761 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164762 std::unique_ptr<URLRequest> r(context.CreateRequest(
4763 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194764 r->Start();
Wez2a31b222018-06-07 22:07:154765 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364766
maksim.sisovb53724b52016-09-16 05:30:504767 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194768 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364769 EXPECT_TRUE(d.auth_required_called());
4770 EXPECT_EQ(1, network_delegate.created_requests());
4771 EXPECT_EQ(0, network_delegate.destroyed_requests());
4772 }
4773 EXPECT_EQ(1, network_delegate.destroyed_requests());
4774}
4775
4776// Tests that the network delegate can asynchronously complete OnAuthRequired
4777// by setting credentials.
4778TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554779 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364780
4781 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304782 BlockingNetworkDelegate network_delegate(
4783 BlockingNetworkDelegate::AUTO_CALLBACK);
4784 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364785 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364786 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4787
[email protected]f3cf9802011-10-28 18:44:584788 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364789 network_delegate.set_auth_credentials(auth_credentials);
4790
[email protected]ef2bf422012-05-11 03:27:094791 TestURLRequestContext context(true);
4792 context.set_network_delegate(&network_delegate);
4793 context.Init();
[email protected]c2911d72011-10-03 22:16:364794
4795 {
tommycli59a63432015-11-06 00:10:554796 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164797 std::unique_ptr<URLRequest> r(context.CreateRequest(
4798 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194799 r->Start();
Wez2a31b222018-06-07 22:07:154800 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364801
maksim.sisovb53724b52016-09-16 05:30:504802 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194803 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364804 EXPECT_FALSE(d.auth_required_called());
4805 EXPECT_EQ(1, network_delegate.created_requests());
4806 EXPECT_EQ(0, network_delegate.destroyed_requests());
4807 }
4808 EXPECT_EQ(1, network_delegate.destroyed_requests());
4809}
4810
4811// Tests that the network delegate can asynchronously complete OnAuthRequired
4812// by cancelling authentication.
4813TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554814 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364815
4816 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304817 BlockingNetworkDelegate network_delegate(
4818 BlockingNetworkDelegate::AUTO_CALLBACK);
4819 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364820 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364821 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4822
[email protected]ef2bf422012-05-11 03:27:094823 TestURLRequestContext context(true);
4824 context.set_network_delegate(&network_delegate);
4825 context.Init();
[email protected]c2911d72011-10-03 22:16:364826
4827 {
tommycli59a63432015-11-06 00:10:554828 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164829 std::unique_ptr<URLRequest> r(context.CreateRequest(
4830 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194831 r->Start();
Wez2a31b222018-06-07 22:07:154832 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364833
maksim.sisovb53724b52016-09-16 05:30:504834 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194835 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364836 EXPECT_FALSE(d.auth_required_called());
4837 EXPECT_EQ(1, network_delegate.created_requests());
4838 EXPECT_EQ(0, network_delegate.destroyed_requests());
4839 }
4840 EXPECT_EQ(1, network_delegate.destroyed_requests());
4841}
4842
David Benjamin0bda12f2018-02-07 19:58:454843// Tests that NetworkDelegate header overrides from the 401 response do not
4844// affect the 200 response. This is a regression test for
4845// https://crbug.com/801237.
4846TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
4847 ASSERT_TRUE(http_test_server()->Start());
4848
4849 TestDelegate d;
4850 d.set_credentials(AuthCredentials(kUser, kSecret));
4851 default_network_delegate_.set_add_header_to_first_response(true);
4852
4853 {
4854 GURL url(http_test_server()->GetURL("/auth-basic"));
Ryan Sleevib8449e02018-07-15 04:31:074855 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:454856 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4857 r->Start();
4858
Wez2a31b222018-06-07 22:07:154859 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:454860
4861 EXPECT_EQ(OK, d.request_status());
4862 EXPECT_EQ(200, r->GetResponseCode());
4863 EXPECT_TRUE(d.auth_required_called());
4864 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
4865 }
4866
4867 {
4868 GURL url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:074869 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
David Benjamin0bda12f2018-02-07 19:58:454870 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4871 r->Start();
4872
Wez2a31b222018-06-07 22:07:154873 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:454874
4875 // Check that set_add_header_to_first_response normally adds a header.
4876 EXPECT_EQ(OK, d.request_status());
4877 EXPECT_EQ(200, r->GetResponseCode());
4878 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
4879 }
4880}
4881
[email protected]9045b8822012-01-13 20:35:354882// Tests that we can handle when a network request was canceled while we were
4883// waiting for the network delegate.
4884// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4885TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554886 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354887
4888 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304889 BlockingNetworkDelegate network_delegate(
4890 BlockingNetworkDelegate::USER_CALLBACK);
4891 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354892
[email protected]ef2bf422012-05-11 03:27:094893 TestURLRequestContext context(true);
4894 context.set_network_delegate(&network_delegate);
4895 context.Init();
[email protected]9045b8822012-01-13 20:35:354896
4897 {
rhalavatib7bd7c792017-04-27 05:25:164898 std::unique_ptr<URLRequest> r(
4899 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4900 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354901
[email protected]f7022f32014-08-21 16:32:194902 r->Start();
Wez2a31b222018-06-07 22:07:154903 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304904 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4905 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354906 EXPECT_EQ(0, network_delegate.completed_requests());
4907 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194908 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354909 // Ensure that network delegate is notified.
4910 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504911 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354912 EXPECT_EQ(1, network_delegate.created_requests());
4913 EXPECT_EQ(0, network_delegate.destroyed_requests());
4914 }
4915 EXPECT_EQ(1, network_delegate.destroyed_requests());
4916}
4917
4918// Tests that we can handle when a network request was canceled while we were
4919// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:004920// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
4921// callback.
[email protected]9045b8822012-01-13 20:35:354922TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554923 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354924
4925 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304926 BlockingNetworkDelegate network_delegate(
4927 BlockingNetworkDelegate::USER_CALLBACK);
4928 network_delegate.set_block_on(
4929 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354930
[email protected]ef2bf422012-05-11 03:27:094931 TestURLRequestContext context(true);
4932 context.set_network_delegate(&network_delegate);
4933 context.Init();
[email protected]9045b8822012-01-13 20:35:354934
4935 {
rhalavatib7bd7c792017-04-27 05:25:164936 std::unique_ptr<URLRequest> r(
4937 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4938 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354939
[email protected]f7022f32014-08-21 16:32:194940 r->Start();
Wez2a31b222018-06-07 22:07:154941 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304942 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4943 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354944 EXPECT_EQ(0, network_delegate.completed_requests());
4945 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194946 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354947 // Ensure that network delegate is notified.
4948 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504949 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354950 EXPECT_EQ(1, network_delegate.created_requests());
4951 EXPECT_EQ(0, network_delegate.destroyed_requests());
4952 }
4953 EXPECT_EQ(1, network_delegate.destroyed_requests());
4954}
4955
4956// Tests that we can handle when a network request was canceled while we were
4957// waiting for the network delegate.
4958// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4959TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554960 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354961
4962 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304963 BlockingNetworkDelegate network_delegate(
4964 BlockingNetworkDelegate::USER_CALLBACK);
4965 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354966
[email protected]ef2bf422012-05-11 03:27:094967 TestURLRequestContext context(true);
4968 context.set_network_delegate(&network_delegate);
4969 context.Init();
[email protected]9045b8822012-01-13 20:35:354970
4971 {
rhalavatib7bd7c792017-04-27 05:25:164972 std::unique_ptr<URLRequest> r(
4973 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4974 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354975
[email protected]f7022f32014-08-21 16:32:194976 r->Start();
Wez2a31b222018-06-07 22:07:154977 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304978 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4979 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354980 EXPECT_EQ(0, network_delegate.completed_requests());
4981 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194982 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354983 // Ensure that network delegate is notified.
4984 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504985 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354986 EXPECT_EQ(1, network_delegate.created_requests());
4987 EXPECT_EQ(0, network_delegate.destroyed_requests());
4988 }
4989 EXPECT_EQ(1, network_delegate.destroyed_requests());
4990}
4991
4992// Tests that we can handle when a network request was canceled while we were
4993// waiting for the network delegate.
4994// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024995TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554996 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354997
4998 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304999 BlockingNetworkDelegate network_delegate(
5000 BlockingNetworkDelegate::USER_CALLBACK);
5001 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:355002
[email protected]ef2bf422012-05-11 03:27:095003 TestURLRequestContext context(true);
5004 context.set_network_delegate(&network_delegate);
5005 context.Init();
[email protected]9045b8822012-01-13 20:35:355006
5007 {
danakj8522a25b2016-04-16 00:17:365008 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165009 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
5010 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355011
[email protected]f7022f32014-08-21 16:32:195012 r->Start();
Wez2a31b222018-06-07 22:07:155013 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305014 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
5015 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355016 EXPECT_EQ(0, network_delegate.completed_requests());
5017 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195018 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355019 // Ensure that network delegate is notified.
5020 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505021 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355022 EXPECT_EQ(1, network_delegate.created_requests());
5023 EXPECT_EQ(0, network_delegate.destroyed_requests());
5024 }
5025 EXPECT_EQ(1, network_delegate.destroyed_requests());
5026}
5027
tommycli59a63432015-11-06 00:10:555028namespace {
5029
danakj8522a25b2016-04-16 00:17:365030std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:555031 const test_server::HttpRequest& request) {
5032 if (request.headers.find("Host") == request.headers.end() ||
5033 request.headers.at("Host") != "www.server-auth.com" ||
5034 request.method != test_server::METHOD_CONNECT) {
5035 return nullptr;
5036 }
5037
danakj8522a25b2016-04-16 00:17:365038 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:555039 new test_server::BasicHttpResponse);
5040 http_response->set_code(HTTP_UNAUTHORIZED);
5041 http_response->AddCustomHeader("WWW-Authenticate",
5042 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:485043 return std::move(http_response);
tommycli59a63432015-11-06 00:10:555044}
5045
5046} // namespace
5047
5048// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:115049// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:555050// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:355051TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:555052 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:125053 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:555054 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115055
[email protected]ceefd7fd2012-11-29 00:36:245056 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:045057 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:555058 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:505059
[email protected]dc651782009-02-14 01:45:085060 TestDelegate d;
5061 {
danakj8522a25b2016-04-16 00:17:365062 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165063 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
5064 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:085065
[email protected]f7022f32014-08-21 16:32:195066 r->Start();
5067 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:085068
Wez2a31b222018-06-07 22:07:155069 d.RunUntilComplete();
[email protected]dc651782009-02-14 01:45:085070
[email protected]d8fc4722014-06-13 13:17:155071 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:475072 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:505073 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:085074 }
5075}
5076
[email protected]b89290212009-08-14 22:37:355077TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:555078 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115079
initial.commit586acc5fe2008-07-26 22:42:525080 TestDelegate d;
5081 {
Ryan Sleevib8449e02018-07-15 04:31:075082 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165083 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5084 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525085
[email protected]f7022f32014-08-21 16:32:195086 r->Start();
5087 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525088
Wez2a31b222018-06-07 22:07:155089 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525090
5091 EXPECT_EQ(1, d.response_started_count());
5092 EXPECT_FALSE(d.received_data_before_response());
5093 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555094 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195095 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555096 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195097 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:165098
[email protected]9e743cd2010-03-16 07:03:535099 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:525100 }
initial.commit586acc5fe2008-07-26 22:42:525101}
5102
[email protected]263163f2012-06-14 22:40:345103// This test has the server send a large number of cookies to the client.
5104// To ensure that no number of cookies causes a crash, a galloping binary
5105// search is used to estimate that maximum number of cookies that are accepted
5106// by the browser. Beyond the maximum number, the request will fail with
5107// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:315108#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:305109// http://crbug.com/177916
5110#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
5111#else
5112#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
5113#endif // defined(OS_WIN)
5114TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:555115 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:345116
5117 int lower_bound = 0;
5118 int upper_bound = 1;
5119
5120 // Double the number of cookies until the response header limits are
5121 // exceeded.
5122 while (DoManyCookiesRequest(upper_bound)) {
5123 lower_bound = upper_bound;
5124 upper_bound *= 2;
5125 ASSERT_LT(upper_bound, 1000000);
5126 }
5127
pkasting6b68a162014-12-01 22:10:295128 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:345129 if (tolerance < 2)
5130 tolerance = 2;
5131
5132 // Perform a binary search to find the highest possible number of cookies,
5133 // within the desired tolerance.
5134 while (upper_bound - lower_bound >= tolerance) {
5135 int num_cookies = (lower_bound + upper_bound) / 2;
5136
5137 if (DoManyCookiesRequest(num_cookies))
5138 lower_bound = num_cookies;
5139 else
5140 upper_bound = num_cookies;
5141 }
5142 // Success: the test did not crash.
5143}
5144
[email protected]b89290212009-08-14 22:37:355145TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:555146 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115147
initial.commit586acc5fe2008-07-26 22:42:525148 TestDelegate d;
5149 {
Ryan Sleevib8449e02018-07-15 04:31:075150 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165151 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5152 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525153
[email protected]f7022f32014-08-21 16:32:195154 r->Start();
5155 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525156
Wez2a31b222018-06-07 22:07:155157 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525158
5159 EXPECT_EQ(1, d.response_started_count());
5160 EXPECT_FALSE(d.received_data_before_response());
5161 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555162 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195163 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555164 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195165 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:525166 }
[email protected]5d7b373e2009-09-02 07:19:035167}
5168
[email protected]79e1fd62013-06-20 06:50:045169TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555170 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045171
5172 TestDelegate d;
5173 {
tommycli59a63432015-11-06 00:10:555174 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
Ryan Sleevib8449e02018-07-15 04:31:075175 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165176 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045177
5178 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195179 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045180
[email protected]f7022f32014-08-21 16:32:195181 r->Start();
5182 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045183
Wez2a31b222018-06-07 22:07:155184 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:045185
5186 EXPECT_EQ(1, d.response_started_count());
5187 EXPECT_FALSE(d.received_data_before_response());
5188 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555189 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195190 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555191 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195192 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:045193
5194 EXPECT_TRUE(d.have_full_request_headers());
5195 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5196 }
5197}
5198
[email protected]58e32bb2013-01-21 18:23:255199TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555200 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255201
5202 TestDelegate d;
5203 {
Ryan Sleevib8449e02018-07-15 04:31:075204 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165205 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5206 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255207
[email protected]f7022f32014-08-21 16:32:195208 r->Start();
5209 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255210
Wez2a31b222018-06-07 22:07:155211 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255212
5213 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195214 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255215 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5216
5217 EXPECT_EQ(1, d.response_started_count());
5218 EXPECT_FALSE(d.received_data_before_response());
5219 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555220 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195221 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555222 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195223 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:255224 }
5225}
5226
tommycli59a63432015-11-06 00:10:555227// TODO(svaldez): Update tests to use EmbeddedTestServer.
5228#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395229TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555230 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555231 base::FilePath(kTestFilePath));
5232
5233 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395234
5235 // Parameter that specifies the Content-Length field in the response:
5236 // C - Compressed length.
5237 // U - Uncompressed length.
5238 // L - Large length (larger than both C & U).
5239 // M - Medium length (between C & U).
5240 // S - Small length (smaller than both C & U).
5241 const char test_parameters[] = "CULMS";
5242 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
5243 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445244 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395245 // S has too little data, but we seem to accept it.
5246 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375247 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395248
xunjielifb4da222016-07-14 18:38:595249 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:195250 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
xunjielifb4da222016-07-14 18:38:595251 file_path = file_path.Append(kTestFilePath);
5252 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5253 std::string expected_content;
5254 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5255
5256 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395257 TestDelegate d;
5258 {
tommycli59a63432015-11-06 00:10:555259 std::string test_file = base::StringPrintf(
5260 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395261
[email protected]ceefd7fd2012-11-29 00:36:245262 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095263 TestURLRequestContext context(true);
5264 context.set_network_delegate(&network_delegate);
5265 context.Init();
[email protected]87a09a92011-07-14 15:50:505266
rhalavatib7bd7c792017-04-27 05:25:165267 std::unique_ptr<URLRequest> r(
5268 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5269 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195270 r->Start();
5271 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395272
Wez2a31b222018-06-07 22:07:155273 d.RunUntilComplete();
[email protected]aad63572011-05-24 20:14:395274
5275 EXPECT_EQ(1, d.response_started_count());
5276 EXPECT_FALSE(d.received_data_before_response());
5277 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505278 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395279 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505280 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5281 << "\"";
xunjielifb4da222016-07-14 18:38:595282 if (test_parameters[i] == 'S') {
5283 // When content length is smaller than both compressed length and
5284 // uncompressed length, HttpStreamParser might not read the full
5285 // response body.
5286 continue;
5287 }
5288 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395289 } else {
maksim.sisovb53724b52016-09-16 05:30:505290 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395291 << " Parameter = \"" << test_file << "\"";
5292 }
5293 }
5294 }
5295}
tommycli59a63432015-11-06 00:10:555296#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395297
[email protected]58e32bb2013-01-21 18:23:255298TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555299 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255300
tommycli59a63432015-11-06 00:10:555301 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455302 GURL original_url =
tommycli59a63432015-11-06 00:10:555303 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255304 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075305 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165306 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195307 req->Start();
Wez2a31b222018-06-07 22:07:155308 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255309
5310 EXPECT_EQ(1, d.response_started_count());
5311 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195312 EXPECT_EQ(destination_url, req->url());
5313 EXPECT_EQ(original_url, req->original_url());
5314 ASSERT_EQ(2U, req->url_chain().size());
5315 EXPECT_EQ(original_url, req->url_chain()[0]);
5316 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255317
5318 LoadTimingInfo load_timing_info_before_redirect;
5319 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5320 &load_timing_info_before_redirect));
5321 TestLoadTimingNotReused(load_timing_info_before_redirect,
5322 CONNECT_TIMING_HAS_DNS_TIMES);
5323
5324 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195325 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255326 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5327
5328 // Check that a new socket was used on redirect, since the server does not
5329 // supposed keep-alive sockets, and that the times before the redirect are
5330 // before the ones recorded for the second request.
5331 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5332 load_timing_info.socket_log_id);
5333 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5334 load_timing_info.connect_timing.connect_start);
5335}
5336
[email protected]8f1ac082011-04-19 21:14:135337TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555338 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135339
tommycli59a63432015-11-06 00:10:555340 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455341 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555342 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5343 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5344 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135345 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:075346 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165347 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195348 req->Start();
Wez2a31b222018-06-07 22:07:155349 d.RunUntilComplete();
[email protected]8f1ac082011-04-19 21:14:135350
5351 EXPECT_EQ(1, d.response_started_count());
5352 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195353 EXPECT_EQ(destination_url, req->url());
5354 EXPECT_EQ(original_url, req->original_url());
5355 ASSERT_EQ(3U, req->url_chain().size());
5356 EXPECT_EQ(original_url, req->url_chain()[0]);
5357 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5358 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135359}
5360
[email protected]abe1c4a2013-10-25 19:28:515361// First and second pieces of information logged by delegates to URLRequests.
5362const char kFirstDelegateInfo[] = "Wonderful delegate";
5363const char kSecondDelegateInfo[] = "Exciting delegate";
5364
5365// Logs delegate information to a URLRequest. The first string is logged
5366// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5367// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5368// another asynchronous call is used to clear the delegate information
5369// before calling a callback. The object then deletes itself.
5370class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5371 public:
David Benjamind1f287bf2018-06-12 01:57:205372 using Callback = base::OnceCallback<void()>;
[email protected]abe1c4a2013-10-25 19:28:515373
5374 // Each time delegate information is added to the URLRequest, the resulting
5375 // load state is checked. The expected load state after each request is
5376 // passed in as an argument.
5377 static void Run(URLRequest* url_request,
5378 LoadState expected_first_load_state,
5379 LoadState expected_second_load_state,
5380 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205381 Callback callback) {
tzik38f920a2018-08-01 04:41:205382 // base::MakeRefCounted<AsyncDelegateLogger> is unavailable here, since the
5383 // constructor of AsyncDelegateLogger is private.
5384 auto logger = base::WrapRefCounted(new AsyncDelegateLogger(
David Benjamind1f287bf2018-06-12 01:57:205385 url_request, expected_first_load_state, expected_second_load_state,
tzik38f920a2018-08-01 04:41:205386 expected_third_load_state, std::move(callback)));
[email protected]abe1c4a2013-10-25 19:28:515387 logger->Start();
5388 }
5389
5390 // Checks that the log entries, starting with log_position, contain the
5391 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5392 // recorded. Returns the index of entry after the expected number of
5393 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465394 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515395 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515396 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5397 if (log_position + 3 >= entries.size()) {
5398 ADD_FAILURE() << "Not enough log entries";
5399 return entries.size();
5400 }
5401 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005402 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5403 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075404 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515405 &delegate_info));
5406 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5407
5408 ++log_position;
mikecirone8b85c432016-09-08 19:11:005409 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5410 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515411
5412 ++log_position;
mikecirone8b85c432016-09-08 19:11:005413 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5414 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075415 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515416 &delegate_info));
5417 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5418
5419 ++log_position;
mikecirone8b85c432016-09-08 19:11:005420 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5421 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515422
5423 return log_position + 1;
5424 }
5425
5426 private:
5427 friend class base::RefCounted<AsyncDelegateLogger>;
5428
5429 AsyncDelegateLogger(URLRequest* url_request,
5430 LoadState expected_first_load_state,
5431 LoadState expected_second_load_state,
5432 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205433 Callback callback)
[email protected]abe1c4a2013-10-25 19:28:515434 : url_request_(url_request),
5435 expected_first_load_state_(expected_first_load_state),
5436 expected_second_load_state_(expected_second_load_state),
5437 expected_third_load_state_(expected_third_load_state),
David Benjamind1f287bf2018-06-12 01:57:205438 callback_(std::move(callback)) {}
[email protected]abe1c4a2013-10-25 19:28:515439
Chris Watkins7a41d3552017-12-01 02:13:275440 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515441
5442 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535443 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515444 LoadStateWithParam load_state = url_request_->GetLoadState();
5445 EXPECT_EQ(expected_first_load_state_, load_state.state);
5446 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455447 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155448 FROM_HERE,
5449 base::BindOnce(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515450 }
5451
5452 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535453 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515454 LoadStateWithParam load_state = url_request_->GetLoadState();
5455 EXPECT_EQ(expected_second_load_state_, load_state.state);
5456 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5457 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5458 } else {
5459 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5460 }
skyostil4891b25b2015-06-11 11:43:455461 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155462 FROM_HERE, base::BindOnce(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515463 }
5464
5465 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535466 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515467 LoadStateWithParam load_state = url_request_->GetLoadState();
5468 EXPECT_EQ(expected_third_load_state_, load_state.state);
5469 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085470 EXPECT_EQ(base::string16(), load_state.param);
David Benjamind1f287bf2018-06-12 01:57:205471 std::move(callback_).Run();
[email protected]abe1c4a2013-10-25 19:28:515472 }
5473
5474 URLRequest* url_request_;
5475 const int expected_first_load_state_;
5476 const int expected_second_load_state_;
5477 const int expected_third_load_state_;
David Benjamind1f287bf2018-06-12 01:57:205478 Callback callback_;
[email protected]abe1c4a2013-10-25 19:28:515479
5480 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5481};
5482
5483// NetworkDelegate that logs delegate information before a request is started,
5484// before headers are sent, when headers are read, and when auth information
5485// is requested. Uses AsyncDelegateLogger.
5486class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5487 public:
Chris Watkins7a41d3552017-12-01 02:13:275488 AsyncLoggingNetworkDelegate() = default;
5489 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515490
5491 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205492 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205493 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:205494 GURL* new_url) override {
David Benjamind1f287bf2018-06-12 01:57:205495 // TestNetworkDelegate always completes synchronously.
5496 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
5497 request, base::NullCallback(), new_url));
5498 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515499 }
5500
ryansturm2343cb62016-06-15 01:09:005501 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205502 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:005503 HttpRequestHeaders* headers) override {
David Benjamind1f287bf2018-06-12 01:57:205504 // TestNetworkDelegate always completes synchronously.
5505 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
5506 request, base::NullCallback(), headers));
5507 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515508 }
5509
dchengb03027d2014-10-21 12:00:205510 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515511 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205512 CompletionOnceCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515513 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165514 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135515 GURL* allowed_unsafe_redirect_url) override {
David Benjamind1f287bf2018-06-12 01:57:205516 // TestNetworkDelegate always completes synchronously.
5517 CHECK_NE(ERR_IO_PENDING,
5518 TestNetworkDelegate::OnHeadersReceived(
5519 request, base::NullCallback(), original_response_headers,
5520 override_response_headers, allowed_unsafe_redirect_url));
5521 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515522 }
5523
dchengb03027d2014-10-21 12:00:205524 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515525 URLRequest* request,
5526 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:205527 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:135528 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515529 AsyncDelegateLogger::Run(
David Benjamind1f287bf2018-06-12 01:57:205530 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5531 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5532 base::BindOnce(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5533 std::move(callback), credentials));
[email protected]abe1c4a2013-10-25 19:28:515534 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5535 }
5536
5537 private:
David Benjamind1f287bf2018-06-12 01:57:205538 static int RunCallbackAsynchronously(URLRequest* request,
5539 CompletionOnceCallback callback) {
5540 AsyncDelegateLogger::Run(request, LOAD_STATE_WAITING_FOR_DELEGATE,
5541 LOAD_STATE_WAITING_FOR_DELEGATE,
5542 LOAD_STATE_WAITING_FOR_DELEGATE,
5543 base::BindOnce(std::move(callback), OK));
[email protected]abe1c4a2013-10-25 19:28:515544 return ERR_IO_PENDING;
5545 }
5546
David Benjamind1f287bf2018-06-12 01:57:205547 static void SetAuthAndResume(AuthCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515548 AuthCredentials* credentials) {
5549 *credentials = AuthCredentials(kUser, kSecret);
David Benjamind1f287bf2018-06-12 01:57:205550 std::move(callback).Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
[email protected]abe1c4a2013-10-25 19:28:515551 }
5552
5553 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5554};
5555
5556// URLRequest::Delegate that logs delegate information when the headers
5557// are received, when each read completes, and during redirects. Uses
5558// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5559//
5560// Inherits from TestDelegate to reuse the TestDelegate code to handle
5561// advancing to the next step in most cases, as well as cancellation.
5562class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5563 public:
5564 enum CancelStage {
5565 NO_CANCEL = 0,
5566 CANCEL_ON_RECEIVED_REDIRECT,
5567 CANCEL_ON_RESPONSE_STARTED,
5568 CANCEL_ON_READ_COMPLETED
5569 };
5570
5571 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5572 : cancel_stage_(cancel_stage) {
5573 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5574 set_cancel_in_received_redirect(true);
5575 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5576 set_cancel_in_response_started(true);
5577 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5578 set_cancel_in_received_data(true);
5579 }
Chris Watkins7a41d3552017-12-01 02:13:275580 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515581
5582 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205583 void OnReceivedRedirect(URLRequest* request,
5584 const RedirectInfo& redirect_info,
5585 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515586 *defer_redirect = true;
5587 AsyncDelegateLogger::Run(
5588 request,
5589 LOAD_STATE_WAITING_FOR_DELEGATE,
5590 LOAD_STATE_WAITING_FOR_DELEGATE,
5591 LOAD_STATE_WAITING_FOR_DELEGATE,
5592 base::Bind(
5593 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595594 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515595 }
5596
maksim.sisov0f4aa142016-09-05 05:55:285597 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515598 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285599 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5600 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5601 base::Bind(
5602 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5603 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515604 }
5605
dchengb03027d2014-10-21 12:00:205606 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515607 AsyncDelegateLogger::Run(
5608 request,
5609 LOAD_STATE_IDLE,
5610 LOAD_STATE_IDLE,
5611 LOAD_STATE_IDLE,
5612 base::Bind(
5613 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5614 base::Unretained(this), request, bytes_read));
5615 }
5616
5617 private:
5618 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595619 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515620 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595621 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515622 // FollowDeferredRedirect should not be called after cancellation.
5623 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5624 return;
5625 if (!defer_redirect)
Chong Zhang7607f1f2018-06-01 20:52:205626 request->FollowDeferredRedirect(
5627 base::nullopt /* modified_request_headers */);
[email protected]abe1c4a2013-10-25 19:28:515628 }
5629
maksim.sisov0f4aa142016-09-05 05:55:285630 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515631 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285632 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515633 }
5634
5635 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5636 // The parent class continues the request.
5637 TestDelegate::OnReadCompleted(request, bytes_read);
5638 }
5639
5640 const CancelStage cancel_stage_;
5641
5642 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5643};
5644
5645// Tests handling of delegate info before a request starts.
5646TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555647 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515648
5649 TestDelegate request_delegate;
5650 TestURLRequestContext context(true);
5651 context.set_network_delegate(NULL);
5652 context.set_net_log(&net_log_);
5653 context.Init();
5654
5655 {
rhalavatib7bd7c792017-04-27 05:25:165656 std::unique_ptr<URLRequest> r(context.CreateRequest(
5657 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5658 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195659 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515660 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085661 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515662
5663 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195664 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515665 LOAD_STATE_WAITING_FOR_DELEGATE,
5666 LOAD_STATE_WAITING_FOR_DELEGATE,
5667 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195668 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515669
Wez2a31b222018-06-07 22:07:155670 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515671
[email protected]f7022f32014-08-21 16:32:195672 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505673 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515674 }
5675
mmenke43758e62015-05-04 21:09:465676 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515677 net_log_.GetEntries(&entries);
5678 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005679 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515680
5681 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5682
5683 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005684 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5685 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515686}
5687
5688// Tests handling of delegate info from a network delegate.
5689TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555690 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515691
5692 TestDelegate request_delegate;
5693 AsyncLoggingNetworkDelegate network_delegate;
5694 TestURLRequestContext context(true);
5695 context.set_network_delegate(&network_delegate);
5696 context.set_net_log(&net_log_);
5697 context.Init();
5698
5699 {
rhalavatib7bd7c792017-04-27 05:25:165700 std::unique_ptr<URLRequest> r(context.CreateRequest(
5701 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
5702 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195703 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515704 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085705 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515706
[email protected]f7022f32014-08-21 16:32:195707 r->Start();
Wez2a31b222018-06-07 22:07:155708 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515709
[email protected]f7022f32014-08-21 16:32:195710 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505711 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515712 EXPECT_EQ(1, network_delegate.created_requests());
5713 EXPECT_EQ(0, network_delegate.destroyed_requests());
5714 }
5715 EXPECT_EQ(1, network_delegate.destroyed_requests());
5716
5717 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465718 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515719 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155720 static const NetLogEventType kExpectedEvents[] = {
5721 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5722 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5723 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5724 };
5725 for (NetLogEventType event : kExpectedEvents) {
5726 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515727 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155728 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515729
5730 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5731 log_position + 1);
5732
5733 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155734 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005735 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515736 }
5737
mikecirone8b85c432016-09-08 19:11:005738 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5739 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515740}
5741
5742// Tests handling of delegate info from a network delegate in the case of an
5743// HTTP redirect.
5744TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555745 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515746
5747 TestDelegate request_delegate;
5748 AsyncLoggingNetworkDelegate network_delegate;
5749 TestURLRequestContext context(true);
5750 context.set_network_delegate(&network_delegate);
5751 context.set_net_log(&net_log_);
5752 context.Init();
5753
5754 {
danakj8522a25b2016-04-16 00:17:365755 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555756 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165757 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195758 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515759 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085760 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515761
[email protected]f7022f32014-08-21 16:32:195762 r->Start();
Wez2a31b222018-06-07 22:07:155763 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515764
[email protected]f7022f32014-08-21 16:32:195765 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505766 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515767 EXPECT_EQ(2, network_delegate.created_requests());
5768 EXPECT_EQ(0, network_delegate.destroyed_requests());
5769 }
5770 EXPECT_EQ(1, network_delegate.destroyed_requests());
5771
5772 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465773 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515774 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155775 static const NetLogEventType kExpectedEvents[] = {
5776 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5777 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5778 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5779 };
5780 for (NetLogEventType event : kExpectedEvents) {
5781 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515782 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155783 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515784
David Benjamin9776ca22018-06-13 00:00:155785 log_position =
5786 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:515787
5788 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155789 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005790 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515791 }
5792
5793 // The URLRequest::Delegate then gets informed about the redirect.
5794 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155795 entries, log_position + 1,
5796 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
mikecirone8b85c432016-09-08 19:11:005797 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515798
5799 // The NetworkDelegate logged information in the same three events as before.
David Benjamin9776ca22018-06-13 00:00:155800 for (NetLogEventType event : kExpectedEvents) {
5801 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515802 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155803 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515804
5805 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5806 log_position + 1);
5807
5808 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155809 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005810 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515811 }
5812
mikecirone8b85c432016-09-08 19:11:005813 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5814 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515815}
5816
5817// Tests handling of delegate info from a network delegate in the case of HTTP
5818// AUTH.
5819TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555820 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515821
5822 TestDelegate request_delegate;
5823 AsyncLoggingNetworkDelegate network_delegate;
5824 TestURLRequestContext context(true);
5825 context.set_network_delegate(&network_delegate);
5826 context.set_net_log(&net_log_);
5827 context.Init();
5828
5829 {
rhalavatib7bd7c792017-04-27 05:25:165830 std::unique_ptr<URLRequest> r(context.CreateRequest(
5831 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
5832 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195833 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515834 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085835 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515836
[email protected]f7022f32014-08-21 16:32:195837 r->Start();
Wez2a31b222018-06-07 22:07:155838 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515839
[email protected]f7022f32014-08-21 16:32:195840 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505841 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515842 EXPECT_EQ(1, network_delegate.created_requests());
5843 EXPECT_EQ(0, network_delegate.destroyed_requests());
5844 }
5845 EXPECT_EQ(1, network_delegate.destroyed_requests());
5846
5847 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465848 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515849 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155850 static const NetLogEventType kExpectedEvents[] = {
5851 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5852 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5853 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5854 NetLogEventType::NETWORK_DELEGATE_AUTH_REQUIRED,
5855 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5856 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5857 };
5858 for (NetLogEventType event : kExpectedEvents) {
5859 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515860 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155861 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515862
David Benjamin9776ca22018-06-13 00:00:155863 log_position =
5864 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:515865
5866 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155867 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005868 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515869 }
5870
mikecirone8b85c432016-09-08 19:11:005871 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5872 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515873}
5874
tommycli59a63432015-11-06 00:10:555875// TODO(svaldez): Update tests to use EmbeddedTestServer.
5876#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515877// Tests handling of delegate info from a URLRequest::Delegate.
5878TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555879 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555880 base::FilePath(kTestFilePath));
5881
5882 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515883
5884 AsyncLoggingUrlRequestDelegate request_delegate(
5885 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5886 TestURLRequestContext context(true);
5887 context.set_network_delegate(NULL);
5888 context.set_net_log(&net_log_);
5889 context.Init();
5890
5891 {
5892 // A chunked response with delays between chunks is used to make sure that
5893 // attempts by the URLRequest delegate to log information while reading the
5894 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485895 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515896 // that it occurs.
danakj8522a25b2016-04-16 00:17:365897 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555898 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:165899 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195900 LoadStateWithParam load_state = r->GetLoadState();
5901 r->Start();
Wez2a31b222018-06-07 22:07:155902 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515903
[email protected]f7022f32014-08-21 16:32:195904 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505905 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515906 }
5907
mmenke43758e62015-05-04 21:09:465908 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515909 net_log_.GetEntries(&entries);
5910
[email protected]1826a402014-01-08 15:40:485911 size_t log_position = 0;
5912
[email protected]abe1c4a2013-10-25 19:28:515913 // The delegate info should only have been logged on header complete. Other
5914 // times it should silently be ignored.
David Benjamin9776ca22018-06-13 00:00:155915 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5916 entries, 0, NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST));
mikecirone8b85c432016-09-08 19:11:005917 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155918 entries, log_position + 1,
5919 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
mikecirone8b85c432016-09-08 19:11:005920 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515921
David Benjamin9776ca22018-06-13 00:00:155922 log_position =
5923 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:515924
5925 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155926 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
5927 entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005928 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515929
mikecirone8b85c432016-09-08 19:11:005930 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5931 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515932 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
David Benjamin9776ca22018-06-13 00:00:155933 entries, log_position + 1,
5934 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED));
[email protected]abe1c4a2013-10-25 19:28:515935}
tommycli59a63432015-11-06 00:10:555936#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515937
5938// Tests handling of delegate info from a URLRequest::Delegate in the case of
5939// an HTTP redirect.
5940TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555941 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515942
5943 AsyncLoggingUrlRequestDelegate request_delegate(
5944 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5945 TestURLRequestContext context(true);
5946 context.set_network_delegate(NULL);
5947 context.set_net_log(&net_log_);
5948 context.Init();
5949
5950 {
danakj8522a25b2016-04-16 00:17:365951 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555952 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165953 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195954 LoadStateWithParam load_state = r->GetLoadState();
5955 r->Start();
Wez2a31b222018-06-07 22:07:155956 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515957
[email protected]f7022f32014-08-21 16:32:195958 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505959 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515960 }
5961
mmenke43758e62015-05-04 21:09:465962 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515963 net_log_.GetEntries(&entries);
5964
5965 // Delegate info should only have been logged in OnReceivedRedirect and
5966 // OnResponseStarted.
5967 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:155968 static const NetLogEventType kExpectedEvents[] = {
5969 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
5970 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
5971 };
5972 for (NetLogEventType event : kExpectedEvents) {
5973 SCOPED_TRACE(NetLog::EventTypeToString(event));
5974 log_position = ExpectLogContainsSomewhereAfter(entries, log_position, event,
5975 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515976
David Benjamin9776ca22018-06-13 00:00:155977 log_position =
5978 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:515979
5980 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155981 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005982 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515983 }
5984
mikecirone8b85c432016-09-08 19:11:005985 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5986 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515987}
5988
5989// Tests handling of delegate info from a URLRequest::Delegate in the case of
5990// an HTTP redirect, with cancellation at various points.
5991TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555992 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515993
5994 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5995 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5996 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5997 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5998 };
5999
David Benjamin9776ca22018-06-13 00:00:156000 for (auto cancel_stage : kCancelStages) {
6001 AsyncLoggingUrlRequestDelegate request_delegate(cancel_stage);
vishal.b62985ca92015-04-17 08:45:516002 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046003 TestURLRequestContext context(true);
[email protected]abe1c4a2013-10-25 19:28:516004 context.set_network_delegate(NULL);
6005 context.set_net_log(&net_log);
6006 context.Init();
6007
6008 {
danakj8522a25b2016-04-16 00:17:366009 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556010 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166011 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196012 LoadStateWithParam load_state = r->GetLoadState();
6013 r->Start();
Wez2a31b222018-06-07 22:07:156014 request_delegate.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506015 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
Wez2a31b222018-06-07 22:07:156016
6017 // Spin the message loop to run AsyncDelegateLogger task(s) posted after
6018 // the |request_delegate| completion task.
6019 base::RunLoop().RunUntilIdle();
[email protected]abe1c4a2013-10-25 19:28:516020 }
6021
mmenke43758e62015-05-04 21:09:466022 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516023 net_log.GetEntries(&entries);
6024
6025 // Delegate info is always logged in both OnReceivedRedirect and
6026 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6027 // OnResponseStarted delegate call is after cancellation, but logging is
6028 // still currently supported in that call.
6029 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156030 static const NetLogEventType kExpectedEvents[] = {
6031 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6032 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6033 };
6034 for (NetLogEventType event : kExpectedEvents) {
6035 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516036 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156037 entries, log_position, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516038
David Benjamin9776ca22018-06-13 00:00:156039 log_position =
6040 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516041
6042 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156043 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006044 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516045 }
6046
mikecirone8b85c432016-09-08 19:11:006047 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6048 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516049 }
6050}
6051
[email protected]847c0fa92012-11-06 16:37:426052namespace {
6053
6054const char kExtraHeader[] = "Allow-Snafu";
6055const char kExtraValue[] = "fubar";
6056
6057class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206058 void OnReceivedRedirect(URLRequest* request,
6059 const RedirectInfo& redirect_info,
6060 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596061 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426062 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6063 }
6064};
6065
6066} // namespace
6067
6068TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556069 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426070
tommycli59a63432015-11-06 00:10:556071 GURL destination_url =
6072 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6073 GURL original_url =
6074 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426075 RedirectWithAdditionalHeadersDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076076 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166077 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196078 req->Start();
Wez2a31b222018-06-07 22:07:156079 d.RunUntilComplete();
[email protected]847c0fa92012-11-06 16:37:426080
6081 std::string value;
[email protected]f7022f32014-08-21 16:32:196082 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426083 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6084 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196085 EXPECT_FALSE(req->is_pending());
6086 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426087 EXPECT_EQ(kExtraValue, d.data_received());
6088}
6089
[email protected]251a1b92012-11-13 11:01:096090namespace {
6091
6092const char kExtraHeaderToRemove[] = "To-Be-Removed";
6093
6094class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206095 void OnReceivedRedirect(URLRequest* request,
6096 const RedirectInfo& redirect_info,
6097 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596098 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096099 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6100 }
6101};
6102
6103} // namespace
6104
6105TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556106 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096107
tommycli59a63432015-11-06 00:10:556108 GURL destination_url = http_test_server()->GetURL(
6109 "/echoheader?" + std::string(kExtraHeaderToRemove));
6110 GURL original_url =
6111 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096112 RedirectWithHeaderRemovalDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076113 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166114 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196115 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6116 req->Start();
Wez2a31b222018-06-07 22:07:156117 d.RunUntilComplete();
[email protected]251a1b92012-11-13 11:01:096118
6119 std::string value;
[email protected]f7022f32014-08-21 16:32:196120 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096121 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196122 EXPECT_FALSE(req->is_pending());
6123 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096124 EXPECT_EQ("None", d.data_received());
6125}
6126
mmenke94f1bd92016-12-07 21:13:056127TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446128 TestDelegate d;
6129 {
Ryan Sleevib8449e02018-07-15 04:31:076130 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166131 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6132 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446133
[email protected]f7022f32014-08-21 16:32:196134 r->Start();
6135 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446136
[email protected]f7022f32014-08-21 16:32:196137 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446138
Wez2a31b222018-06-07 22:07:156139 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446140
6141 // We expect to receive OnResponseStarted even though the request has been
6142 // cancelled.
6143 EXPECT_EQ(1, d.response_started_count());
6144 EXPECT_EQ(0, d.bytes_received());
6145 EXPECT_FALSE(d.received_data_before_response());
6146 }
6147}
6148
mmenke94f1bd92016-12-07 21:13:056149TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556150 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446151
6152 TestDelegate d;
6153 {
Ryan Sleevib8449e02018-07-15 04:31:076154 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166155 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6156 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446157
6158 d.set_cancel_in_response_started(true);
6159
[email protected]f7022f32014-08-21 16:32:196160 r->Start();
6161 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446162
Wez2a31b222018-06-07 22:07:156163 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446164
6165 EXPECT_EQ(1, d.response_started_count());
6166 EXPECT_EQ(0, d.bytes_received());
6167 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506168 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446169 }
6170}
6171
mmenke94f1bd92016-12-07 21:13:056172TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556173 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446174
6175 TestDelegate d;
6176 {
Ryan Sleevib8449e02018-07-15 04:31:076177 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166178 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6179 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056180
6181 d.set_cancel_in_received_data(true);
6182
6183 r->Start();
6184 EXPECT_TRUE(r->is_pending());
6185
Wez2a31b222018-06-07 22:07:156186 d.RunUntilComplete();
mmenke94f1bd92016-12-07 21:13:056187
6188 EXPECT_EQ(1, d.response_started_count());
6189 EXPECT_NE(0, d.received_bytes_count());
6190 EXPECT_FALSE(d.received_data_before_response());
6191 EXPECT_EQ(ERR_ABORTED, d.request_status());
6192 }
6193}
6194
6195TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6196 ASSERT_TRUE(http_test_server()->Start());
6197
6198 TestDelegate d;
6199 {
6200 // This returns an empty response (With headers).
Ryan Sleevib8449e02018-07-15 04:31:076201 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166202 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6203 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446204
6205 d.set_cancel_in_received_data(true);
6206
[email protected]f7022f32014-08-21 16:32:196207 r->Start();
6208 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446209
Wez2a31b222018-06-07 22:07:156210 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446211
6212 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056213 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446214 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506215 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446216 }
6217}
6218
mmenke94f1bd92016-12-07 21:13:056219TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556220 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446221
6222 TestDelegate d;
6223 {
Ryan Sleevib8449e02018-07-15 04:31:076224 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166225 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6226 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446227
[email protected]f7022f32014-08-21 16:32:196228 r->Start();
6229 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446230
6231 // The request will be implicitly canceled when it is destroyed. The
6232 // test delegate must not post a quit message when this happens because
6233 // this test doesn't actually have a message loop. The quit message would
6234 // get put on this thread's message queue and the next test would exit
6235 // early, causing problems.
Wez0e717112018-06-18 23:09:226236 d.set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:446237 }
6238 // expect things to just cleanup properly.
6239
kimwjdalsl2bb4ff02015-12-16 22:06:026240 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446241 // message loop
6242 EXPECT_FALSE(d.received_data_before_response());
6243 EXPECT_EQ(0, d.bytes_received());
6244}
6245
mmenke94f1bd92016-12-07 21:13:056246TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556247 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446248
6249 // populate cache
6250 {
6251 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076252 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166253 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6254 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196255 r->Start();
Wez2a31b222018-06-07 22:07:156256 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506257 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446258 }
6259
6260 // cancel read from cache (see bug 990242)
6261 {
6262 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076263 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166264 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6265 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196266 r->Start();
6267 r->Cancel();
Wez2a31b222018-06-07 22:07:156268 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446269
maksim.sisovb53724b52016-09-16 05:30:506270 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446271 EXPECT_EQ(1, d.response_started_count());
6272 EXPECT_EQ(0, d.bytes_received());
6273 EXPECT_FALSE(d.received_data_before_response());
6274 }
6275}
6276
6277TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556278 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446279 HTTPUploadDataOperationTest("POST");
6280}
6281
6282TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556283 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446284 HTTPUploadDataOperationTest("PUT");
6285}
6286
6287TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556288 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446289
6290 TestDelegate d;
6291 {
Ryan Sleevib8449e02018-07-15 04:31:076292 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166293 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6294 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196295 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446296
[email protected]f7022f32014-08-21 16:32:196297 r->Start();
6298 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446299
Wez2a31b222018-06-07 22:07:156300 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446301
maksim.sisovb53724b52016-09-16 05:30:506302 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6303 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446304
6305 EXPECT_FALSE(d.received_data_before_response());
6306 EXPECT_TRUE(d.data_received().empty());
6307 }
6308}
6309
6310TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556311 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446312
6313 TestDelegate d;
6314 {
Ryan Sleevib8449e02018-07-15 04:31:076315 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166316 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6317 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196318 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446319
[email protected]6cdfd7f2013-02-08 20:40:156320 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196321 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026322 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446323
danakj8522a25b2016-04-16 00:17:366324 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446325
[email protected]6cdfd7f2013-02-08 20:40:156326 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196327 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476328 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446329 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196330 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146331 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076332 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046333 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6334 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446335
[email protected]f7022f32014-08-21 16:32:196336 r->Start();
6337 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446338
Wez2a31b222018-06-07 22:07:156339 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446340
avibf0746c2015-12-09 19:53:146341 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296342 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6343 ASSERT_LE(size64, std::numeric_limits<int>::max());
6344 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366345 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446346
[email protected]7600d0b2013-12-08 21:43:306347 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446348
maksim.sisovb53724b52016-09-16 05:30:506349 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6350 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446351
6352 EXPECT_FALSE(d.received_data_before_response());
6353
[email protected]329b68b2012-11-14 17:54:276354 EXPECT_EQ(size, d.bytes_received());
6355 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446356 }
6357}
6358
[email protected]999dd8c2013-11-12 06:45:546359TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556360 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546361
6362 TestDelegate d;
6363 {
Ryan Sleevib8449e02018-07-15 04:31:076364 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166365 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6366 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196367 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546368
danakj8522a25b2016-04-16 00:17:366369 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546370
Jeremy Roman0579ed62017-08-29 15:56:196371 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456372 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546373 base::FilePath(FILE_PATH_LITERAL(
6374 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076375 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046376 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6377 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546378
[email protected]f7022f32014-08-21 16:32:196379 r->Start();
6380 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546381
Wez2a31b222018-06-07 22:07:156382 d.RunUntilComplete();
[email protected]999dd8c2013-11-12 06:45:546383
[email protected]999dd8c2013-11-12 06:45:546384 EXPECT_TRUE(d.request_failed());
6385 EXPECT_FALSE(d.received_data_before_response());
6386 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506387 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546388 }
6389}
6390
mmenke56b0cbb912016-03-28 21:34:536391namespace {
6392
6393// Adds a standard set of data to an upload for chunked upload integration
6394// tests.
6395void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6396 writer->AppendData("a", 1, false);
6397 writer->AppendData("bcd", 3, false);
6398 writer->AppendData("this is a longer chunk than before.", 35, false);
6399 writer->AppendData("\r\n\r\n", 4, false);
6400 writer->AppendData("0", 1, false);
6401 writer->AppendData("2323", 4, true);
6402}
6403
6404// Checks that the upload data added in AddChunksToUpload() was echoed back from
6405// the server.
6406void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6407 // This should match the chunks sent by AddChunksToUpload().
6408 const std::string expected_data =
6409 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6410
maksim.sisovb53724b52016-09-16 05:30:506411 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6412 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536413
6414 EXPECT_FALSE(d->received_data_before_response());
6415
6416 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6417 EXPECT_EQ(expected_data, d->data_received());
6418}
6419
6420} // namespace
6421
[email protected]316c1e5e2012-09-12 15:17:446422TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556423 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446424
6425 TestDelegate d;
6426 {
Ryan Sleevib8449e02018-07-15 04:31:076427 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166428 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6429 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366430 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536431 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366432 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536433 upload_data_stream->CreateWriter();
6434 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196435 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536436 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196437 r->Start();
6438 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446439
Wez2a31b222018-06-07 22:07:156440 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446441
[email protected]f7022f32014-08-21 16:32:196442 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446443 }
6444}
6445
[email protected]329b68b2012-11-14 17:54:276446TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556447 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276448
6449 TestDelegate d;
6450 {
Ryan Sleevib8449e02018-07-15 04:31:076451 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166452 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6453 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366454 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536455 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366456 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536457 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046458 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196459 r->set_method("POST");
6460 r->Start();
6461 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536462 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156463 d.RunUntilComplete();
[email protected]329b68b2012-11-14 17:54:276464
[email protected]f7022f32014-08-21 16:32:196465 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276466 }
6467}
6468
Asanka Herathf05753e2018-08-16 17:38:206469TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556470 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446471
6472 TestDelegate d;
6473 {
Ryan Sleevib8449e02018-07-15 04:31:076474 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166475 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6476 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366477 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536478 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366479 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536480 upload_data_stream->CreateWriter();
6481 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196482 r->set_method("POST");
6483 r->Start();
6484 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446485
Asanka Herathf05753e2018-08-16 17:38:206486 // Pump messages until we start sending headers..
[email protected]255620da2013-08-19 13:14:296487 base::RunLoop().RunUntilIdle();
Asanka Herathf05753e2018-08-16 17:38:206488
6489 // And now wait for completion.
6490 base::RunLoop run_loop;
6491 d.set_on_complete(run_loop.QuitClosure());
mmenke56b0cbb912016-03-28 21:34:536492 AddDataToUpload(writer.get());
Asanka Herathf05753e2018-08-16 17:38:206493 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:446494
[email protected]f7022f32014-08-21 16:32:196495 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446496 }
6497}
6498
6499TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556500 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446501
6502 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076503 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166504 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6505 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196506 req->Start();
Wez2a31b222018-06-07 22:07:156507 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446508
[email protected]f7022f32014-08-21 16:32:196509 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446510
6511 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196512 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446513
6514 std::string header;
6515 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6516 EXPECT_EQ("private", header);
6517
6518 header.clear();
6519 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6520 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6521
6522 // The response has two "X-Multiple-Entries" headers.
6523 // This verfies our output has them concatenated together.
6524 header.clear();
6525 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6526 EXPECT_EQ("a, b", header);
6527}
6528
tommycli59a63432015-11-06 00:10:556529// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6530// security state. (see http://crbug.com/550977).
6531#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466532TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556533 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6534 https_test_server.SetSSLConfig(
6535 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6536 https_test_server.ServeFilesFromSourceDirectory(
6537 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466538 ASSERT_TRUE(https_test_server.Start());
6539
tommycli59a63432015-11-06 00:10:556540 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466541 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076542 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166543 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6544 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196545 request->Start();
Wez2a31b222018-06-07 22:07:156546 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466547
6548 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076549 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406550 TransportSecurityState::STSState sts_state;
6551 TransportSecurityState::PKPState pkp_state;
6552 EXPECT_TRUE(
6553 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6554 EXPECT_FALSE(
6555 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6556 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6557 sts_state.upgrade_mode);
6558 EXPECT_TRUE(sts_state.include_subdomains);
6559 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036560#if defined(OS_ANDROID)
6561 // Android's CertVerifyProc does not (yet) handle pins.
6562#else
martijnc0d6b622015-06-30 19:14:406563 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036564#endif
[email protected]37fd55fb2013-06-29 13:13:276565}
6566
estarka5da76702015-04-09 04:00:166567TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556568 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6569 https_test_server.ServeFilesFromSourceDirectory(
6570 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166571 ASSERT_TRUE(https_test_server.Start());
6572 // Make sure this test fails if the test server is changed to not
6573 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556574 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6575 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166576
6577 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076578 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166579 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6580 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166581 request->Start();
Wez2a31b222018-06-07 22:07:156582 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:166583 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076584 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406585 TransportSecurityState::STSState sts_state;
6586 EXPECT_FALSE(
6587 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166588}
6589
estark06e0dac2015-08-07 21:56:016590namespace {
Martijn Croonenb1383da2017-10-11 11:56:356591const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
Matt Mueller230996f12018-10-22 19:39:446592const char kPKPReportUri[] = "http://report-uri.preloaded.test/pkp";
6593const char kPKPHost[] = "with-report-uri-pkp.preloaded.test";
estark06e0dac2015-08-07 21:56:016594} // namespace
6595
Matt Mueller230996f12018-10-22 19:39:446596// Tests that reports get sent on PKP violations when a report-uri is set.
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516597TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
Matt Mueller230996f12018-10-22 19:39:446598 GURL report_uri(kPKPReportUri);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516599 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6600 https_test_server.SetSSLConfig(
6601 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6602 https_test_server.ServeFilesFromSourceDirectory(
6603 base::FilePath(kTestFilePath));
6604 ASSERT_TRUE(https_test_server.Start());
6605
Matt Mueller230996f12018-10-22 19:39:446606 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016607
6608 // Set up a pin for |test_server_hostname|.
6609 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446610 security_state.EnableStaticPinsForTesting();
6611 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016612
6613 MockCertificateReportSender mock_report_sender;
6614 security_state.SetReportSender(&mock_report_sender);
6615
6616 // Set up a MockCertVerifier to trigger a violation of the previously
6617 // set pin.
6618 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6619 ASSERT_TRUE(cert);
6620
6621 MockCertVerifier cert_verifier;
6622 CertVerifyResult verify_result;
6623 verify_result.verified_cert = cert;
6624 verify_result.is_issued_by_known_root = true;
6625 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446626 ASSERT_TRUE(
6627 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016628 verify_result.public_key_hashes.push_back(hash3);
6629 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6630
6631 TestNetworkDelegate network_delegate;
6632 TestURLRequestContext context(true);
6633 context.set_transport_security_state(&security_state);
6634 context.set_network_delegate(&network_delegate);
6635 context.set_cert_verifier(&cert_verifier);
6636 context.Init();
6637
6638 // Now send a request to trigger the violation.
6639 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366640 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446641 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166642 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016643 violating_request->Start();
Wez2a31b222018-06-07 22:07:156644 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016645
6646 // Check that a report was sent.
6647 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6648 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446649 EXPECT_EQ("application/json; charset=utf-8",
6650 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366651 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016652 base::JSONReader::Read(mock_report_sender.latest_report()));
6653 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086654 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016655 base::DictionaryValue* report_dict;
6656 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6657 std::string report_hostname;
6658 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6659 EXPECT_EQ(test_server_hostname, report_hostname);
6660}
6661
Matt Mueller230996f12018-10-22 19:39:446662// Tests that reports do not get sent on requests to static pkp hosts that
6663// don't have pin violations.
6664TEST_F(URLRequestTestHTTP, ProcessPKPWithNoViolation) {
tommycli59a63432015-11-06 00:10:556665 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6666 https_test_server.SetSSLConfig(
6667 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6668 https_test_server.ServeFilesFromSourceDirectory(
6669 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016670 ASSERT_TRUE(https_test_server.Start());
6671
Matt Mueller230996f12018-10-22 19:39:446672 std::string test_server_hostname = kPKPHost;
estark06e0dac2015-08-07 21:56:016673
6674 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446675 security_state.EnableStaticPinsForTesting();
6676 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
estark06e0dac2015-08-07 21:56:016677 MockCertificateReportSender mock_report_sender;
6678 security_state.SetReportSender(&mock_report_sender);
6679
Matt Mueller230996f12018-10-22 19:39:446680 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6681 ASSERT_TRUE(cert);
Hiroki Nakagawa4e4967bcb2018-10-11 04:09:516682 MockCertVerifier mock_cert_verifier;
Matt Mueller230996f12018-10-22 19:39:446683 CertVerifyResult verify_result;
6684 verify_result.verified_cert = cert;
6685 verify_result.is_issued_by_known_root = true;
6686 HashValue hash;
6687 // The expected value of GoodPin1 used by |test_default::kHSTSSource|.
6688 ASSERT_TRUE(
6689 hash.FromString("sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY="));
6690 verify_result.public_key_hashes.push_back(hash);
6691 mock_cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6692
6693 TestNetworkDelegate network_delegate;
estark06e0dac2015-08-07 21:56:016694 TestURLRequestContext context(true);
6695 context.set_transport_security_state(&security_state);
6696 context.set_network_delegate(&network_delegate);
6697 context.set_cert_verifier(&mock_cert_verifier);
estark06e0dac2015-08-07 21:56:016698 context.Init();
6699
6700 // Now send a request that does not trigger the violation.
6701 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366702 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446703 https_test_server.GetURL(test_server_hostname, "/simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166704 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016705 request->Start();
Wez2a31b222018-06-07 22:07:156706 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016707
Matt Mueller230996f12018-10-22 19:39:446708 // Check that the request succeeded, a report was not sent and the pkp was
6709 // not bypassed.
6710 EXPECT_EQ(OK, d.request_status());
estark06e0dac2015-08-07 21:56:016711 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6712 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
Matt Mueller230996f12018-10-22 19:39:446713 TransportSecurityState::STSState sts_state;
martijnc0d6b622015-06-30 19:14:406714 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:446715 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
6716 &sts_state, &pkp_state));
6717 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
6718 EXPECT_FALSE(request->ssl_info().pkp_bypassed);
estarka5da76702015-04-09 04:00:166719}
6720
dadriandf302c42016-06-10 18:48:596721TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6722 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6723 https_test_server.SetSSLConfig(
6724 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6725 https_test_server.ServeFilesFromSourceDirectory(
6726 base::FilePath(kTestFilePath));
6727 ASSERT_TRUE(https_test_server.Start());
6728
6729 // Set up a MockCertVerifier to be a local root that violates the pin
6730 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6731 ASSERT_TRUE(cert);
6732
6733 MockCertVerifier cert_verifier;
6734 CertVerifyResult verify_result;
6735 verify_result.verified_cert = cert;
6736 verify_result.is_issued_by_known_root = false;
6737 HashValue hash;
6738 ASSERT_TRUE(
6739 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6740 verify_result.public_key_hashes.push_back(hash);
6741 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
dadriandf302c42016-06-10 18:48:596742
Matt Mueller230996f12018-10-22 19:39:446743 std::string test_server_hostname = kPKPHost;
dadriandf302c42016-06-10 18:48:596744
Matt Mueller230996f12018-10-22 19:39:446745 // Set up PKP
dadriandf302c42016-06-10 18:48:596746 TransportSecurityState security_state;
Matt Mueller230996f12018-10-22 19:39:446747 security_state.EnableStaticPinsForTesting();
6748 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
6749 MockCertificateReportSender mock_report_sender;
6750 security_state.SetReportSender(&mock_report_sender);
dadriandf302c42016-06-10 18:48:596751
6752 TestNetworkDelegate network_delegate;
6753 TestURLRequestContext context(true);
6754 context.set_transport_security_state(&security_state);
6755 context.set_network_delegate(&network_delegate);
6756 context.set_cert_verifier(&cert_verifier);
6757 context.Init();
6758
6759 TestDelegate d;
6760 std::unique_ptr<URLRequest> request(context.CreateRequest(
Matt Mueller230996f12018-10-22 19:39:446761 https_test_server.GetURL(test_server_hostname, "/simple.html"),
6762 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:596763 request->Start();
Wez2a31b222018-06-07 22:07:156764 d.RunUntilComplete();
dadriandf302c42016-06-10 18:48:596765
Matt Mueller230996f12018-10-22 19:39:446766 // Check that the request succeeded, a report was not sent and the PKP was
6767 // bypassed.
6768 EXPECT_EQ(OK, d.request_status());
6769 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6770 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6771 TransportSecurityState::STSState sts_state;
dadriandf302c42016-06-10 18:48:596772 TransportSecurityState::PKPState pkp_state;
Matt Mueller230996f12018-10-22 19:39:446773 EXPECT_TRUE(security_state.GetStaticDomainState(test_server_hostname,
6774 &sts_state, &pkp_state));
6775 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
dadriandf302c42016-06-10 18:48:596776 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6777}
6778
[email protected]242d8562012-10-30 21:20:466779TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556780 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6781 https_test_server.SetSSLConfig(
6782 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6783 https_test_server.ServeFilesFromSourceDirectory(
6784 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466785 ASSERT_TRUE(https_test_server.Start());
6786
tommycli59a63432015-11-06 00:10:556787 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166788
[email protected]242d8562012-10-30 21:20:466789 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:076790 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:556791 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166792 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196793 request->Start();
Wez2a31b222018-06-07 22:07:156794 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466795
6796 // We should have set parameters from the first header, not the second.
6797 TransportSecurityState* security_state =
Ryan Sleevib8449e02018-07-15 04:31:076798 default_context().transport_security_state();
martijnc0d6b622015-06-30 19:14:406799 TransportSecurityState::STSState sts_state;
6800 EXPECT_TRUE(
6801 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6802 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6803 sts_state.upgrade_mode);
6804 EXPECT_FALSE(sts_state.include_subdomains);
6805 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466806}
6807
estark1614475f2016-03-10 03:46:476808// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6809// called.
6810class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6811 public:
6812 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:276813 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:476814
6815 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6816 const GURL& report_uri,
estarkae028b462017-06-20 23:25:016817 base::Time expiration,
estarkbf1b52962017-05-05 17:05:256818 const X509Certificate* validated_certificate_chain,
6819 const X509Certificate* served_certificate_chain,
6820 const SignedCertificateTimestampAndStatusList&
6821 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:476822 num_failures_++;
6823 }
6824
6825 uint32_t num_failures() { return num_failures_; }
6826
6827 private:
6828 uint32_t num_failures_;
6829};
6830
Emily Stark627238f2017-11-29 03:29:546831// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:476832// for every certificate.
6833class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6834 public:
6835 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:546836 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:276837 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:476838
Emily Stark627238f2017-11-29 03:29:546839 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:476840 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:236841 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:206842 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:476843 return default_result_;
6844 }
6845
Emily Stark627238f2017-11-29 03:29:546846 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:476847 default_result_ = default_result;
6848 }
6849
6850 private:
Emily Stark627238f2017-11-29 03:29:546851 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:476852};
6853
Emily Stark4cfecf072017-08-08 01:05:516854// Tests that Expect CT headers for the preload list are processed correctly.
6855TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:356856 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
6857
estark1614475f2016-03-10 03:46:476858 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6859 https_test_server.SetSSLConfig(
6860 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6861 https_test_server.ServeFilesFromSourceDirectory(
6862 base::FilePath(kTestFilePath));
6863 ASSERT_TRUE(https_test_server.Start());
6864
6865 MockExpectCTReporter reporter;
6866 TransportSecurityState transport_security_state;
6867 transport_security_state.enable_static_expect_ct_ = true;
6868 transport_security_state.SetExpectCTReporter(&reporter);
6869
6870 // Set up a MockCertVerifier to accept the certificate that the server sends.
6871 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6872 ASSERT_TRUE(cert);
6873 MockCertVerifier cert_verifier;
6874 CertVerifyResult verify_result;
6875 verify_result.verified_cert = cert;
6876 verify_result.is_issued_by_known_root = true;
6877 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6878
rsleevi22cae1672016-12-28 01:53:366879 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
6880 // CT violation.
6881 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:476882 MockCTPolicyEnforcer ct_policy_enforcer;
6883 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:546884 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:476885
6886 TestNetworkDelegate network_delegate;
6887 // Use a MockHostResolver (which by default maps all hosts to
6888 // 127.0.0.1) so that the request can be sent to a site on the Expect
6889 // CT preload list.
6890 MockHostResolver host_resolver;
6891 TestURLRequestContext context(true);
6892 context.set_host_resolver(&host_resolver);
6893 context.set_transport_security_state(&transport_security_state);
6894 context.set_network_delegate(&network_delegate);
6895 context.set_cert_verifier(&cert_verifier);
6896 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:466897 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:476898 context.Init();
6899
6900 // Now send a request to trigger the violation.
6901 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:516902 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:476903 GURL::Replacements replace_host;
6904 replace_host.SetHostStr(kExpectCTStaticHostname);
6905 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:166906 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
6907 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:476908 violating_request->Start();
Wez2a31b222018-06-07 22:07:156909 d.RunUntilComplete();
estark1614475f2016-03-10 03:46:476910
6911 EXPECT_EQ(1u, reporter.num_failures());
6912}
Emily Stark4cfecf072017-08-08 01:05:516913
6914// Tests that Expect CT HTTP headers are processed correctly.
6915TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6916 base::test::ScopedFeatureList feature_list;
6917 feature_list.InitAndEnableFeature(
6918 TransportSecurityState::kDynamicExpectCTFeature);
6919
6920 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6921 https_test_server.SetSSLConfig(
6922 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6923 https_test_server.ServeFilesFromSourceDirectory(
6924 base::FilePath(kTestFilePath));
6925 ASSERT_TRUE(https_test_server.Start());
6926
6927 MockExpectCTReporter reporter;
6928 TransportSecurityState transport_security_state;
6929 transport_security_state.SetExpectCTReporter(&reporter);
6930
6931 // Set up a MockCertVerifier to accept the certificate that the server sends.
6932 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6933 ASSERT_TRUE(cert);
6934 MockCertVerifier cert_verifier;
6935 CertVerifyResult verify_result;
6936 verify_result.verified_cert = cert;
6937 verify_result.is_issued_by_known_root = true;
6938 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6939
6940 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
6941 // compliance.
6942 DoNothingCTVerifier ct_verifier;
6943 MockCTPolicyEnforcer ct_policy_enforcer;
6944 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:546945 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:516946
6947 TestNetworkDelegate network_delegate;
6948 // Use a MockHostResolver (which by default maps all hosts to
6949 // 127.0.0.1).
6950 MockHostResolver host_resolver;
6951 TestURLRequestContext context(true);
6952 context.set_host_resolver(&host_resolver);
6953 context.set_transport_security_state(&transport_security_state);
6954 context.set_network_delegate(&network_delegate);
6955 context.set_cert_verifier(&cert_verifier);
6956 context.set_cert_transparency_verifier(&ct_verifier);
6957 context.set_ct_policy_enforcer(&ct_policy_enforcer);
6958 context.Init();
6959
6960 // Now send a request to trigger the header processing.
6961 TestDelegate d;
6962 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6963 std::unique_ptr<URLRequest> request(context.CreateRequest(
6964 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
6965 request->Start();
Wez2a31b222018-06-07 22:07:156966 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:516967
6968 TransportSecurityState::ExpectCTState state;
6969 ASSERT_TRUE(
6970 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
6971 EXPECT_TRUE(state.enforce);
6972 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
6973}
6974
6975// Tests that if multiple Expect CT HTTP headers are sent, they are all
6976// processed.
6977TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
6978 base::test::ScopedFeatureList feature_list;
6979 feature_list.InitAndEnableFeature(
6980 TransportSecurityState::kDynamicExpectCTFeature);
6981
6982 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6983 https_test_server.SetSSLConfig(
6984 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6985 https_test_server.ServeFilesFromSourceDirectory(
6986 base::FilePath(kTestFilePath));
6987 ASSERT_TRUE(https_test_server.Start());
6988
6989 MockExpectCTReporter reporter;
6990 TransportSecurityState transport_security_state;
6991 transport_security_state.SetExpectCTReporter(&reporter);
6992
6993 // Set up a MockCertVerifier to accept the certificate that the server sends.
6994 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6995 ASSERT_TRUE(cert);
6996 MockCertVerifier cert_verifier;
6997 CertVerifyResult verify_result;
6998 verify_result.verified_cert = cert;
6999 verify_result.is_issued_by_known_root = true;
7000 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7001
7002 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7003 // compliance.
7004 DoNothingCTVerifier ct_verifier;
7005 MockCTPolicyEnforcer ct_policy_enforcer;
7006 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547007 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517008
7009 TestNetworkDelegate network_delegate;
7010 // Use a MockHostResolver (which by default maps all hosts to
7011 // 127.0.0.1).
7012 MockHostResolver host_resolver;
7013 TestURLRequestContext context(true);
7014 context.set_host_resolver(&host_resolver);
7015 context.set_transport_security_state(&transport_security_state);
7016 context.set_network_delegate(&network_delegate);
7017 context.set_cert_verifier(&cert_verifier);
7018 context.set_cert_transparency_verifier(&ct_verifier);
7019 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7020 context.Init();
7021
7022 // Now send a request to trigger the header processing.
7023 TestDelegate d;
7024 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7025 std::unique_ptr<URLRequest> request(context.CreateRequest(
7026 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7027 request->Start();
Wez2a31b222018-06-07 22:07:157028 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517029
7030 TransportSecurityState::ExpectCTState state;
7031 ASSERT_TRUE(
7032 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7033 EXPECT_TRUE(state.enforce);
7034 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7035}
7036
mmenkefd9d15c2017-06-29 13:45:547037#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477038
[email protected]316c1e5e2012-09-12 15:17:447039TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557040 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447041
7042 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077043 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557044 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167045 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197046 req->Start();
Wez2a31b222018-06-07 22:07:157047 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447048
7049 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197050 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447051 EXPECT_EQ("text/html", mime_type);
7052
7053 std::string charset;
[email protected]f7022f32014-08-21 16:32:197054 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447055 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197056 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447057}
7058
[email protected]02494ec2014-05-07 15:05:297059TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347060 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347061 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347062 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027063 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347064
7065 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507066 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347067}
7068
brettwa1228ebb2016-10-28 03:51:347069#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297070TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7071 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7072 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457073 FileProtocolHandler file_protocol_handler(
7074 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297075 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7076
7077 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507078 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297079}
7080
[email protected]588614c22013-08-16 00:09:027081TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557082 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447083
7084 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077085 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557086 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167087 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197088 req->Start();
Wez2a31b222018-06-07 22:07:157089 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447090
maksim.sisovb53724b52016-09-16 05:30:507091 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307092
7093 // The redirect should have been rejected before reporting it to the caller.
7094 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447095}
brettwa1228ebb2016-10-28 03:51:347096#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447097
[email protected]588614c22013-08-16 00:09:027098TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557099 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027100
7101 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077102 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557103 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167104 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197105 req->Start();
Wez2a31b222018-06-07 22:07:157106 d.RunUntilComplete();
[email protected]588614c22013-08-16 00:09:027107
maksim.sisovb53724b52016-09-16 05:30:507108 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307109
7110 // The redirect should have been rejected before reporting it to the
7111 // caller. See https://crbug.com/723796
7112 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027113}
7114
davidbend894710b2017-06-06 19:28:307115// Test that redirects to invalid URLs are rejected. See
7116// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447117TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557118 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447119
7120 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077121 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557122 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167123 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197124 req->Start();
Wez2a31b222018-06-07 22:07:157125 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447126
davidbend894710b2017-06-06 19:28:307127 EXPECT_EQ(1, d.response_started_count());
7128 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7129
7130 // The redirect should have been rejected before reporting it to the caller.
7131 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447132}
7133
[email protected]e50efea2014-03-24 18:41:007134// Make sure redirects are cached, despite not reading their bodies.
7135TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557136 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007137 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557138 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007139
7140 {
7141 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077142 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167143 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197144 req->Start();
Wez2a31b222018-06-07 22:07:157145 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507146 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007147 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557148 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007149 }
7150
7151 {
7152 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077153 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167154 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197155 req->Start();
Wez0e717112018-06-18 23:09:227156 d.RunUntilRedirect();
[email protected]e50efea2014-03-24 18:41:007157
7158 EXPECT_EQ(1, d.received_redirect_count());
7159 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197160 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007161
Chong Zhang7607f1f2018-06-01 20:52:207162 req->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:157163 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007164 EXPECT_EQ(1, d.received_redirect_count());
7165 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507166 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557167 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007168 }
7169}
7170
7171// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7172// when the headers are read, since the body won't have been read.
7173TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557174 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007175 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557176 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007177
7178 {
7179 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557180 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007181 default_network_delegate_.set_redirect_on_headers_received_url(
7182 redirect_to_url);
7183
7184 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077185 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167186 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197187 req->Start();
Wez2a31b222018-06-07 22:07:157188 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507189 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007190 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197191 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007192 }
7193
7194 {
7195 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077196 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167197 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197198 req->Start();
Wez2a31b222018-06-07 22:07:157199 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007200
maksim.sisovb53724b52016-09-16 05:30:507201 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197202 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007203 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197204 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007205 }
7206}
7207
[email protected]5f714132014-03-26 10:41:167208// Tests that redirection to an unsafe URL is allowed when it has been marked as
7209// safe.
7210TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557211 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167212
7213 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7214 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7215 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7216
7217 TestDelegate d;
7218 {
Ryan Sleevib8449e02018-07-15 04:31:077219 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167220 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7221 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167222
[email protected]f7022f32014-08-21 16:32:197223 r->Start();
Wez2a31b222018-06-07 22:07:157224 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167225
maksim.sisovb53724b52016-09-16 05:30:507226 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197227 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197228 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167229 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7230 }
7231}
7232
7233// Tests that a redirect to a different unsafe URL is blocked, even after adding
7234// some other URL to the whitelist.
7235TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557236 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167237
7238 GURL unsafe_url("data:text/html,something");
7239 GURL different_unsafe_url("data:text/html,something-else");
7240 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7241 default_network_delegate_.set_allowed_unsafe_redirect_url(
7242 different_unsafe_url);
7243
7244 TestDelegate d;
7245 {
Ryan Sleevib8449e02018-07-15 04:31:077246 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167247 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7248 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167249
[email protected]f7022f32014-08-21 16:32:197250 r->Start();
Wez2a31b222018-06-07 22:07:157251 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167252
maksim.sisovb53724b52016-09-16 05:30:507253 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307254
7255 // The redirect should have been rejected before reporting it to the caller.
7256 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167257 }
7258}
7259
[email protected]5f714132014-03-26 10:41:167260// Redirects from an URL with fragment to an unsafe URL with fragment should
7261// be allowed, and the reference fragment of the target URL should be preserved.
7262TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557263 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167264
tommycli59a63432015-11-06 00:10:557265 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167266 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7267 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7268
7269 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7270 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7271
7272 TestDelegate d;
7273 {
Ryan Sleevib8449e02018-07-15 04:31:077274 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167275 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167276
[email protected]f7022f32014-08-21 16:32:197277 r->Start();
Wez2a31b222018-06-07 22:07:157278 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167279
[email protected]f7022f32014-08-21 16:32:197280 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507281 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197282 EXPECT_EQ(original_url, r->original_url());
7283 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167284 }
7285}
7286
7287// When a delegate has specified a safe redirect URL, but it does not match the
7288// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147289TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557290 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167291
tommycli59a63432015-11-06 00:10:557292 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167293 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557294 GURL redirect_url(http_test_server()->GetURL("/target"));
7295 GURL expected_redirect_url(
7296 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167297
7298 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7299 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7300
7301 TestDelegate d;
7302 {
Ryan Sleevib8449e02018-07-15 04:31:077303 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167304 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167305
[email protected]f7022f32014-08-21 16:32:197306 r->Start();
Wez2a31b222018-06-07 22:07:157307 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:167308
[email protected]f7022f32014-08-21 16:32:197309 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507310 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197311 EXPECT_EQ(original_url, r->original_url());
7312 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167313 }
7314}
7315
[email protected]f878230e2014-04-03 15:36:147316// When a delegate has specified a safe redirect URL, assume that the redirect
7317// URL should not be changed. In particular, the reference fragment should not
7318// be modified.
7319TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557320 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147321
tommycli59a63432015-11-06 00:10:557322 GURL original_url(
7323 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147324 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7325
7326 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7327 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7328
7329 TestDelegate d;
7330 {
Ryan Sleevib8449e02018-07-15 04:31:077331 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167332 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147333
[email protected]f7022f32014-08-21 16:32:197334 r->Start();
Wez2a31b222018-06-07 22:07:157335 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147336
[email protected]f7022f32014-08-21 16:32:197337 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507338 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197339 EXPECT_EQ(original_url, r->original_url());
7340 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147341 }
7342}
7343
7344// When a URLRequestRedirectJob is created, the redirection must be followed and
7345// the reference fragment of the target URL must not be modified.
7346TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557347 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147348
tommycli59a63432015-11-06 00:10:557349 GURL original_url(
7350 http_test_server()->GetURL("/original#should-not-be-appended"));
7351 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147352
7353 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077354 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167355 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147356
danakj8522a25b2016-04-16 00:17:367357 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197358 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427359 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7360 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:147361
[email protected]f7022f32014-08-21 16:32:197362 r->Start();
Wez2a31b222018-06-07 22:07:157363 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:147364
maksim.sisovb53724b52016-09-16 05:30:507365 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197366 EXPECT_EQ(original_url, r->original_url());
7367 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147368}
7369
lizeb5120f6dc2016-02-19 09:29:447370TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
7371 ASSERT_TRUE(http_test_server()->Start());
7372
7373 const std::string referrer("foobar://totally.legit.referrer");
7374 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077375 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167376 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7377 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:447378 req->SetReferrer(referrer);
7379 req->Start();
Wez2a31b222018-06-07 22:07:157380 d.RunUntilComplete();
lizeb5120f6dc2016-02-19 09:29:447381
7382 EXPECT_EQ(std::string("None"), d.data_received());
7383}
7384
[email protected]316c1e5e2012-09-12 15:17:447385TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:557386 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447387
7388 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077389 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167390 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7391 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197392 req->SetReferrer("http://user:[email protected]/");
7393 req->Start();
Wez2a31b222018-06-07 22:07:157394 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447395
7396 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
7397}
7398
[email protected]99ecf6e2013-04-10 22:46:137399TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:557400 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137401
7402 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077403 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167404 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7405 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197406 req->SetReferrer("http://foo.com/test#fragment");
7407 req->Start();
Wez2a31b222018-06-07 22:07:157408 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:137409
7410 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
7411}
7412
7413TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:557414 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137415
7416 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077417 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167418 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7419 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197420 req->SetReferrer("http://foo.com/test#fragment");
7421 req->SetReferrer("");
7422 req->Start();
Wez2a31b222018-06-07 22:07:157423 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:137424
7425 EXPECT_EQ(std::string("None"), d.data_received());
7426}
7427
[email protected]316c1e5e2012-09-12 15:17:447428TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:557429 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447430
7431 TestDelegate d;
7432 {
7433 d.set_cancel_in_received_redirect(true);
Ryan Sleevib8449e02018-07-15 04:31:077434 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167435 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7436 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197437 req->Start();
Wez2a31b222018-06-07 22:07:157438 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447439
7440 EXPECT_EQ(1, d.response_started_count());
7441 EXPECT_EQ(0, d.bytes_received());
7442 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507443 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447444 }
7445}
7446
7447TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:557448 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447449
7450 TestDelegate d;
7451 {
tommycli59a63432015-11-06 00:10:557452 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:077453 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167454 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047455
[email protected]f7022f32014-08-21 16:32:197456 req->Start();
Wez0e717112018-06-18 23:09:227457 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:447458
7459 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:237460 EXPECT_TRUE(d.have_full_request_headers());
7461 CheckFullRequestHeaders(d.full_request_headers(), test_url);
7462 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:447463
Chong Zhang7607f1f2018-06-01 20:52:207464 req->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:157465 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447466
7467 EXPECT_EQ(1, d.response_started_count());
7468 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507469 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447470
[email protected]6cdfd7f2013-02-08 20:40:157471 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:197472 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477473 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:447474 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7475
7476 std::string contents;
[email protected]82f84b92013-08-30 18:23:507477 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:447478 EXPECT_EQ(contents, d.data_received());
7479 }
7480}
7481
[email protected]79e1fd62013-06-20 06:50:047482TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:557483 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:047484
7485 TestDelegate d;
7486 {
tommycli59a63432015-11-06 00:10:557487 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:077488 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167489 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047490
7491 EXPECT_FALSE(d.have_full_request_headers());
7492
[email protected]f7022f32014-08-21 16:32:197493 req->Start();
Wez0e717112018-06-18 23:09:227494 d.RunUntilRedirect();
[email protected]79e1fd62013-06-20 06:50:047495
7496 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:047497
Chong Zhang7607f1f2018-06-01 20:52:207498 req->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:157499 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:047500
tommycli59a63432015-11-06 00:10:557501 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:047502 EXPECT_EQ(1, d.response_started_count());
7503 EXPECT_TRUE(d.have_full_request_headers());
7504 CheckFullRequestHeaders(d.full_request_headers(), target_url);
7505 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507506 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:047507
7508 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:197509 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477510 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:047511 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7512
7513 std::string contents;
[email protected]82f84b92013-08-30 18:23:507514 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:047515 EXPECT_EQ(contents, d.data_received());
7516 }
7517}
7518
Chong Zhang7607f1f2018-06-01 20:52:207519TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedRequestHeaders) {
7520 ASSERT_TRUE(http_test_server()->Start());
7521
7522 TestDelegate d;
7523 {
Chong Zhang7607f1f2018-06-01 20:52:207524 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:077525 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Chong Zhang7607f1f2018-06-01 20:52:207526 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7527
7528 // Set initial headers for the request.
7529 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
7530 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
7531
7532 req->Start();
Wez0e717112018-06-18 23:09:227533 d.RunUntilRedirect();
Chong Zhang7607f1f2018-06-01 20:52:207534
7535 // Initial request should only have initial headers.
7536 EXPECT_EQ(1, d.received_redirect_count());
7537 EXPECT_TRUE(d.have_full_request_headers());
7538 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
7539 std::string sent_value;
7540 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
7541 EXPECT_EQ("Value1", sent_value);
7542 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
7543 EXPECT_EQ("Value2", sent_value);
7544 EXPECT_FALSE(sent_headers1.GetHeader("Header3", &sent_value));
7545 d.ClearFullRequestHeaders();
7546
7547 // Overwrite Header2 and add Header3.
7548 net::HttpRequestHeaders modified_request_headers;
7549 modified_request_headers.SetHeader("Header2", "");
7550 modified_request_headers.SetHeader("Header3", "Value3");
7551
7552 req->FollowDeferredRedirect(modified_request_headers);
Wez2a31b222018-06-07 22:07:157553 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:207554
7555 EXPECT_EQ(1, d.response_started_count());
7556 EXPECT_FALSE(d.received_data_before_response());
7557 EXPECT_EQ(OK, d.request_status());
7558
7559 // Redirected request should also have modified headers.
7560 EXPECT_TRUE(d.have_full_request_headers());
7561 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
7562 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
7563 EXPECT_EQ("Value1", sent_value);
7564 EXPECT_TRUE(sent_headers2.GetHeader("Header2", &sent_value));
7565 EXPECT_EQ("", sent_value);
7566 EXPECT_TRUE(sent_headers2.GetHeader("Header3", &sent_value));
7567 EXPECT_EQ("Value3", sent_value);
7568 }
7569}
7570
[email protected]316c1e5e2012-09-12 15:17:447571TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:557572 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447573
7574 TestDelegate d;
7575 {
Ryan Sleevib8449e02018-07-15 04:31:077576 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167577 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7578 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197579 req->Start();
Wez0e717112018-06-18 23:09:227580 d.RunUntilRedirect();
[email protected]316c1e5e2012-09-12 15:17:447581
7582 EXPECT_EQ(1, d.received_redirect_count());
7583
[email protected]f7022f32014-08-21 16:32:197584 req->Cancel();
Wez2a31b222018-06-07 22:07:157585 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447586
7587 EXPECT_EQ(1, d.response_started_count());
7588 EXPECT_EQ(0, d.bytes_received());
7589 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507590 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447591 }
7592}
7593
7594TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:557595 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447596
[email protected]3b23a222013-05-15 21:33:257597 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:447598 {
7599 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077600 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557601 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167602 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447603 HttpRequestHeaders headers;
7604 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197605 req->SetExtraRequestHeaders(headers);
7606 req->Start();
Wez2a31b222018-06-07 22:07:157607 d.RunUntilComplete();
[email protected]3b23a222013-05-15 21:33:257608
7609 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197610 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257611 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447612 }
7613
[email protected]3b23a222013-05-15 21:33:257614 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:447615 {
7616 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077617 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557618 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167619 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447620 HttpRequestHeaders headers;
7621 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197622 req->SetExtraRequestHeaders(headers);
7623 req->Start();
Wez2a31b222018-06-07 22:07:157624 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447625
[email protected]f7022f32014-08-21 16:32:197626 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257627
7628 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197629 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257630 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:447631 }
7632
[email protected]3b23a222013-05-15 21:33:257633 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:447634 {
7635 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077636 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557637 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167638 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447639 HttpRequestHeaders headers;
7640 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:197641 req->SetExtraRequestHeaders(headers);
7642 req->Start();
Wez2a31b222018-06-07 22:07:157643 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447644
[email protected]f7022f32014-08-21 16:32:197645 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257646
7647 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197648 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257649 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447650 }
7651}
7652
7653TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:557654 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447655
7656 // populate the cache
7657 {
7658 TestDelegate d;
7659 d.set_credentials(AuthCredentials(kUser, kSecret));
7660
Ryan Sleevib8449e02018-07-15 04:31:077661 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167662 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7663 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197664 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447665
Wez2a31b222018-06-07 22:07:157666 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447667
7668 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7669 }
7670
7671 // repeat request with end-to-end validation. since auth-basic results in a
7672 // cachable page, we expect this test to result in a 304. in which case, the
7673 // response should be fetched from the cache.
7674 {
7675 TestDelegate d;
7676 d.set_credentials(AuthCredentials(kUser, kSecret));
7677
Ryan Sleevib8449e02018-07-15 04:31:077678 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167679 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7680 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197681 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7682 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447683
Wez2a31b222018-06-07 22:07:157684 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447685
7686 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7687
7688 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197689 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:447690 }
7691}
7692
7693// Check that Set-Cookie headers in 401 responses are respected.
7694// http://crbug.com/6450
7695TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:557696 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447697
7698 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:557699 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:447700
7701 // Request a page that will give a 401 containing a Set-Cookie header.
7702 // Verify that when the transaction is restarted, it includes the new cookie.
7703 {
[email protected]ceefd7fd2012-11-29 00:36:247704 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447705 TestURLRequestContext context(true);
7706 context.set_network_delegate(&network_delegate);
7707 context.Init();
7708
7709 TestDelegate d;
7710 d.set_credentials(AuthCredentials(kUser, kSecret));
7711
danakj8522a25b2016-04-16 00:17:367712 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:167713 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
7714 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197715 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447716
Wez2a31b222018-06-07 22:07:157717 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447718
7719 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7720
7721 // Make sure we sent the cookie in the restarted transaction.
7722 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7723 != std::string::npos);
7724 }
7725
7726 // Same test as above, except this time the restart is initiated earlier
7727 // (without user intervention since identity is embedded in the URL).
7728 {
[email protected]ceefd7fd2012-11-29 00:36:247729 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447730 TestURLRequestContext context(true);
7731 context.set_network_delegate(&network_delegate);
7732 context.Init();
7733
7734 TestDelegate d;
7735
7736 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:187737 replacements.SetUsernameStr("user2");
7738 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:447739 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
7740
rhalavatib7bd7c792017-04-27 05:25:167741 std::unique_ptr<URLRequest> r(context.CreateRequest(
7742 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197743 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447744
Wez2a31b222018-06-07 22:07:157745 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447746
7747 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
7748
7749 // Make sure we sent the cookie in the restarted transaction.
7750 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7751 != std::string::npos);
7752 }
7753}
7754
[email protected]58e32bb2013-01-21 18:23:257755// Tests that load timing works as expected with auth and the cache.
7756TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:557757 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:257758
7759 // populate the cache
7760 {
7761 TestDelegate d;
7762 d.set_credentials(AuthCredentials(kUser, kSecret));
7763
Ryan Sleevib8449e02018-07-15 04:31:077764 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167765 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7766 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197767 r->Start();
[email protected]58e32bb2013-01-21 18:23:257768
Wez2a31b222018-06-07 22:07:157769 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:257770
7771 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7772
7773 LoadTimingInfo load_timing_info_before_auth;
7774 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7775 &load_timing_info_before_auth));
7776 TestLoadTimingNotReused(load_timing_info_before_auth,
7777 CONNECT_TIMING_HAS_DNS_TIMES);
7778
7779 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197780 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257781 // The test server does not support keep alive sockets, so the second
7782 // request with auth should use a new socket.
7783 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7784 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7785 load_timing_info.socket_log_id);
7786 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7787 load_timing_info.connect_timing.connect_start);
7788 }
7789
[email protected]3b23a222013-05-15 21:33:257790 // Repeat request with end-to-end validation. Since auth-basic results in a
7791 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:257792 // response should be fetched from the cache.
7793 {
7794 TestDelegate d;
7795 d.set_credentials(AuthCredentials(kUser, kSecret));
7796
Ryan Sleevib8449e02018-07-15 04:31:077797 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167798 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
7799 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197800 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7801 r->Start();
[email protected]58e32bb2013-01-21 18:23:257802
Wez2a31b222018-06-07 22:07:157803 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:257804
7805 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7806
7807 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197808 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:257809
[email protected]3b23a222013-05-15 21:33:257810 // Since there was a request that went over the wire, the load timing
7811 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:257812 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197813 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257814 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:257815 }
7816}
7817
[email protected]316c1e5e2012-09-12 15:17:447818// In this test, we do a POST which the server will 302 redirect.
7819// The subsequent transaction should use GET, and should not send the
7820// Content-Type header.
7821// http://code.google.com/p/chromium/issues/detail?id=843
7822TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:557823 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447824
7825 const char kData[] = "hello world";
7826
7827 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:077828 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167829 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
7830 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197831 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077832 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447833
7834 // Set headers (some of which are specific to the POST).
7835 HttpRequestHeaders headers;
Yeol45b9e0a2018-07-27 02:03:297836 headers.SetHeader("Content-Type",
7837 "multipart/form-data;"
7838 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ");
7839 headers.SetHeader("Accept",
7840 "text/xml,application/xml,application/xhtml+xml,"
7841 "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
7842 headers.SetHeader("Accept-Language", "en-US,en");
7843 headers.SetHeader("Accept-Charset", "ISO-8859-1,*,utf-8");
7844 headers.SetHeader("Content-Length", "11");
7845 headers.SetHeader("Origin", "http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:197846 req->SetExtraRequestHeaders(headers);
7847 req->Start();
Wez2a31b222018-06-07 22:07:157848 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447849
7850 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197851 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447852 EXPECT_EQ("text/html", mime_type);
7853
7854 const std::string& data = d.data_received();
7855
7856 // Check that the post-specific headers were stripped:
7857 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
7858 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:497859 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:447860
7861 // These extra request headers should not have been stripped.
7862 EXPECT_TRUE(ContainsString(data, "Accept:"));
7863 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
7864 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
7865}
7866
jww5fe460ff2015-03-28 00:22:517867// The following tests check that we handle mutating the request for HTTP
7868// redirects as expected.
7869// See https://crbug.com/56373, https://crbug.com/102130, and
7870// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:447871
7872TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:557873 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447874
tommycli59a63432015-11-06 00:10:557875 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:517876 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557877 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:447878
7879 HTTPRedirectMethodTest(url, "POST", "GET", true);
7880 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7881 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517882
7883 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7884 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:497885 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7886 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7887 std::string());
Alex Clarke1e08882b32017-10-06 14:22:407888 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
7889 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:447890}
7891
7892TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:557893 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447894
tommycli59a63432015-11-06 00:10:557895 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:517896 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557897 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:447898
7899 HTTPRedirectMethodTest(url, "POST", "GET", true);
7900 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7901 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517902
7903 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7904 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:497905 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7906 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7907 std::string());
Alex Clarke1e08882b32017-10-06 14:22:407908 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
7909 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:447910}
7911
7912TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:557913 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447914
tommycli59a63432015-11-06 00:10:557915 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:517916 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557917 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:447918
7919 HTTPRedirectMethodTest(url, "POST", "GET", true);
7920 HTTPRedirectMethodTest(url, "PUT", "GET", true);
7921 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517922
Alex Clarke1e08882b32017-10-06 14:22:407923 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
7924 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
7925 std::string());
7926 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
7927 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
7928 std::string());
jww5fe460ff2015-03-28 00:22:517929 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7930 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:407931 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
7932 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
7933 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
7934 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
7935 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:497936 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7937 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7938 std::string());
Alex Clarke1e08882b32017-10-06 14:22:407939 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
7940 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:447941}
7942
7943TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557944 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447945
tommycli59a63432015-11-06 00:10:557946 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517947 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557948 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447949
7950 HTTPRedirectMethodTest(url, "POST", "POST", true);
7951 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7952 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517953
7954 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7955 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7956 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7957 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:407958 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
7959 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:447960}
7961
[email protected]0a17aab32014-04-24 03:32:377962TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557963 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377964
tommycli59a63432015-11-06 00:10:557965 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517966 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557967 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377968
7969 HTTPRedirectMethodTest(url, "POST", "POST", true);
7970 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7971 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517972
7973 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7974 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7975 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7976 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:407977 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
7978 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:377979}
7980
7981// Make sure that 308 responses without bodies are not treated as redirects.
7982// Certain legacy apis that pre-date the response code expect this behavior
7983// (Like Google Drive).
7984TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557985 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377986
7987 TestDelegate d;
tommycli59a63432015-11-06 00:10:557988 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377989
Ryan Sleevib8449e02018-07-15 04:31:077990 std::unique_ptr<URLRequest> request(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167991 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:377992
[email protected]f7022f32014-08-21 16:32:197993 request->Start();
Wez2a31b222018-06-07 22:07:157994 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507995 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:377996 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197997 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377998 EXPECT_EQ("This is not a redirect.", d.data_received());
7999}
8000
[email protected]f878230e2014-04-03 15:36:148001TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558002 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148003
tommycli59a63432015-11-06 00:10:558004 GURL original_url(
8005 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8006 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148007
8008 TestDelegate d;
8009 {
Ryan Sleevib8449e02018-07-15 04:31:078010 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168011 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148012
[email protected]f7022f32014-08-21 16:32:198013 r->Start();
Wez2a31b222018-06-07 22:07:158014 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148015
[email protected]f7022f32014-08-21 16:32:198016 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508017 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198018 EXPECT_EQ(original_url, r->original_url());
8019 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148020 }
8021}
8022
[email protected]cba24642014-08-15 20:49:598023TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558024 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598025
tommycli59a63432015-11-06 00:10:558026 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598027 GURL first_party_url("http://example.com");
8028
8029 TestDelegate d;
8030 {
Ryan Sleevib8449e02018-07-15 04:31:078031 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168032 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468033 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598034
[email protected]f7022f32014-08-21 16:32:198035 r->Start();
Wez2a31b222018-06-07 22:07:158036 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598037
[email protected]f7022f32014-08-21 16:32:198038 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508039 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468040 EXPECT_EQ(first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598041 }
8042}
8043
8044TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558045 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598046
tommycli59a63432015-11-06 00:10:558047 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598048 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558049 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598050
8051 TestDelegate d;
8052 {
Ryan Sleevib8449e02018-07-15 04:31:078053 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168054 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468055 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198056 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598057 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8058
[email protected]f7022f32014-08-21 16:32:198059 r->Start();
Wez2a31b222018-06-07 22:07:158060 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598061
[email protected]f7022f32014-08-21 16:32:198062 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508063 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468064 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598065 }
8066}
8067
[email protected]316c1e5e2012-09-12 15:17:448068TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558069 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448070
8071 const char kData[] = "hello world";
8072
8073 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078074 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168075 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8076 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198077 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078078 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448079 HttpRequestHeaders headers;
8080 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:328081 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198082 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448083
danakj8522a25b2016-04-16 00:17:368084 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558085 req.get(), &default_network_delegate_,
8086 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428087 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8088 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448089
[email protected]f7022f32014-08-21 16:32:198090 req->Start();
Wez2a31b222018-06-07 22:07:158091 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198092 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:448093}
8094
8095TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:558096 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448097
8098 const char kData[] = "hello world";
8099
8100 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078101 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168102 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8103 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198104 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078105 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448106 HttpRequestHeaders headers;
8107 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:328108 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198109 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448110
danakj8522a25b2016-04-16 00:17:368111 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558112 req.get(), &default_network_delegate_,
8113 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:098114 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:428115 "Very Good Reason"));
8116 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448117
[email protected]f7022f32014-08-21 16:32:198118 req->Start();
Wez2a31b222018-06-07 22:07:158119 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198120 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:448121 EXPECT_EQ(kData, d.data_received());
8122}
8123
8124// Check that default A-L header is sent.
8125TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558126 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448127
[email protected]8790210c2013-12-02 05:29:538128 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:248129 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448130 TestURLRequestContext context(true);
8131 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:438132 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448133 context.Init();
8134
8135 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368136 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558137 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168138 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198139 req->Start();
Wez2a31b222018-06-07 22:07:158140 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448141 EXPECT_EQ("en", d.data_received());
8142}
8143
8144// Check that an empty A-L header is not sent. http://crbug.com/77365.
8145TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558146 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448147
[email protected]8790210c2013-12-02 05:29:538148 std::string empty_string; // Avoid most vexing parse on line below.
8149 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:248150 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448151 TestURLRequestContext context(true);
8152 context.set_network_delegate(&network_delegate);
8153 context.Init();
8154 // We override the language after initialization because empty entries
8155 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:438156 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448157
8158 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368159 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558160 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168161 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198162 req->Start();
Wez2a31b222018-06-07 22:07:158163 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448164 EXPECT_EQ("None", d.data_received());
8165}
8166
8167// Check that if request overrides the A-L header, the default is not appended.
8168// See http://crbug.com/20894
8169TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558170 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448171
8172 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078173 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558174 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168175 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448176 HttpRequestHeaders headers;
8177 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:198178 req->SetExtraRequestHeaders(headers);
8179 req->Start();
Wez2a31b222018-06-07 22:07:158180 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448181 EXPECT_EQ(std::string("ru"), d.data_received());
8182}
8183
8184// Check that default A-E header is sent.
8185TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558186 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448187
8188 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078189 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558190 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168191 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448192 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:198193 req->SetExtraRequestHeaders(headers);
8194 req->Start();
Wez2a31b222018-06-07 22:07:158195 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448196 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
8197}
8198
8199// Check that if request overrides the A-E header, the default is not appended.
8200// See http://crbug.com/47381
8201TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558202 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448203
8204 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078205 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558206 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168207 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448208 HttpRequestHeaders headers;
8209 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:198210 req->SetExtraRequestHeaders(headers);
8211 req->Start();
Wez2a31b222018-06-07 22:07:158212 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448213 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
8214 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
8215}
8216
[email protected]84f05432013-03-15 01:00:128217// Check that setting the A-C header sends the proper header.
8218TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:558219 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448220
8221 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078222 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558223 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:168224 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448225 HttpRequestHeaders headers;
8226 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:198227 req->SetExtraRequestHeaders(headers);
8228 req->Start();
Wez2a31b222018-06-07 22:07:158229 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448230 EXPECT_EQ(std::string("koi-8r"), d.data_received());
8231}
8232
8233// Check that default User-Agent header is sent.
8234TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:558235 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448236
8237 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078238 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558239 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168240 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198241 req->Start();
Wez2a31b222018-06-07 22:07:158242 d.RunUntilComplete();
Ryan Sleevib8449e02018-07-15 04:31:078243 EXPECT_EQ(default_context().http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:378244 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448245}
8246
8247// Check that if request overrides the User-Agent header,
8248// the default is not appended.
marqf14fff8d2015-12-02 15:52:298249// TODO(crbug.com/564656) This test is flaky on iOS.
8250#if defined(OS_IOS)
8251#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
8252#else
8253#define MAYBE_OverrideUserAgent OverrideUserAgent
8254#endif
8255TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:558256 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448257
8258 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078259 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558260 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168261 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448262 HttpRequestHeaders headers;
8263 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:198264 req->SetExtraRequestHeaders(headers);
8265 req->Start();
Wez2a31b222018-06-07 22:07:158266 d.RunUntilComplete();
[email protected]cd6f2522014-01-16 18:27:358267 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448268}
8269
[email protected]ee4c30d2012-11-07 15:08:438270// Check that a NULL HttpUserAgentSettings causes the corresponding empty
8271// User-Agent header to be sent but does not send the Accept-Language and
8272// Accept-Charset headers.
8273TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:558274 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:438275
[email protected]ceefd7fd2012-11-29 00:36:248276 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:438277 TestURLRequestContext context(true);
8278 context.set_network_delegate(&network_delegate);
8279 context.Init();
8280 // We override the HttpUserAgentSettings after initialization because empty
8281 // entries get overridden by Init().
8282 context.set_http_user_agent_settings(NULL);
8283
8284 struct {
8285 const char* request;
8286 const char* expected_response;
tommycli59a63432015-11-06 00:10:558287 } tests[] = {{"/echoheader?Accept-Language", "None"},
8288 {"/echoheader?Accept-Charset", "None"},
8289 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:438290
viettrungluue4a8b882014-10-16 06:17:388291 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:438292 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368293 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168294 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
8295 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198296 req->Start();
Wez2a31b222018-06-07 22:07:158297 d.RunUntilComplete();
[email protected]ee4c30d2012-11-07 15:08:438298 EXPECT_EQ(tests[i].expected_response, d.data_received())
8299 << " Request = \"" << tests[i].request << "\"";
8300 }
8301}
8302
[email protected]5033ab82013-03-22 20:17:468303// Make sure that URLRequest passes on its priority updates to
8304// newly-created jobs after the first one.
8305TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:558306 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:468307
8308 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078309 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168310 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8311 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198312 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:468313
danakj8522a25b2016-04-16 00:17:368314 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558315 req.get(), &default_network_delegate_,
8316 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428317 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8318 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:468319
[email protected]f7022f32014-08-21 16:32:198320 req->SetPriority(LOW);
8321 req->Start();
8322 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:468323
mmenkeed0498b2015-12-08 23:20:428324 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:368325 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:428326 req.get(), &default_network_delegate_, &job_priority));
8327 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:468328
8329 // Should trigger |job| to be started.
Wez2a31b222018-06-07 22:07:158330 d.RunUntilComplete();
mmenkeed0498b2015-12-08 23:20:428331 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:468332}
8333
[email protected]80abdad2014-03-15 00:20:548334// Check that creating a network request while entering/exiting suspend mode
8335// fails as it should. This is the only case where an HttpTransactionFactory
8336// does not return an HttpTransaction.
8337TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
8338 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:368339 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
Ryan Sleevib8449e02018-07-15 04:31:078340 default_context().http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:548341 network_layer->OnSuspend();
8342
dchengc7eeda422015-12-26 03:56:488343 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:038344 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:278345 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:548346
8347 TestURLRequestContext context(true);
8348 context.set_http_transaction_factory(&http_cache);
8349 context.Init();
8350
8351 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368352 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:168353 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
8354 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198355 req->Start();
Wez2a31b222018-06-07 22:07:158356 d.RunUntilComplete();
[email protected]80abdad2014-03-15 00:20:548357
8358 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:508359 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:548360}
8361
mmenke2281f3762015-11-02 20:38:178362namespace {
[email protected]80abdad2014-03-15 00:20:548363
mmenke2281f3762015-11-02 20:38:178364// HttpTransactionFactory that synchronously fails to create transactions.
8365class FailingHttpTransactionFactory : public HttpTransactionFactory {
8366 public:
8367 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
8368 : network_session_(network_session) {}
8369
Chris Watkins7a41d3552017-12-01 02:13:278370 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:178371
8372 // HttpTransactionFactory methods:
8373 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:368374 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:178375 return ERR_FAILED;
8376 }
8377
8378 HttpCache* GetCache() override { return nullptr; }
8379
8380 HttpNetworkSession* GetSession() override { return network_session_; }
8381
8382 private:
8383 HttpNetworkSession* network_session_;
8384
8385 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
8386};
8387
8388} // namespace
8389
8390// Check that when a request that fails to create an HttpTransaction can be
8391// cancelled while the failure notification is pending, and doesn't send two
8392// failure notifications.
8393//
8394// This currently only happens when in suspend mode and there's no cache, but
8395// just use a special HttpTransactionFactory, to avoid depending on those
8396// behaviors.
8397TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
8398 FailingHttpTransactionFactory http_transaction_factory(
Ryan Sleevib8449e02018-07-15 04:31:078399 default_context().http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:548400 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:178401 context.set_http_transaction_factory(&http_transaction_factory);
8402 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:548403 context.Init();
8404
8405 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368406 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:168407 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
8408 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:178409 // Don't send cookies (Collecting cookies is asynchronous, and need request to
8410 // try to create an HttpNetworkTransaction synchronously on start).
8411 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:198412 req->Start();
mmenke2281f3762015-11-02 20:38:178413 req->Cancel();
Wez2a31b222018-06-07 22:07:158414 d.RunUntilComplete();
mmenke2281f3762015-11-02 20:38:178415 // Run pending error task, if there is one.
8416 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:548417
8418 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:178419 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:508420 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:178421
8422 // NetworkDelegate should see the cancellation, but not the error.
8423 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
8424 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:548425}
8426
ttuttlec0c828492015-05-15 01:25:558427TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:558428 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558429
8430 TestDelegate d;
tommycli59a63432015-11-06 00:10:558431 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:078432 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168433 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:558434
8435 req->Start();
Wez2a31b222018-06-07 22:07:158436 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:558437
8438 EXPECT_TRUE(req->response_info().network_accessed);
8439}
8440
8441TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:558442 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558443
8444 // Populate the cache.
8445 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078446 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168447 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
8448 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:558449 req->Start();
Wez2a31b222018-06-07 22:07:158450 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:558451
maksim.sisovb53724b52016-09-16 05:30:508452 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:558453 EXPECT_TRUE(req->response_info().network_accessed);
8454 EXPECT_FALSE(req->response_info().was_cached);
8455
Ryan Sleevib8449e02018-07-15 04:31:078456 req = default_context().CreateRequest(
8457 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
8458 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:558459 req->Start();
Wez2a31b222018-06-07 22:07:158460 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:558461
maksim.sisovb53724b52016-09-16 05:30:508462 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:558463 EXPECT_FALSE(req->response_info().network_accessed);
8464 EXPECT_TRUE(req->response_info().was_cached);
8465}
8466
8467TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:558468 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558469
8470 TestDelegate d;
tommycli59a63432015-11-06 00:10:558471 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:078472 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168473 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:338474 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:558475
8476 req->Start();
Wez2a31b222018-06-07 22:07:158477 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:558478
8479 EXPECT_FALSE(req->response_info().network_accessed);
8480}
8481
rdsmithbf8c3c12016-11-18 18:16:248482// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:088483// correctly in the absence of contention.
8484TEST_F(URLRequestTestHTTP, ThrottledPriority) {
8485 ASSERT_TRUE(http_test_server()->Start());
8486
8487 TestDelegate d;
8488 GURL test_url(http_test_server()->GetURL("/"));
Ryan Sleevib8449e02018-07-15 04:31:078489 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168490 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:088491 req->Start();
Wez2a31b222018-06-07 22:07:158492 d.RunUntilComplete();
rdsmith5eb6fbc2016-10-21 17:36:088493
8494 EXPECT_TRUE(req->status().is_success());
8495}
8496
ricea3a1c71f2016-06-17 10:05:268497TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
8498 ASSERT_TRUE(http_test_server()->Start());
8499
8500 TestDelegate d;
8501 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168502 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
8503 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:268504 req->Start();
Wez2a31b222018-06-07 22:07:158505 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:268506
8507 EXPECT_EQ(5, req->GetRawBodyBytes());
8508}
8509
8510TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
8511 ASSERT_TRUE(http_test_server()->Start());
8512
8513 TestDelegate d;
8514 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168515 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
8516 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:268517 req->Start();
Wez2a31b222018-06-07 22:07:158518 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:268519
8520 EXPECT_EQ(30, req->GetRawBodyBytes());
8521}
8522
jamd3f5a3c2016-10-27 18:52:028523// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
8524// the delegate isn't called back synchronously.
8525TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
8526 ASSERT_TRUE(http_test_server()->Start());
8527 default_network_delegate_.set_before_start_transaction_fails();
8528
8529 TestDelegate d;
8530 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168531 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
8532 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:028533 req->Start();
8534 DCHECK(!d.response_completed());
Wez2a31b222018-06-07 22:07:158535 d.RunUntilComplete();
jamd3f5a3c2016-10-27 18:52:028536 DCHECK(d.response_completed());
8537 EXPECT_EQ(ERR_FAILED, d.request_status());
8538}
8539
bengr1bf8e942014-11-07 01:36:508540class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
8541 public:
8542 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
8543 // ideally remove the dependency on URLRequestTestJob, and maybe move these
8544 // tests into the factory tests.
8545 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
8546 }
8547
8548 void SetUpFactory() override {
8549 interceptor_ = new MockURLRequestInterceptor();
8550 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:368551 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:508552 }
8553
8554 MockURLRequestInterceptor* interceptor() const {
8555 return interceptor_;
8556 }
8557
8558 private:
8559 MockURLRequestInterceptor* interceptor_;
8560};
8561
8562TEST_F(URLRequestInterceptorTestHTTP,
8563 NetworkDelegateNotificationOnRedirectIntercept) {
8564 interceptor()->set_intercept_redirect(true);
8565 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
8566 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
8567
tommycli59a63432015-11-06 00:10:558568 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508569
8570 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368571 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168572 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8573 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:508574 req->Start();
Wez2a31b222018-06-07 22:07:158575 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:508576
8577 EXPECT_TRUE(interceptor()->did_intercept_redirect());
8578 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:508579 int status = d.request_status();
8580 EXPECT_EQ(OK, status);
8581 if (status == OK)
bengr1bf8e942014-11-07 01:36:508582 EXPECT_EQ(200, req->response_headers()->response_code());
8583
8584 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8585 EXPECT_EQ(1, d.response_started_count());
8586 EXPECT_EQ(0, d.received_redirect_count());
8587
8588 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008589 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508590 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
8591}
8592
8593TEST_F(URLRequestInterceptorTestHTTP,
8594 NetworkDelegateNotificationOnErrorIntercept) {
8595 // Intercept that error and respond with an OK response.
8596 interceptor()->set_intercept_final_response(true);
8597 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
8598 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
8599 default_network_delegate()->set_can_be_intercepted_on_error(true);
8600
tommycli59a63432015-11-06 00:10:558601 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508602
8603 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368604 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558605 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168606 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:508607 req->set_method("GET");
8608 req->Start();
Wez2a31b222018-06-07 22:07:158609 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:508610
8611 EXPECT_TRUE(interceptor()->did_intercept_final());
8612
8613 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:508614 int status = d.request_status();
8615 EXPECT_EQ(OK, status);
8616 if (status == OK)
bengr1bf8e942014-11-07 01:36:508617 EXPECT_EQ(200, req->response_headers()->response_code());
8618 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8619 EXPECT_EQ(1, d.response_started_count());
8620 EXPECT_EQ(0, d.received_redirect_count());
8621
8622 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008623 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508624 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
8625}
8626
8627TEST_F(URLRequestInterceptorTestHTTP,
8628 NetworkDelegateNotificationOnResponseIntercept) {
8629 // Intercept that error and respond with an OK response.
8630 interceptor()->set_intercept_final_response(true);
8631
8632 // Intercept with a real URLRequestHttpJob.
8633 interceptor()->set_use_url_request_http_job(true);
8634
tommycli59a63432015-11-06 00:10:558635 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508636
8637 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368638 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168639 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
8640 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:508641 req->set_method("GET");
8642 req->Start();
Wez2a31b222018-06-07 22:07:158643 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:508644
8645 EXPECT_TRUE(interceptor()->did_intercept_final());
8646
8647 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:508648 int status = d.request_status();
8649 EXPECT_EQ(OK, status);
8650 if (status == OK)
bengr1bf8e942014-11-07 01:36:508651 EXPECT_EQ(200, req->response_headers()->response_code());
8652 EXPECT_EQ("hello", d.data_received());
8653 EXPECT_EQ(1, d.response_started_count());
8654 EXPECT_EQ(0, d.received_redirect_count());
8655
8656 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008657 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508658 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
8659}
8660
mkwst0c5eab872014-11-21 14:18:548661class URLRequestTestReferrerPolicy : public URLRequestTest {
8662 public:
Chris Watkins7a41d3552017-12-01 02:13:278663 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:548664
tommycli59a63432015-11-06 00:10:558665 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
8666 origin_server_.reset(new EmbeddedTestServer(type));
8667 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
8668 origin_server_->AddDefaultHandlers(
8669 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8670 } else {
8671 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8672 }
mkwst0c5eab872014-11-21 14:18:548673 ASSERT_TRUE(origin_server_->Start());
8674 }
8675
tommycli59a63432015-11-06 00:10:558676 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
8677 net::EmbeddedTestServer::Type dest_type) {
8678 origin_server_.reset(new EmbeddedTestServer(origin_type));
8679 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8680 origin_server_->AddDefaultHandlers(
8681 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8682 } else {
8683 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8684 }
mkwst0c5eab872014-11-21 14:18:548685 ASSERT_TRUE(origin_server_->Start());
8686
tommycli59a63432015-11-06 00:10:558687 destination_server_.reset(new EmbeddedTestServer(dest_type));
8688 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8689 destination_server_->AddDefaultHandlers(
8690 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8691 } else {
8692 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8693 }
mkwst0c5eab872014-11-21 14:18:548694 ASSERT_TRUE(destination_server_->Start());
8695 }
8696
8697 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
8698 const GURL& referrer,
8699 const GURL& expected) {
8700 // Create and execute the request: we'll only have a |destination_server_|
8701 // if the origins are meant to be distinct. Otherwise, we'll use the
8702 // |origin_server_| for both endpoints.
8703 GURL destination_url =
tommycli59a63432015-11-06 00:10:558704 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
8705 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:548706 GURL origin_url =
tommycli59a63432015-11-06 00:10:558707 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:548708
8709 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:078710 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168711 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:548712 req->set_referrer_policy(policy);
8713 req->SetReferrer(referrer.spec());
8714 req->Start();
Wez2a31b222018-06-07 22:07:158715 d.RunUntilComplete();
mkwst0c5eab872014-11-21 14:18:548716
8717 EXPECT_EQ(1, d.response_started_count());
8718 EXPECT_EQ(1, d.received_redirect_count());
8719 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:508720 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:548721 EXPECT_EQ(200, req->response_headers()->response_code());
8722
8723 EXPECT_EQ(expected.spec(), req->referrer());
8724 if (expected.is_empty())
8725 EXPECT_EQ("None", d.data_received());
8726 else
8727 EXPECT_EQ(expected.spec(), d.data_received());
8728 }
8729
tommycli59a63432015-11-06 00:10:558730 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:548731
8732 private:
danakj8522a25b2016-04-16 00:17:368733 std::unique_ptr<EmbeddedTestServer> origin_server_;
8734 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:548735};
8736
8737TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:558738 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548739
estarkc8ccba82017-06-13 22:37:408740 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:548741 VerifyReferrerAfterRedirect(
8742 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:408743 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:548744
8745 VerifyReferrerAfterRedirect(
8746 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:408747 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:548748
8749 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:408750 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:548751
estarkc8ccba82017-06-13 22:37:408752 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
8753 referrer);
8754
8755 // The original referrer set on the request is expected to obey the referrer
8756 // policy and already be stripped to the origin; thus this test case just
8757 // checks that this policy doesn't cause the referrer to change when following
8758 // a redirect.
8759 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
8760 referrer.GetOrigin());
8761
8762 VerifyReferrerAfterRedirect(
8763 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
8764 referrer);
8765
8766 // The original referrer set on the request is expected to obey the referrer
8767 // policy and already be stripped to the origin; thus this test case just
8768 // checks that this policy doesn't cause the referrer to change when following
8769 // a redirect.
8770 VerifyReferrerAfterRedirect(
8771 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
8772 referrer.GetOrigin(), referrer.GetOrigin());
8773
8774 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:548775}
8776
tommycli59a63432015-11-06 00:10:558777TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
8778 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8779 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:408780 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:548781
8782 VerifyReferrerAfterRedirect(
8783 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:408784 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:548785
8786 VerifyReferrerAfterRedirect(
8787 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:408788 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:548789
8790 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:408791 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
8792 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:548793
estarkc8ccba82017-06-13 22:37:408794 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
8795 referrer);
8796
8797 // The original referrer set on the request is expected to obey the referrer
8798 // policy and already be stripped to the origin; thus this test case just
8799 // checks that this policy doesn't cause the referrer to change when following
8800 // a redirect.
8801 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
8802 referrer.GetOrigin());
8803
8804 VerifyReferrerAfterRedirect(
8805 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
8806
8807 // The original referrer set on the request is expected to obey the referrer
8808 // policy and already be stripped to the origin; thus this test case just
8809 // checks that this policy doesn't cause the referrer to change when following
8810 // a redirect.
8811 VerifyReferrerAfterRedirect(
8812 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
8813 referrer.GetOrigin(), referrer.GetOrigin());
8814
8815 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:548816}
8817
8818TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:558819 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:408820 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:548821
8822 VerifyReferrerAfterRedirect(
8823 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:408824 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:548825
8826 VerifyReferrerAfterRedirect(
8827 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:408828 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:548829
8830 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:408831 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:548832
estarkc8ccba82017-06-13 22:37:408833 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
8834 referrer);
8835
8836 // The original referrer set on the request is expected to obey the referrer
8837 // policy and already be stripped to the origin; thus this test case just
8838 // checks that this policy doesn't cause the referrer to change when following
8839 // a redirect.
8840 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
8841 referrer.GetOrigin());
8842
8843 VerifyReferrerAfterRedirect(
8844 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
8845 referrer);
8846
8847 // The original referrer set on the request is expected to obey the referrer
8848 // policy and already be stripped to the origin; thus this test case just
8849 // checks that this policy doesn't cause the referrer to change when following
8850 // a redirect.
8851 VerifyReferrerAfterRedirect(
8852 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
8853 referrer.GetOrigin(), referrer.GetOrigin());
8854
8855 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:548856}
8857
tommycli59a63432015-11-06 00:10:558858TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
8859 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8860 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:408861 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:548862
8863 VerifyReferrerAfterRedirect(
8864 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:408865 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:548866
8867 VerifyReferrerAfterRedirect(
8868 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:408869 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548870
8871 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:408872 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:558873 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548874
estarkc8ccba82017-06-13 22:37:408875 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
8876 referrer);
8877
8878 // The original referrer set on the request is expected to obey the referrer
8879 // policy and already be stripped to the origin; thus this test case just
8880 // checks that this policy doesn't cause the referrer to change when following
8881 // a redirect.
8882 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
8883 referrer.GetOrigin());
8884
8885 VerifyReferrerAfterRedirect(
8886 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
8887
8888 // The original referrer set on the request is expected to obey the referrer
8889 // policy and already be stripped to the origin; thus this test case just
8890 // checks that this policy doesn't cause the referrer to change when following
8891 // a redirect.
8892 VerifyReferrerAfterRedirect(
8893 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
8894 referrer.GetOrigin(), referrer.GetOrigin());
8895
8896 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:548897}
8898
tommycli59a63432015-11-06 00:10:558899TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
8900 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8901 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:408902 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:548903
8904 VerifyReferrerAfterRedirect(
8905 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:408906 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:548907
8908 VerifyReferrerAfterRedirect(
8909 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:408910 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548911
8912 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:408913 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:558914 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548915
estarkc8ccba82017-06-13 22:37:408916 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
8917 referrer);
8918
8919 // The original referrer set on the request is expected to obey the referrer
8920 // policy and already be stripped to the origin; thus this test case just
8921 // checks that this policy doesn't cause the referrer to change when following
8922 // a redirect.
8923 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
8924 referrer.GetOrigin());
8925
8926 VerifyReferrerAfterRedirect(
8927 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
8928
8929 // The original referrer set on the request is expected to obey the referrer
8930 // policy and already be stripped to the origin; thus this test case just
8931 // checks that this policy doesn't cause the referrer to change when following
8932 // a redirect.
8933 VerifyReferrerAfterRedirect(
8934 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
8935 referrer.GetOrigin(), referrer.GetOrigin());
8936
8937 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:548938}
8939
tommycli59a63432015-11-06 00:10:558940TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
8941 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8942 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:408943 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:548944
8945 VerifyReferrerAfterRedirect(
8946 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:408947 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:548948
8949 VerifyReferrerAfterRedirect(
8950 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:408951 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:548952
8953 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:408954 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:558955 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548956
estarkc8ccba82017-06-13 22:37:408957 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
8958 referrer);
8959
8960 // The original referrer set on the request is expected to obey the referrer
8961 // policy and already be stripped to the origin; thus this test case just
8962 // checks that this policy doesn't cause the referrer to change when following
8963 // a redirect.
8964 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
8965 referrer.GetOrigin());
8966
8967 VerifyReferrerAfterRedirect(
8968 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
8969
8970 // The original referrer set on the request is expected to obey the referrer
8971 // policy and already be stripped to the origin, though it should be
8972 // subsequently cleared during the downgrading redirect.
8973 VerifyReferrerAfterRedirect(
8974 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
8975 referrer.GetOrigin(), GURL());
8976
8977 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:548978}
8979
Bence Béky98447b12018-05-08 03:14:018980class HTTPSRequestTest : public TestWithScopedTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:508981 public:
fdorayf33fede2017-05-11 21:18:108982 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:098983 default_context_.set_network_delegate(&default_network_delegate_);
8984 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:508985 }
Martijn Croonenb1383da2017-10-11 11:56:358986 ~HTTPSRequestTest() override {
8987 SetTransportSecurityStateSourceForTesting(nullptr);
8988 }
[email protected]87a09a92011-07-14 15:50:508989
8990 protected:
[email protected]ceefd7fd2012-11-29 00:36:248991 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:098992 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:468993};
8994
[email protected]c044616e2013-02-20 02:01:268995TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:558996 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8997 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228998 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118999 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469000
[email protected]ea224582008-12-07 20:25:469001 TestDelegate d;
9002 {
danakj8522a25b2016-04-16 00:17:369003 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169004 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9005 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199006 r->Start();
9007 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469008
Wez2a31b222018-06-07 22:07:159009 d.RunUntilComplete();
[email protected]ea224582008-12-07 20:25:469010
9011 EXPECT_EQ(1, d.response_started_count());
9012 EXPECT_FALSE(d.received_data_before_response());
9013 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199014 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199015 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199016 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199017 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199018 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:469019 }
[email protected]ea224582008-12-07 20:25:469020}
9021
[email protected]5774ada2010-07-15 06:30:549022TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559023 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9024 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9025 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229026 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119027 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339028
9029 bool err_allowed = true;
9030 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9031 TestDelegate d;
9032 {
9033 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369034 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169035 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9036 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339037
[email protected]f7022f32014-08-21 16:32:199038 r->Start();
9039 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339040
Wez2a31b222018-06-07 22:07:159041 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339042
9043 EXPECT_EQ(1, d.response_started_count());
9044 EXPECT_FALSE(d.received_data_before_response());
9045 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179046 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339047 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199048 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179049 } else {
[email protected]bacff652009-03-31 17:50:339050 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179051 }
[email protected]bacff652009-03-31 17:50:339052 }
9053 }
9054}
9055
[email protected]5774ada2010-07-15 06:30:549056TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559057 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9058 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9059 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229060 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119061 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339062
9063 // Iterate from false to true, just so that we do the opposite of the
9064 // previous test in order to increase test coverage.
9065 bool err_allowed = false;
9066 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9067 TestDelegate d;
9068 {
9069 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369070 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169071 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9072 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339073
[email protected]f7022f32014-08-21 16:32:199074 r->Start();
9075 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339076
Wez2a31b222018-06-07 22:07:159077 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339078
9079 EXPECT_EQ(1, d.response_started_count());
9080 EXPECT_FALSE(d.received_data_before_response());
9081 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179082 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339083 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199084 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179085 } else {
[email protected]bacff652009-03-31 17:50:339086 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179087 }
[email protected]bacff652009-03-31 17:50:339088 }
9089 }
9090}
[email protected]73e0bba2009-02-19 22:57:099091
tommycli59a63432015-11-06 00:10:559092// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
9093// security state. (see http://crbug.com/550977).
9094#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:359095// This tests that a load of a domain with preloaded HSTS and HPKP with a
9096// certificate error sets the |certificate_errors_are_fatal| flag correctly.
9097// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:449098TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359099 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9100
tommycli59a63432015-11-06 00:10:559101 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9102 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9103 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449104 ASSERT_TRUE(test_server.Start());
9105
Martijn Croonenb1383da2017-10-11 11:56:359106 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9107 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9108 // means that we have to use a MockHostResolver in order to direct
9109 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9110 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449111
9112 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249113 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449114 TestURLRequestContext context(true);
9115 context.set_network_delegate(&network_delegate);
9116 context.set_host_resolver(&host_resolver);
9117 TransportSecurityState transport_security_state;
9118 context.set_transport_security_state(&transport_security_state);
9119 context.Init();
9120
9121 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369122 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359123 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369124 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169125 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449126
[email protected]f7022f32014-08-21 16:32:199127 r->Start();
9128 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449129
Wez2a31b222018-06-07 22:07:159130 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449131
9132 EXPECT_EQ(1, d.response_started_count());
9133 EXPECT_FALSE(d.received_data_before_response());
9134 EXPECT_TRUE(d.have_certificate_errors());
9135 EXPECT_TRUE(d.certificate_errors_are_fatal());
9136}
9137
9138// This tests that cached HTTPS page loads do not cause any updates to the
9139// TransportSecurityState.
9140TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359141 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9142
[email protected]316c1e5e2012-09-12 15:17:449143 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
9144 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:559145 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9146 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9147 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449148 ASSERT_TRUE(test_server.Start());
9149
Martijn Croonenb1383da2017-10-11 11:56:359150 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9151 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9152 // means that we have to use a MockHostResolver in order to direct
9153 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9154 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449155
9156 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249157 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449158 TestURLRequestContext context(true);
9159 context.set_network_delegate(&network_delegate);
9160 context.set_host_resolver(&host_resolver);
9161 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:269162
martijnc0d6b622015-06-30 19:14:409163 TransportSecurityState::STSState static_sts_state;
9164 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269165 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359166 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:449167 context.set_transport_security_state(&transport_security_state);
9168 context.Init();
9169
martijnc0d6b622015-06-30 19:14:409170 TransportSecurityState::STSState dynamic_sts_state;
9171 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:359172 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
9173 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
9174 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
9175 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269176
[email protected]316c1e5e2012-09-12 15:17:449177 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369178 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359179 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369180 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169181 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449182
[email protected]f7022f32014-08-21 16:32:199183 r->Start();
9184 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449185
Wez2a31b222018-06-07 22:07:159186 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449187
9188 EXPECT_EQ(1, d.response_started_count());
9189 EXPECT_FALSE(d.received_data_before_response());
9190 EXPECT_TRUE(d.have_certificate_errors());
9191 EXPECT_TRUE(d.certificate_errors_are_fatal());
9192
[email protected]9e6968d2014-05-07 21:46:269193 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:409194 TransportSecurityState::STSState new_static_sts_state;
9195 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269196 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359197 "hsts-hpkp-preloaded.test", &new_static_sts_state,
9198 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:409199 TransportSecurityState::STSState new_dynamic_sts_state;
9200 TransportSecurityState::PKPState new_dynamic_pkp_state;
9201 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:359202 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:409203 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:359204 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269205
martijnc0d6b622015-06-30 19:14:409206 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
9207 EXPECT_EQ(new_static_sts_state.include_subdomains,
9208 static_sts_state.include_subdomains);
9209 EXPECT_EQ(new_static_pkp_state.include_subdomains,
9210 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:489211 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
9212 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
9213 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:449214}
9215
[email protected]8ccc69f2012-11-28 19:52:149216// Make sure HSTS preserves a POST request's method and body.
9217TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
9218 static const char kData[] = "hello world";
9219
tommycli59a63432015-11-06 00:10:559220 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9221 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229222 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:149223 ASSERT_TRUE(test_server.Start());
9224
9225
9226 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9227 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:559228 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:229229 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:149230 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:149231
9232 // Force https for www.somewhere.com.
9233 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:209234 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
9235 bool include_subdomains = false;
9236 transport_security_state.AddHSTS("www.somewhere.com", expiry,
9237 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:149238
9239 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9240
9241 TestURLRequestContext context(true);
9242 context.set_host_resolver(&host_resolver);
9243 context.set_transport_security_state(&transport_security_state);
9244 context.set_network_delegate(&network_delegate);
9245 context.Init();
9246
9247 TestDelegate d;
9248 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
9249 // cause a certificate error. Ignore the error.
9250 d.set_allow_certificate_errors(true);
9251
danakj8522a25b2016-04-16 00:17:369252 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199253 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:369254 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169255 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199256 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079257 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:149258
[email protected]f7022f32014-08-21 16:32:199259 req->Start();
Wez2a31b222018-06-07 22:07:159260 d.RunUntilComplete();
[email protected]8ccc69f2012-11-28 19:52:149261
[email protected]f7022f32014-08-21 16:32:199262 EXPECT_EQ("https", req->url().scheme());
9263 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:149264 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:409265
9266 LoadTimingInfo load_timing_info;
9267 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
9268 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
9269 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:149270}
9271
rob4e0be1f2014-09-11 23:40:229272// Make sure that the CORS headers are added to cross-origin HSTS redirects.
9273TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
9274 static const char kOriginHeaderValue[] = "http://www.example.com";
9275
tommycli59a63432015-11-06 00:10:559276 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9277 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:229278 ASSERT_TRUE(test_server.Start());
9279
9280 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9281 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:559282 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
9283 // default.
rob4e0be1f2014-09-11 23:40:229284 MockHostResolver host_resolver;
9285
9286 TransportSecurityState transport_security_state;
9287 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
9288 bool include_subdomains = false;
9289 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
9290
9291 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9292
9293 MockCertVerifier cert_verifier;
9294 cert_verifier.set_default_result(OK);
9295
9296 TestURLRequestContext context(true);
9297 context.set_host_resolver(&host_resolver);
9298 context.set_transport_security_state(&transport_security_state);
9299 context.set_network_delegate(&network_delegate);
9300 context.set_cert_verifier(&cert_verifier);
9301 context.Init();
9302
9303 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
9304 test_server.host_port_pair().port()));
9305 url::Replacements<char> replacements;
9306 const char kNewScheme[] = "https";
9307 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
9308 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
9309
9310 TestDelegate d;
rob4e0be1f2014-09-11 23:40:229311
rhalavatib7bd7c792017-04-27 05:25:169312 std::unique_ptr<URLRequest> req(context.CreateRequest(
9313 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:229314 // Set Origin header to simulate a cross-origin request.
9315 HttpRequestHeaders request_headers;
9316 request_headers.SetHeader("Origin", kOriginHeaderValue);
9317 req->SetExtraRequestHeaders(request_headers);
9318
9319 req->Start();
Wez0e717112018-06-18 23:09:229320 d.RunUntilRedirect();
rob4e0be1f2014-09-11 23:40:229321
9322 EXPECT_EQ(1, d.received_redirect_count());
9323
9324 const HttpResponseHeaders* headers = req->response_headers();
9325 std::string redirect_location;
9326 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
9327 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
9328
9329 std::string received_cors_header;
9330 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
9331 &received_cors_header));
9332 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
9333}
9334
[email protected]316c1e5e2012-09-12 15:17:449335namespace {
9336
9337class SSLClientAuthTestDelegate : public TestDelegate {
9338 public:
9339 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
Wez0e717112018-06-18 23:09:229340 set_on_complete(base::DoNothing());
[email protected]316c1e5e2012-09-12 15:17:449341 }
dchengb03027d2014-10-21 12:00:209342 void OnCertificateRequested(URLRequest* request,
9343 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:449344 on_certificate_requested_count_++;
Wez0e717112018-06-18 23:09:229345 std::move(on_certificate_requested_).Run();
9346 }
9347 void RunUntilCertificateRequested() {
9348 base::RunLoop run_loop;
9349 on_certificate_requested_ = run_loop.QuitClosure();
9350 run_loop.Run();
[email protected]316c1e5e2012-09-12 15:17:449351 }
9352 int on_certificate_requested_count() {
9353 return on_certificate_requested_count_;
9354 }
9355 private:
9356 int on_certificate_requested_count_;
Wez0e717112018-06-18 23:09:229357 base::OnceClosure on_certificate_requested_;
[email protected]316c1e5e2012-09-12 15:17:449358};
9359
David Benjamin76a40ad2018-02-24 22:22:089360class TestSSLPrivateKey : public SSLPrivateKey {
9361 public:
9362 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
9363 : key_(std::move(key)) {}
9364
9365 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
9366 int sign_count() const { return sign_count_; }
9367
David Benjaminb65b0732018-11-09 20:33:539368 std::string GetProviderName() override { return key_->GetProviderName(); }
David Benjamin76a40ad2018-02-24 22:22:089369 std::vector<uint16_t> GetAlgorithmPreferences() override {
9370 return key_->GetAlgorithmPreferences();
9371 }
9372 void Sign(uint16_t algorithm,
9373 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:269374 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:089375 sign_count_++;
9376 if (fail_signing_) {
9377 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:269378 FROM_HERE, base::BindOnce(std::move(callback),
9379 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
9380 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:089381 } else {
David Benjamin8f2d2c12018-02-27 00:08:269382 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:089383 }
9384 }
9385
9386 private:
9387 ~TestSSLPrivateKey() override = default;
9388
9389 scoped_refptr<SSLPrivateKey> key_;
9390 bool fail_signing_ = false;
9391 int sign_count_ = 0;
9392};
9393
[email protected]316c1e5e2012-09-12 15:17:449394} // namespace
9395
9396// TODO(davidben): Test the rest of the code. Specifically,
9397// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:449398// - Getting a certificate request in an SSL renegotiation sending the
9399// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:089400TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:559401 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9402 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:129403 ssl_config.client_cert_type =
9404 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:089405 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:559406 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229407 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449408 ASSERT_TRUE(test_server.Start());
9409
9410 SSLClientAuthTestDelegate d;
9411 {
danakj8522a25b2016-04-16 00:17:369412 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169413 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9414 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449415
[email protected]f7022f32014-08-21 16:32:199416 r->Start();
9417 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449418
Wez0e717112018-06-18 23:09:229419 d.RunUntilCertificateRequested();
9420 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449421
9422 EXPECT_EQ(1, d.on_certificate_requested_count());
9423 EXPECT_FALSE(d.received_data_before_response());
9424 EXPECT_EQ(0, d.bytes_received());
9425
9426 // Send no certificate.
9427 // TODO(davidben): Get temporary client cert import (with keys) working on
9428 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:549429 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:449430
Wez2a31b222018-06-07 22:07:159431 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449432
David Benjamin76a40ad2018-02-24 22:22:089433 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:449434 EXPECT_EQ(1, d.response_started_count());
9435 EXPECT_FALSE(d.received_data_before_response());
9436 EXPECT_NE(0, d.bytes_received());
9437 }
9438}
9439
David Benjamin76a40ad2018-02-24 22:22:089440TEST_F(HTTPSRequestTest, ClientAuth) {
9441 std::unique_ptr<FakeClientCertIdentity> identity =
9442 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
9443 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
9444 ASSERT_TRUE(identity);
9445 scoped_refptr<TestSSLPrivateKey> private_key =
9446 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
9447
9448 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9449 net::SSLServerConfig ssl_config;
9450 ssl_config.client_cert_type =
9451 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
9452 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
9453 test_server.AddDefaultHandlers(
9454 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9455 ASSERT_TRUE(test_server.Start());
9456
9457 {
9458 SSLClientAuthTestDelegate d;
9459 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9460 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9461 TRAFFIC_ANNOTATION_FOR_TESTS));
9462
9463 r->Start();
9464 EXPECT_TRUE(r->is_pending());
9465
Wez0e717112018-06-18 23:09:229466 d.RunUntilCertificateRequested();
9467 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:089468
9469 EXPECT_EQ(1, d.on_certificate_requested_count());
9470 EXPECT_FALSE(d.received_data_before_response());
9471 EXPECT_EQ(0, d.bytes_received());
9472
9473 // Send a certificate.
9474 r->ContinueWithCertificate(identity->certificate(), private_key);
9475
Wez2a31b222018-06-07 22:07:159476 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:089477
9478 EXPECT_EQ(OK, d.request_status());
9479 EXPECT_EQ(1, d.response_started_count());
9480 EXPECT_FALSE(d.received_data_before_response());
9481 EXPECT_NE(0, d.bytes_received());
9482
9483 // The private key should have been used.
9484 EXPECT_EQ(1, private_key->sign_count());
9485 }
9486
9487 // Close all connections and clear the session cache to force a new handshake.
9488 default_context_.http_transaction_factory()
9489 ->GetSession()
9490 ->CloseAllConnections();
9491 SSLClientSocket::ClearSessionCache();
9492
9493 // Connecting again should not call OnCertificateRequested. The identity is
9494 // taken from the client auth cache.
9495 {
9496 SSLClientAuthTestDelegate d;
9497 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9498 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9499 TRAFFIC_ANNOTATION_FOR_TESTS));
9500
9501 r->Start();
9502 EXPECT_TRUE(r->is_pending());
9503
Wez2a31b222018-06-07 22:07:159504 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:089505
9506 EXPECT_EQ(OK, d.request_status());
9507 EXPECT_EQ(0, d.on_certificate_requested_count());
9508 EXPECT_FALSE(d.received_data_before_response());
9509 EXPECT_EQ(1, d.response_started_count());
9510 EXPECT_FALSE(d.received_data_before_response());
9511 EXPECT_NE(0, d.bytes_received());
9512
9513 // The private key should have been used.
9514 EXPECT_EQ(2, private_key->sign_count());
9515 }
9516}
9517
9518// Test that private keys that fail to sign anything get evicted from the cache.
9519TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
9520 std::unique_ptr<FakeClientCertIdentity> identity =
9521 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
9522 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
9523 ASSERT_TRUE(identity);
9524 scoped_refptr<TestSSLPrivateKey> private_key =
9525 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
9526 private_key->set_fail_signing(true);
9527
9528 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9529 net::SSLServerConfig ssl_config;
9530 ssl_config.client_cert_type =
9531 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
9532 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
9533 test_server.AddDefaultHandlers(
9534 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9535 ASSERT_TRUE(test_server.Start());
9536
9537 {
9538 SSLClientAuthTestDelegate d;
9539 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9540 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9541 TRAFFIC_ANNOTATION_FOR_TESTS));
9542
9543 r->Start();
9544 EXPECT_TRUE(r->is_pending());
Wez0e717112018-06-18 23:09:229545
9546 d.RunUntilCertificateRequested();
9547 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:089548
9549 EXPECT_EQ(1, d.on_certificate_requested_count());
9550 EXPECT_FALSE(d.received_data_before_response());
9551 EXPECT_EQ(0, d.bytes_received());
9552
9553 // Send a certificate.
9554 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:159555 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:089556
9557 // The private key cannot sign anything, so we report an error.
9558 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
9559 EXPECT_EQ(1, d.response_started_count());
9560 EXPECT_FALSE(d.received_data_before_response());
9561 EXPECT_EQ(0, d.bytes_received());
9562
9563 // The private key should have been used.
9564 EXPECT_EQ(1, private_key->sign_count());
9565 }
9566
9567 // Close all connections and clear the session cache to force a new handshake.
9568 default_context_.http_transaction_factory()
9569 ->GetSession()
9570 ->CloseAllConnections();
9571 SSLClientSocket::ClearSessionCache();
9572
9573 // The bad identity should have been evicted from the cache, so connecting
9574 // again should call OnCertificateRequested again.
9575 {
9576 SSLClientAuthTestDelegate d;
9577 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9578 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9579 TRAFFIC_ANNOTATION_FOR_TESTS));
9580
9581 r->Start();
9582 EXPECT_TRUE(r->is_pending());
9583
Wez0e717112018-06-18 23:09:229584 d.RunUntilCertificateRequested();
9585 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:089586
9587 EXPECT_EQ(1, d.on_certificate_requested_count());
9588 EXPECT_FALSE(d.received_data_before_response());
9589 EXPECT_EQ(0, d.bytes_received());
9590
9591 // There should have been no additional uses of the private key.
9592 EXPECT_EQ(1, private_key->sign_count());
9593 }
9594}
9595
9596// Test that cached private keys that fail to sign anything trigger a
9597// retry. This is so we handle unplugged smartcards
9598// gracefully. https://crbug.com/813022.
9599TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
9600 std::unique_ptr<FakeClientCertIdentity> identity =
9601 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
9602 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
9603 ASSERT_TRUE(identity);
9604 scoped_refptr<TestSSLPrivateKey> private_key =
9605 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
9606
9607 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9608 net::SSLServerConfig ssl_config;
9609 ssl_config.client_cert_type =
9610 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
9611 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
9612 test_server.AddDefaultHandlers(
9613 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9614 ASSERT_TRUE(test_server.Start());
9615
9616 // Connect with a client certificate to put it in the client auth cache.
9617 {
9618 SSLClientAuthTestDelegate d;
9619 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9620 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9621 TRAFFIC_ANNOTATION_FOR_TESTS));
9622
9623 r->Start();
9624 EXPECT_TRUE(r->is_pending());
9625
Wez0e717112018-06-18 23:09:229626 d.RunUntilCertificateRequested();
9627 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:089628
9629 EXPECT_EQ(1, d.on_certificate_requested_count());
9630 EXPECT_FALSE(d.received_data_before_response());
9631 EXPECT_EQ(0, d.bytes_received());
9632
9633 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:159634 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:089635
9636 EXPECT_EQ(OK, d.request_status());
9637 EXPECT_EQ(1, d.response_started_count());
9638 EXPECT_FALSE(d.received_data_before_response());
9639 EXPECT_NE(0, d.bytes_received());
9640
9641 // The private key should have been used.
9642 EXPECT_EQ(1, private_key->sign_count());
9643 }
9644
9645 // Close all connections and clear the session cache to force a new handshake.
9646 default_context_.http_transaction_factory()
9647 ->GetSession()
9648 ->CloseAllConnections();
9649 SSLClientSocket::ClearSessionCache();
9650
9651 // Cause the private key to fail. Connecting again should attempt to use it,
9652 // notice the failure, and then request a new identity via
9653 // OnCertificateRequested.
9654 private_key->set_fail_signing(true);
9655
9656 {
9657 SSLClientAuthTestDelegate d;
9658 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9659 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9660 TRAFFIC_ANNOTATION_FOR_TESTS));
9661
9662 r->Start();
9663 EXPECT_TRUE(r->is_pending());
9664
Wez0e717112018-06-18 23:09:229665 d.RunUntilCertificateRequested();
9666 EXPECT_TRUE(r->is_pending());
David Benjamin76a40ad2018-02-24 22:22:089667
9668 // There was an additional signing call on the private key (the one which
9669 // failed).
9670 EXPECT_EQ(2, private_key->sign_count());
9671
9672 // That caused another OnCertificateRequested call.
9673 EXPECT_EQ(1, d.on_certificate_requested_count());
9674 EXPECT_FALSE(d.received_data_before_response());
9675 EXPECT_EQ(0, d.bytes_received());
9676 }
9677}
9678
[email protected]316c1e5e2012-09-12 15:17:449679TEST_F(HTTPSRequestTest, ResumeTest) {
9680 // Test that we attempt a session resume when making two connections to the
9681 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:229682 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:449683 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:229684 SpawnedTestServer test_server(
9685 SpawnedTestServer::TYPE_HTTPS,
9686 ssl_options,
9687 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449688 ASSERT_TRUE(test_server.Start());
9689
9690 SSLClientSocket::ClearSessionCache();
9691
9692 {
9693 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369694 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169695 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9696 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449697
[email protected]f7022f32014-08-21 16:32:199698 r->Start();
9699 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449700
Wez2a31b222018-06-07 22:07:159701 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449702
9703 EXPECT_EQ(1, d.response_started_count());
9704 }
9705
9706 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
9707 CloseAllConnections();
9708
9709 {
9710 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369711 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169712 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9713 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449714
[email protected]f7022f32014-08-21 16:32:199715 r->Start();
9716 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449717
Wez2a31b222018-06-07 22:07:159718 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449719
9720 // The response will look like;
Steven Valdez0ef94d02018-11-19 23:28:139721 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]316c1e5e2012-09-12 15:17:449722 // insert abc
9723 // lookup abc
9724 // insert xyz
9725 //
9726 // With a newline at the end which makes the split think that there are
9727 // four lines.
9728
9729 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:299730 std::vector<std::string> lines = base::SplitString(
9731 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Steven Valdez0ef94d02018-11-19 23:28:139732 ASSERT_EQ(5u, lines.size()) << d.data_received();
[email protected]316c1e5e2012-09-12 15:17:449733
9734 std::string session_id;
9735
Steven Valdez0ef94d02018-11-19 23:28:139736 for (size_t i = 0; i < 3; i++) {
brettw3a2c6902015-07-06 19:43:299737 std::vector<std::string> parts = base::SplitString(
9738 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:449739 ASSERT_EQ(2u, parts.size());
Steven Valdez0ef94d02018-11-19 23:28:139740 if (i % 2 == 1) {
[email protected]316c1e5e2012-09-12 15:17:449741 EXPECT_EQ("insert", parts[0]);
9742 session_id = parts[1];
9743 } else {
9744 EXPECT_EQ("lookup", parts[0]);
Steven Valdez0ef94d02018-11-19 23:28:139745 if (i != 0)
9746 EXPECT_EQ(session_id, parts[1]);
[email protected]316c1e5e2012-09-12 15:17:449747 }
9748 }
9749 }
9750}
9751
Adam Langley32352ad2014-10-14 22:31:009752// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
9753// the result of fetching "ssl-session-cache" from the test server, indicates
Steven Valdez0ef94d02018-11-19 23:28:139754// that exactly two different sessions were inserted, with no real lookups.
9755// There will be a fake TLS 1.3 session ID lookup that can be ignored.
Adam Langley32352ad2014-10-14 22:31:009756static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:299757 std::vector<std::string> lines = base::SplitString(
9758 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:009759
Steven Valdez0ef94d02018-11-19 23:28:139760 size_t inserts = 0;
Adam Langley32352ad2014-10-14 22:31:009761 std::string session_id;
Steven Valdez0ef94d02018-11-19 23:28:139762 for (size_t i = 0; i < lines.size() - 1; i++) {
brettw3a2c6902015-07-06 19:43:299763 std::vector<std::string> parts = base::SplitString(
9764 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:009765 ASSERT_EQ(2u, parts.size());
Steven Valdez0ef94d02018-11-19 23:28:139766 if (parts[0] == "insert") {
9767 inserts++;
9768 if (i == 0) {
9769 session_id = parts[1];
9770 } else {
9771 EXPECT_NE(session_id, parts[1]);
9772 }
9773 } else if (parts[0] == "lookup") {
9774 // The fake TLS 1.3 session ID will produce fake lookups. Check that the
9775 // inserted ID was not looked up.
Adam Langley32352ad2014-10-14 22:31:009776 EXPECT_NE(session_id, parts[1]);
9777 }
9778 }
Steven Valdez0ef94d02018-11-19 23:28:139779 ASSERT_EQ(2u, inserts) << session_info;
Adam Langley32352ad2014-10-14 22:31:009780}
9781
[email protected]316c1e5e2012-09-12 15:17:449782TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
9783 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
9784 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:229785 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:449786 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:229787 SpawnedTestServer test_server(
9788 SpawnedTestServer::TYPE_HTTPS,
9789 ssl_options,
9790 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449791 ASSERT_TRUE(test_server.Start());
9792
9793 SSLClientSocket::ClearSessionCache();
9794
9795 {
9796 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369797 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169798 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9799 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449800
[email protected]f7022f32014-08-21 16:32:199801 r->Start();
9802 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449803
Wez2a31b222018-06-07 22:07:159804 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449805
9806 EXPECT_EQ(1, d.response_started_count());
9807 }
9808
9809 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:419810 HttpNetworkSession::Context session_context;
9811 session_context.host_resolver = default_context_.host_resolver();
9812 session_context.cert_verifier = default_context_.cert_verifier();
9813 session_context.transport_security_state =
9814 default_context_.transport_security_state();
9815 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:209816 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:419817 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:599818 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:419819 session_context.ssl_config_service = default_context_.ssl_config_service();
9820 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:449821 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:419822 session_context.http_server_properties =
9823 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:449824
mmenke6ddfbea2017-05-31 21:48:419825 HttpNetworkSession network_session(HttpNetworkSession::Params(),
9826 session_context);
zhongyi4928bd52017-02-08 02:16:279827 std::unique_ptr<HttpCache> cache(
9828 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
9829 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:449830
9831 default_context_.set_http_transaction_factory(cache.get());
9832
9833 {
9834 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369835 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169836 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9837 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449838
[email protected]f7022f32014-08-21 16:32:199839 r->Start();
9840 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449841
Wez2a31b222018-06-07 22:07:159842 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449843
9844 // The response will look like;
Steven Valdez0ef94d02018-11-19 23:28:139845 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]316c1e5e2012-09-12 15:17:449846 // insert abc
9847 // insert xyz
9848 //
9849 // With a newline at the end which makes the split think that there are
9850 // three lines.
9851
9852 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:009853 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449854 }
9855}
9856
Bence Béky98447b12018-05-08 03:14:019857class HTTPSFallbackTest : public TestWithScopedTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:559858 public:
fdorayf33fede2017-05-11 21:18:109859 HTTPSFallbackTest() : context_(true) {
Nick Harper2243e8002018-09-28 20:33:269860 ssl_config_service_ = std::make_unique<TestSSLConfigService>();
davidben095ebb52017-04-12 22:23:349861 context_.set_ssl_config_service(ssl_config_service_.get());
9862 }
Chris Watkins7a41d3552017-12-01 02:13:279863 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:559864
9865 protected:
davidben095ebb52017-04-12 22:23:349866 TestSSLConfigService* ssl_config_service() {
9867 return ssl_config_service_.get();
9868 }
9869
[email protected]48d2b7c52014-06-27 01:16:559870 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
9871 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:009872 context_.Init();
9873 delegate_.set_allow_certificate_errors(true);
9874
[email protected]48d2b7c52014-06-27 01:16:559875 SpawnedTestServer test_server(
9876 SpawnedTestServer::TYPE_HTTPS,
9877 ssl_options,
9878 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9879 ASSERT_TRUE(test_server.Start());
9880
tommycli59a63432015-11-06 00:10:559881 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169882 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:559883 request_->Start();
9884
Wez2a31b222018-06-07 22:07:159885 delegate_.RunUntilComplete();
[email protected]48d2b7c52014-06-27 01:16:559886 }
9887
davidben095ebb52017-04-12 22:23:349888 void ExpectConnection(int version) {
9889 EXPECT_EQ(1, delegate_.response_started_count());
9890 EXPECT_NE(0, delegate_.bytes_received());
9891 EXPECT_EQ(version, SSLConnectionStatusToVersion(
9892 request_->ssl_info().connection_status));
9893 }
9894
[email protected]48d2b7c52014-06-27 01:16:559895 void ExpectFailure(int error) {
9896 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509897 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:559898 }
9899
9900 private:
Ryan Sleevib8449e02018-07-15 04:31:079901 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:559902 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:479903 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:369904 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:559905};
9906
davidbenb127ca82015-06-15 19:05:429907// Tests the TLS 1.0 fallback doesn't happen.
9908TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:559909 SpawnedTestServer::SSLOptions ssl_options(
9910 SpawnedTestServer::SSLOptions::CERT_OK);
9911 ssl_options.tls_intolerant =
9912 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
9913
9914 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:559915 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:429916}
9917
davidben5a312152016-06-27 22:11:479918// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:559919TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:429920 SpawnedTestServer::SSLOptions ssl_options(
9921 SpawnedTestServer::SSLOptions::CERT_OK);
9922 ssl_options.tls_intolerant =
9923 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
9924
9925 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:559926 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
9927}
9928
davidben095ebb52017-04-12 22:23:349929// Tests that TLS 1.3 interference results in a dedicated error code.
9930TEST_F(HTTPSFallbackTest, TLSv1_3Interference) {
9931 SpawnedTestServer::SSLOptions ssl_options(
9932 SpawnedTestServer::SSLOptions::CERT_OK);
9933 ssl_options.tls_intolerant =
9934 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
9935 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
9936
9937 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
9938 ExpectFailure(ERR_SSL_VERSION_INTERFERENCE);
9939}
9940
9941// Tests that disabling TLS 1.3 leaves TLS 1.3 interference unnoticed.
9942TEST_F(HTTPSFallbackTest, TLSv1_3InterferenceDisableVersion) {
9943 SpawnedTestServer::SSLOptions ssl_options(
9944 SpawnedTestServer::SSLOptions::CERT_OK);
9945 ssl_options.tls_intolerant =
9946 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
9947 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_2);
9948
9949 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
9950 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_2);
9951}
9952
Bence Béky98447b12018-05-08 03:14:019953class HTTPSSessionTest : public TestWithScopedTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:249954 public:
fdorayf33fede2017-05-11 21:18:109955 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:599956 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:249957
9958 default_context_.set_network_delegate(&default_network_delegate_);
9959 default_context_.set_cert_verifier(&cert_verifier_);
9960 default_context_.Init();
9961 }
Chris Watkins7a41d3552017-12-01 02:13:279962 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:249963
9964 protected:
9965 MockCertVerifier cert_verifier_;
9966 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
9967 TestURLRequestContext default_context_;
9968};
9969
9970// Tests that session resumption is not attempted if an invalid certificate
9971// is presented.
9972TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
9973 SpawnedTestServer::SSLOptions ssl_options;
9974 ssl_options.record_resume = true;
9975 SpawnedTestServer test_server(
9976 SpawnedTestServer::TYPE_HTTPS,
9977 ssl_options,
9978 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9979 ASSERT_TRUE(test_server.Start());
9980
9981 SSLClientSocket::ClearSessionCache();
9982
9983 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:599984 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:249985 {
9986 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369987 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169988 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
9989 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:249990
[email protected]f7022f32014-08-21 16:32:199991 r->Start();
9992 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:249993
Wez2a31b222018-06-07 22:07:159994 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:249995
9996 EXPECT_EQ(1, d.response_started_count());
9997 }
9998
9999 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10000 CloseAllConnections();
10001
10002 // Now change the certificate to be acceptable (so that the response is
10003 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910004 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410005 {
10006 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610007 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610008 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10009 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410010
[email protected]f7022f32014-08-21 16:32:1910011 r->Start();
10012 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410013
Wez2a31b222018-06-07 22:07:1510014 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410015
10016 // The response will look like;
Steven Valdez0ef94d02018-11-19 23:28:1310017 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]a8fed1742013-12-27 02:14:2410018 // insert abc
10019 // insert xyz
10020 //
10021 // With a newline at the end which makes the split think that there are
10022 // three lines.
10023 //
10024 // If a session was presented (eg: a bug), then the response would look
10025 // like;
Steven Valdez0ef94d02018-11-19 23:28:1310026 // lookup uvw (TLS 1.3's compatibility session ID)
[email protected]a8fed1742013-12-27 02:14:2410027 // insert abc
10028 // lookup abc
10029 // insert xyz
10030
10031 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010032 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:2410033 }
10034}
10035
[email protected]dffe8242012-03-20 15:14:2710036// This the fingerprint of the "Testing CA" certificate used by the testserver.
10037// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5810038static const SHA256HashValue kOCSPTestCertFingerprint = {{
10039 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
10040 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
10041 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1510042}};
[email protected]dffe8242012-03-20 15:14:2710043
[email protected]51523f52013-07-31 21:57:2810044// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
10045// testserver.
mattm0b12a6f2016-11-29 19:57:1610046static const SHA256HashValue kOCSPTestCertSPKI = {{
10047 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
10048 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
10049 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
10050}};
[email protected]51523f52013-07-31 21:57:2810051
[email protected]dffe8242012-03-20 15:14:2710052// This is the policy OID contained in the certificates that testserver
10053// generates.
10054static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
10055
10056class HTTPSOCSPTest : public HTTPSRequestTest {
10057 public:
10058 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0910059 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0810060 ev_test_policy_(
10061 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
10062 kOCSPTestCertFingerprint,
10063 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0210064 }
10065
dcheng67be2b1f2014-10-27 21:47:2910066 void SetUp() override {
Ryan Sleevi8a9c9c12018-05-09 02:36:2310067 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
[email protected]ef2bf422012-05-11 03:27:0910068 context_.Init();
[email protected]dffe8242012-03-20 15:14:2710069
Ryan Sleevi24fe2682018-08-16 21:33:4610070 context_.cert_verifier()->SetConfig(GetCertVerifierConfig());
10071
[email protected]cba24642014-08-15 20:49:5910072 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2010073 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:4210074 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:5010075 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2710076
Matt Muellerfb271992018-01-30 18:10:4810077#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510078 SetGlobalCertNetFetcherForTesting(net::CreateCertNetFetcher(&context_));
10079#endif
10080
svaldez2135be52016-04-20 16:34:5310081#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0910082 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2710083#endif
10084 }
10085
dadrian612337a2016-07-20 22:36:5810086 void DoConnectionWithDelegate(
10087 const SpawnedTestServer::SSLOptions& ssl_options,
10088 TestDelegate* delegate,
10089 SSLInfo* out_ssl_info) {
10090 // Always overwrite |out_ssl_info|.
10091 out_ssl_info->Reset();
10092
[email protected]ce7d0cbc2013-05-03 18:57:2210093 SpawnedTestServer test_server(
10094 SpawnedTestServer::TYPE_HTTPS,
10095 ssl_options,
10096 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2710097 ASSERT_TRUE(test_server.Start());
10098
dadrian612337a2016-07-20 22:36:5810099 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1610100 std::unique_ptr<URLRequest> r(
10101 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
10102 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910103 r->Start();
[email protected]dffe8242012-03-20 15:14:2710104
Wez2a31b222018-06-07 22:07:1510105 delegate->RunUntilComplete();
dadrian612337a2016-07-20 22:36:5810106 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2710107
dadrian612337a2016-07-20 22:36:5810108 *out_ssl_info = r->ssl_info();
10109 }
10110
10111 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
10112 CertStatus* out_cert_status) {
10113 // Always overwrite |out_cert_status|.
10114 *out_cert_status = 0;
10115
10116 TestDelegate d;
10117 SSLInfo ssl_info;
10118 ASSERT_NO_FATAL_FAILURE(
10119 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
10120
10121 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2710122 }
10123
dcheng67be2b1f2014-10-27 21:47:2910124 ~HTTPSOCSPTest() override {
Matt Muellerfb271992018-01-30 18:10:4810125#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510126 ShutdownGlobalCertNetFetcher();
10127#endif
10128
svaldez2135be52016-04-20 16:34:5310129#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1810130 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2710131#endif
10132 }
10133
[email protected]a13234c2012-03-20 21:45:0210134 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4610135 // GetCertVerifierConfig() configures the URLRequestContext that will be used
10136 // for making connections to the testserver. This can be overridden in test
10137 // subclasses for different behaviour.
10138 virtual CertVerifier::Config GetCertVerifierConfig() {
10139 CertVerifier::Config config;
10140 config.enable_rev_checking = true;
10141 return config;
[email protected]a13234c2012-03-20 21:45:0210142 }
10143
danakj8522a25b2016-04-16 00:17:3610144 std::unique_ptr<ScopedTestRoot> test_root_;
Ryan Sleevib8449e02018-07-15 04:31:0710145 std::unique_ptr<TestSSLConfigService> ssl_config_service_;
[email protected]ef2bf422012-05-11 03:27:0910146 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610147 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2710148};
10149
[email protected]a13234c2012-03-20 21:45:0210150static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2010151#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0210152 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
10153 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0410154 // TODO(eroman): Should this also be the return value for
10155 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0210156 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
10157#else
10158 return 0;
10159#endif
10160}
10161
[email protected]3a86a712013-07-30 07:16:2010162// SystemSupportsHardFailRevocationChecking returns true iff the current
10163// operating system supports revocation checking and can distinguish between
10164// situations where a given certificate lacks any revocation information (eg:
10165// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
10166// revocation information cannot be obtained (eg: the CRL was unreachable).
10167// If it does not, then tests which rely on 'hard fail' behaviour should be
10168// skipped.
10169static bool SystemSupportsHardFailRevocationChecking() {
Eric Roman1b628daa2017-10-19 19:52:0410170#if defined(OS_WIN) || defined(USE_NSS_CERTS) || \
10171 defined(USE_BUILTIN_CERT_VERIFIER)
[email protected]3a86a712013-07-30 07:16:2010172 return true;
10173#else
10174 return false;
10175#endif
10176}
10177
[email protected]a13234c2012-03-20 21:45:0210178// SystemUsesChromiumEVMetadata returns true iff the current operating system
10179// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
10180// several tests are effected because our testing EV certificate won't be
10181// recognised as EV.
10182static bool SystemUsesChromiumEVMetadata() {
Eric Roman5f8d9d22017-10-17 02:32:5210183#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0110184 return true;
Eric Roman5f8d9d22017-10-17 02:32:5210185#else
10186 return false;
[email protected]05454a432012-03-20 20:04:0110187#endif
10188}
10189
mattmaf868e72016-09-23 23:25:2010190// Returns the expected CertStatus for tests that expect an online revocation
10191// check failure as a result of checking a test EV cert, which will not
10192// actually trigger an online revocation check on some platforms.
10193static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
10194 if (SystemUsesChromiumEVMetadata()) {
10195 return ExpectedCertStatusForFailedOnlineRevocationCheck();
10196 } else {
10197 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
10198 // be enabled, and thus there will not be a revocation check to fail.
10199 return 0u;
10200 }
10201}
10202
[email protected]b6f2de32012-08-17 04:35:0810203static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3910204#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0210205 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
10206 return false;
10207#else
10208 return true;
10209#endif
10210}
10211
davidbend1fb2f12014-11-08 02:51:0010212static bool SystemSupportsOCSPStapling() {
Eric Roman1b628daa2017-10-19 19:52:0410213#if defined(USE_NSS_CERTS) || defined(OS_WIN) || \
10214 defined(USE_BUILTIN_CERT_VERIFIER)
mathpc992e602015-10-21 20:34:0310215 return true;
mathpc992e602015-10-21 20:34:0310216#else
10217 return false;
10218#endif
davidbend1fb2f12014-11-08 02:51:0010219}
10220
[email protected]dffe8242012-03-20 15:14:2710221TEST_F(HTTPSOCSPTest, Valid) {
10222 if (!SystemSupportsOCSP()) {
10223 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10224 return;
10225 }
10226
[email protected]ce7d0cbc2013-05-03 18:57:2210227 SpawnedTestServer::SSLOptions ssl_options(
10228 SpawnedTestServer::SSLOptions::CERT_AUTO);
10229 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2710230
[email protected]924e9f92012-12-16 22:00:5310231 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210232 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710233
10234 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10235
[email protected]a13234c2012-03-20 21:45:0210236 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10237 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2710238
10239 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10240}
10241
10242TEST_F(HTTPSOCSPTest, Revoked) {
10243 if (!SystemSupportsOCSP()) {
10244 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10245 return;
10246 }
10247
[email protected]ce7d0cbc2013-05-03 18:57:2210248 SpawnedTestServer::SSLOptions ssl_options(
10249 SpawnedTestServer::SSLOptions::CERT_AUTO);
10250 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2710251
10252 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210253 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710254
[email protected]dffe8242012-03-20 15:14:2710255 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2710256 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10257 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10258}
10259
10260TEST_F(HTTPSOCSPTest, Invalid) {
10261 if (!SystemSupportsOCSP()) {
10262 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10263 return;
10264 }
10265
[email protected]ce7d0cbc2013-05-03 18:57:2210266 SpawnedTestServer::SSLOptions ssl_options(
10267 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810268 ssl_options.ocsp_status =
10269 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2710270
[email protected]924e9f92012-12-16 22:00:5310271 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210272 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710273
Eric Roman1b628daa2017-10-19 19:52:0410274#if defined(USE_BUILTIN_CERT_VERIFIER)
10275 // TODO(649017): This test uses soft-fail revocation checking, but returns an
10276 // invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
10277 // doesn't consider this a candidate for soft-fail (only considers
10278 // network-level failures as skippable).
10279 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
10280 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
10281#else
[email protected]a13234c2012-03-20 21:45:0210282 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2710283 cert_status & CERT_STATUS_ALL_ERRORS);
Eric Roman1b628daa2017-10-19 19:52:0410284#endif
[email protected]dffe8242012-03-20 15:14:2710285
10286 // Without a positive OCSP response, we shouldn't show the EV status.
10287 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10288 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10289}
[email protected]a13234c2012-03-20 21:45:0210290
Matt Mueller5339d862018-05-02 18:53:5710291TEST_F(HTTPSOCSPTest, IntermediateValid) {
10292 if (!SystemSupportsOCSP()) {
10293 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10294 return;
10295 }
10296
10297 SpawnedTestServer::SSLOptions ssl_options(
10298 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
10299 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10300 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10301
10302 CertStatus cert_status;
10303 DoConnection(ssl_options, &cert_status);
10304
10305 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10306
10307 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10308 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10309
10310 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10311}
10312
10313TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
10314 if (!SystemSupportsOCSP()) {
10315 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10316 return;
10317 }
10318
10319 SpawnedTestServer::SSLOptions ssl_options(
10320 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
10321 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10322 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10323 // Use an OCSP response for the intermediate that would be too old for a leaf
10324 // cert, but is still valid for an intermediate.
10325 ssl_options.ocsp_intermediate_date =
10326 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
10327
10328 CertStatus cert_status;
10329 DoConnection(ssl_options, &cert_status);
10330
10331 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10332
10333 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10334 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10335
10336 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10337}
10338
10339TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
10340 if (!SystemSupportsOCSP()) {
10341 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10342 return;
10343 }
10344
10345 SpawnedTestServer::SSLOptions ssl_options(
10346 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
10347 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10348 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10349 ssl_options.ocsp_intermediate_date =
10350 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
10351
10352 CertStatus cert_status;
10353 DoConnection(ssl_options, &cert_status);
10354
10355#if defined(USE_BUILTIN_CERT_VERIFIER)
10356 // The builtin verifier enforces the baseline requirements for max age of an
10357 // intermediate's OCSP response.
10358 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
10359 cert_status & CERT_STATUS_ALL_ERRORS);
10360 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
10361#else
10362 // The platform verifiers are more lenient.
10363 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10364 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10365 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10366#endif
10367 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10368}
10369
10370TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
10371 if (!SystemSupportsOCSP()) {
10372 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10373 return;
10374 }
10375
10376 SpawnedTestServer::SSLOptions ssl_options(
10377 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
10378 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10379 ssl_options.ocsp_intermediate_status =
10380 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
10381
10382 CertStatus cert_status;
10383 DoConnection(ssl_options, &cert_status);
10384
10385#if defined(OS_WIN)
10386 // TODO(mattm): why does CertVerifyProcWin accept this?
10387 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10388#else
10389 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10390#endif
10391 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
10392 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10393}
10394
davidbend1fb2f12014-11-08 02:51:0010395TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0310396 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0010397 LOG(WARNING)
10398 << "Skipping test because system doesn't support OCSP stapling";
10399 return;
10400 }
10401
10402 SpawnedTestServer::SSLOptions ssl_options(
10403 SpawnedTestServer::SSLOptions::CERT_AUTO);
10404 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10405 ssl_options.staple_ocsp_response = true;
10406 ssl_options.ocsp_server_unavailable = true;
10407
10408 CertStatus cert_status;
10409 DoConnection(ssl_options, &cert_status);
10410
10411 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10412
10413 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10414 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10415
10416 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10417}
10418
davidben6c3191b2014-11-21 22:38:0410419// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4810420#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0410421#define MAYBE_RevokedStapled DISABLED_RevokedStapled
10422#else
10423#define MAYBE_RevokedStapled RevokedStapled
10424#endif
10425TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0310426 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0010427 LOG(WARNING)
10428 << "Skipping test because system doesn't support OCSP stapling";
10429 return;
10430 }
10431
10432 SpawnedTestServer::SSLOptions ssl_options(
10433 SpawnedTestServer::SSLOptions::CERT_AUTO);
10434 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
10435 ssl_options.staple_ocsp_response = true;
10436 ssl_options.ocsp_server_unavailable = true;
10437
10438 CertStatus cert_status;
10439 DoConnection(ssl_options, &cert_status);
10440
10441 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10442 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10443 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10444}
10445
dadrian612337a2016-07-20 22:36:5810446static const struct OCSPVerifyTestData {
10447 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
10448 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
10449 OCSPVerifyResult::ResponseStatus response_status;
10450 bool has_revocation_status;
10451 OCSPRevocationStatus cert_status;
10452} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3110453 // 0
dadrian612337a2016-07-20 22:36:5810454 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10455 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10456 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10457 OCSPVerifyResult::PROVIDED,
10458 true,
10459 OCSPRevocationStatus::GOOD},
10460
Eric Roman8673b812017-09-20 18:57:3110461 // 1
dadrian612337a2016-07-20 22:36:5810462 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10463 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10464 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10465 OCSPVerifyResult::INVALID_DATE,
10466 false,
10467 OCSPRevocationStatus::UNKNOWN},
10468
Eric Roman8673b812017-09-20 18:57:3110469 // 2
dadrian612337a2016-07-20 22:36:5810470 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10471 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10472 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10473 OCSPVerifyResult::INVALID_DATE,
10474 false,
10475 OCSPRevocationStatus::UNKNOWN},
10476
Eric Roman8673b812017-09-20 18:57:3110477 // 3
dadrian612337a2016-07-20 22:36:5810478 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10479 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10480 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10481 OCSPVerifyResult::INVALID_DATE,
10482 false,
10483 OCSPRevocationStatus::UNKNOWN},
10484
Eric Roman8673b812017-09-20 18:57:3110485 // 4
dadrian612337a2016-07-20 22:36:5810486 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10487 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10488 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10489 OCSPVerifyResult::INVALID_DATE,
10490 false,
10491 OCSPRevocationStatus::UNKNOWN},
10492
Eric Roman8673b812017-09-20 18:57:3110493 // 5
dadrian612337a2016-07-20 22:36:5810494 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
10495 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10496 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10497 OCSPVerifyResult::ERROR_RESPONSE,
10498 false,
10499 OCSPRevocationStatus::UNKNOWN},
10500
Eric Roman8673b812017-09-20 18:57:3110501 // 6
dadrian612337a2016-07-20 22:36:5810502 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
10503 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10504 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10505 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
10506 false,
10507 OCSPRevocationStatus::UNKNOWN},
10508
Eric Roman8673b812017-09-20 18:57:3110509 // 7
dadrian612337a2016-07-20 22:36:5810510 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
10511 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10512 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10513 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
10514 false,
10515 OCSPRevocationStatus::UNKNOWN},
10516
Eric Roman8673b812017-09-20 18:57:3110517 // 8
dadrian612337a2016-07-20 22:36:5810518 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10519 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10520 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10521 OCSPVerifyResult::INVALID_DATE,
10522 false,
10523 OCSPRevocationStatus::UNKNOWN},
10524
Eric Roman8673b812017-09-20 18:57:3110525 // 9
dadrian612337a2016-07-20 22:36:5810526 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10527 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10528 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10529 OCSPVerifyResult::PROVIDED,
10530 true,
10531 OCSPRevocationStatus::UNKNOWN},
10532
Eric Roman8673b812017-09-20 18:57:3110533 // 10
dadrian612337a2016-07-20 22:36:5810534 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10535 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10536 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10537 OCSPVerifyResult::INVALID_DATE,
10538 false,
10539 OCSPRevocationStatus::UNKNOWN},
10540
Eric Roman8673b812017-09-20 18:57:3110541 // 11
dadrian612337a2016-07-20 22:36:5810542 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10543 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10544 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10545 OCSPVerifyResult::INVALID_DATE,
10546 false,
10547 OCSPRevocationStatus::UNKNOWN},
10548
Eric Roman8673b812017-09-20 18:57:3110549 // 12
dadrian612337a2016-07-20 22:36:5810550 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10551 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10552 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
10553 OCSPVerifyResult::BAD_PRODUCED_AT,
10554 false,
10555 OCSPRevocationStatus::UNKNOWN},
10556
Eric Roman8673b812017-09-20 18:57:3110557 // 13
dadrian612337a2016-07-20 22:36:5810558 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10559 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10560 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
10561 OCSPVerifyResult::BAD_PRODUCED_AT,
10562 false,
10563 OCSPRevocationStatus::UNKNOWN},
10564
Eric Roman8673b812017-09-20 18:57:3110565 // 14
dadrian612337a2016-07-20 22:36:5810566 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10567 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10568 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
10569 OCSPVerifyResult::BAD_PRODUCED_AT,
10570 false,
10571 OCSPRevocationStatus::UNKNOWN},
10572
Eric Roman8673b812017-09-20 18:57:3110573 // 15
dadrian612337a2016-07-20 22:36:5810574 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10575 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10576 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10577 OCSPVerifyResult::PROVIDED,
10578 true,
10579 OCSPRevocationStatus::GOOD},
10580
Eric Roman8673b812017-09-20 18:57:3110581 // 16
dadrian612337a2016-07-20 22:36:5810582 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10583 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
10584 {SpawnedTestServer::SSLOptions::OCSP_OK,
10585 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10586 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10587 OCSPVerifyResult::PROVIDED,
10588 true,
10589 OCSPRevocationStatus::GOOD},
10590
Eric Roman8673b812017-09-20 18:57:3110591 // 17
dadrian612337a2016-07-20 22:36:5810592 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10593 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
10594 {SpawnedTestServer::SSLOptions::OCSP_OK,
10595 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10596 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10597 OCSPVerifyResult::PROVIDED,
10598 true,
10599 OCSPRevocationStatus::GOOD},
10600
Eric Roman8673b812017-09-20 18:57:3110601 // 18
dadrian612337a2016-07-20 22:36:5810602 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10603 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
10604 {SpawnedTestServer::SSLOptions::OCSP_OK,
10605 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10606 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10607 OCSPVerifyResult::PROVIDED,
10608 true,
10609 OCSPRevocationStatus::GOOD},
10610
Eric Roman8673b812017-09-20 18:57:3110611 // 19
dadrian612337a2016-07-20 22:36:5810612 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10613 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
10614 {SpawnedTestServer::SSLOptions::OCSP_OK,
10615 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
10616 {SpawnedTestServer::SSLOptions::OCSP_OK,
10617 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10618 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10619 OCSPVerifyResult::INVALID_DATE,
10620 false,
10621 OCSPRevocationStatus::UNKNOWN},
10622
Eric Roman8673b812017-09-20 18:57:3110623 // 20
dadrian612337a2016-07-20 22:36:5810624 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10625 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10626 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10627 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10628 {SpawnedTestServer::SSLOptions::OCSP_OK,
10629 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10630 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10631 OCSPVerifyResult::PROVIDED,
10632 true,
10633 OCSPRevocationStatus::REVOKED},
10634
Eric Roman8673b812017-09-20 18:57:3110635 // 21
dadrian612337a2016-07-20 22:36:5810636 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10637 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10638 {SpawnedTestServer::SSLOptions::OCSP_OK,
10639 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10640 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10641 OCSPVerifyResult::PROVIDED,
10642 true,
10643 OCSPRevocationStatus::UNKNOWN},
10644
Eric Roman8673b812017-09-20 18:57:3110645 // 22
dadrian612337a2016-07-20 22:36:5810646 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10647 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10648 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10649 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
10650 {SpawnedTestServer::SSLOptions::OCSP_OK,
10651 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10652 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10653 OCSPVerifyResult::PROVIDED,
10654 true,
10655 OCSPRevocationStatus::UNKNOWN},
10656
Eric Roman8673b812017-09-20 18:57:3110657 // 23
dadrian612337a2016-07-20 22:36:5810658 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10659 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10660 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10661 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10662 false,
10663 OCSPRevocationStatus::UNKNOWN},
10664
Eric Roman8673b812017-09-20 18:57:3110665 // 24
dadrian612337a2016-07-20 22:36:5810666 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10667 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10668 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10669 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10670 false,
10671 OCSPRevocationStatus::UNKNOWN},
10672
Eric Roman8673b812017-09-20 18:57:3110673// These tests fail when using NSS for certificate verification, as NSS fails
10674// and doesn't return the partial path. As a result the OCSP checks being done
10675// at the CertVerifyProc layer cannot access the issuer certificate.
10676#if !defined(USE_NSS_CERTS)
10677 // 25
10678 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10679 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10680 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10681 OCSPVerifyResult::PROVIDED,
10682 true,
10683 OCSPRevocationStatus::REVOKED},
10684
10685 // 26
10686 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10687 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10688 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10689 OCSPVerifyResult::INVALID_DATE,
10690 false,
10691 OCSPRevocationStatus::UNKNOWN},
10692
10693 // 27
10694 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10695 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10696 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10697 OCSPVerifyResult::INVALID_DATE,
10698 false,
10699 OCSPRevocationStatus::UNKNOWN},
10700#endif
dadrian612337a2016-07-20 22:36:5810701};
10702
10703class HTTPSOCSPVerifyTest
10704 : public HTTPSOCSPTest,
10705 public testing::WithParamInterface<OCSPVerifyTestData> {};
10706
10707TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
10708 SpawnedTestServer::SSLOptions ssl_options(
10709 SpawnedTestServer::SSLOptions::CERT_AUTO);
10710 OCSPVerifyTestData test = GetParam();
10711
10712 ssl_options.ocsp_responses = test.ocsp_responses;
10713 ssl_options.ocsp_produced = test.ocsp_produced;
10714 ssl_options.staple_ocsp_response = true;
10715
10716 SSLInfo ssl_info;
10717 OCSPErrorTestDelegate delegate;
10718 ASSERT_NO_FATAL_FAILURE(
10719 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
10720
10721 // The SSLInfo must be extracted from |delegate| on error, due to how
10722 // URLRequest caches certificate errors.
10723 if (delegate.have_certificate_errors()) {
10724 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
10725 ssl_info = delegate.ssl_info();
10726 }
10727
10728 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
10729
10730 if (test.has_revocation_status)
10731 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
10732}
10733
10734INSTANTIATE_TEST_CASE_P(OCSPVerify,
10735 HTTPSOCSPVerifyTest,
10736 testing::ValuesIn(kOCSPVerifyData));
10737
mattm0b12a6f2016-11-29 19:57:1610738class HTTPSAIATest : public HTTPSOCSPTest {
10739 public:
Ryan Sleevi24fe2682018-08-16 21:33:4610740 CertVerifier::Config GetCertVerifierConfig() override {
10741 CertVerifier::Config config;
10742 return config;
mattm0b12a6f2016-11-29 19:57:1610743 }
10744};
10745
10746TEST_F(HTTPSAIATest, AIAFetching) {
10747 SpawnedTestServer::SSLOptions ssl_options(
10748 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
10749 SpawnedTestServer test_server(
10750 SpawnedTestServer::TYPE_HTTPS, ssl_options,
10751 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10752 ASSERT_TRUE(test_server.Start());
10753
Ryan Sleevi5b4702a2018-04-06 22:23:5610754 // Unmark the certificate's OID as EV, which will disable revocation
10755 // checking.
10756 ev_test_policy_.reset();
10757
mattm0b12a6f2016-11-29 19:57:1610758 TestDelegate d;
10759 d.set_allow_certificate_errors(true);
10760 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610761 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10762 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1610763
10764 r->Start();
10765 EXPECT_TRUE(r->is_pending());
10766
Wez2a31b222018-06-07 22:07:1510767 d.RunUntilComplete();
mattm0b12a6f2016-11-29 19:57:1610768
10769 EXPECT_EQ(1, d.response_started_count());
10770
10771 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4810772 EXPECT_EQ(OK, d.request_status());
10773 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10774 ASSERT_TRUE(r->ssl_info().cert);
10775 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1610776 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3410777 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1610778}
10779
[email protected]3a86a712013-07-30 07:16:2010780class HTTPSHardFailTest : public HTTPSOCSPTest {
10781 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4610782 CertVerifier::Config GetCertVerifierConfig() override {
10783 CertVerifier::Config config;
10784 config.require_rev_checking_local_anchors = true;
10785 return config;
[email protected]3a86a712013-07-30 07:16:2010786 }
10787};
10788
[email protected]3a86a712013-07-30 07:16:2010789TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
10790 if (!SystemSupportsOCSP()) {
10791 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10792 return;
10793 }
10794
10795 if (!SystemSupportsHardFailRevocationChecking()) {
10796 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
10797 << "revocation checking";
10798 return;
10799 }
10800
10801 SpawnedTestServer::SSLOptions ssl_options(
10802 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810803 ssl_options.ocsp_status =
10804 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2010805
10806 CertStatus cert_status;
10807 DoConnection(ssl_options, &cert_status);
10808
Eric Roman1b628daa2017-10-19 19:52:0410809#if defined(USE_BUILTIN_CERT_VERIFIER)
10810 // TODO(crbug.com/649017): Should we consider invalid response as
10811 // affirmatively revoked?
10812 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
10813 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
10814#else
10815 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
10816#endif
[email protected]3a86a712013-07-30 07:16:2010817
10818 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0410819 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2010820 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10821}
10822
[email protected]a13234c2012-03-20 21:45:0210823class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
10824 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4610825 CertVerifier::Config GetCertVerifierConfig() override {
10826 CertVerifier::Config config;
10827 return config;
[email protected]a13234c2012-03-20 21:45:0210828 }
10829};
10830
10831TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
10832 if (!SystemSupportsOCSP()) {
10833 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10834 return;
10835 }
10836
[email protected]ce7d0cbc2013-05-03 18:57:2210837 SpawnedTestServer::SSLOptions ssl_options(
10838 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810839 ssl_options.ocsp_status =
10840 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0210841
[email protected]924e9f92012-12-16 22:00:5310842 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210843 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210844
mattmaf868e72016-09-23 23:25:2010845 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0210846 cert_status & CERT_STATUS_ALL_ERRORS);
10847
10848 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0810849 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10850 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210851}
10852
[email protected]be0fff62013-08-29 23:37:4810853TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
10854 if (!SystemSupportsOCSP()) {
10855 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10856 return;
10857 }
10858
10859 SpawnedTestServer::SSLOptions ssl_options(
10860 SpawnedTestServer::SSLOptions::CERT_AUTO);
10861 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]be0fff62013-08-29 23:37:4810862
10863 CertStatus cert_status;
10864 DoConnection(ssl_options, &cert_status);
10865
mattm1a282f52016-11-10 21:49:4210866// Currently only works for Windows and OS X. When using NSS, it's not
10867// possible to determine whether the check failed because of actual
10868// revocation or because there was an OCSP failure.
10869#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4810870 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10871#else
10872 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10873#endif
10874
10875 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10876 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10877 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
10878}
10879
[email protected]a13234c2012-03-20 21:45:0210880TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
10881 if (!SystemSupportsOCSP()) {
10882 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10883 return;
10884 }
10885
[email protected]ce7d0cbc2013-05-03 18:57:2210886 SpawnedTestServer::SSLOptions ssl_options(
10887 SpawnedTestServer::SSLOptions::CERT_AUTO);
10888 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0210889
10890 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210891 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210892
10893 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10894
10895 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10896 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0810897 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10898 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210899}
10900
10901TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
10902 if (!SystemSupportsOCSP()) {
10903 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10904 return;
10905 }
10906
[email protected]ce7d0cbc2013-05-03 18:57:2210907 SpawnedTestServer::SSLOptions ssl_options(
10908 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810909 ssl_options.ocsp_status =
10910 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2210911 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
10912 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
10913 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0210914
10915 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210916 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210917
mattmaf868e72016-09-23 23:25:2010918 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0210919 cert_status & CERT_STATUS_ALL_ERRORS);
10920
10921 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0810922 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10923 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210924}
10925
[email protected]51523f52013-07-31 21:57:2810926TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
10927 if (!SystemSupportsOCSP()) {
10928 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10929 return;
10930 }
10931
10932 SpawnedTestServer::SSLOptions ssl_options(
10933 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810934 ssl_options.ocsp_status =
10935 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2210936 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
10937 cert_verifier_config.crl_set =
10938 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {});
10939 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2810940
10941 CertStatus cert_status;
10942 DoConnection(ssl_options, &cert_status);
10943
10944 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
10945 // revocation check for EV.
10946 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10947 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10948 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10949 EXPECT_FALSE(
10950 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
10951}
10952
10953TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
10954 if (!SystemSupportsOCSP()) {
10955 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10956 return;
10957 }
10958
[email protected]ce7d0cbc2013-05-03 18:57:2210959 SpawnedTestServer::SSLOptions ssl_options(
10960 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810961 ssl_options.ocsp_status =
10962 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2210963 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
10964 cert_verifier_config.crl_set = CRLSet::EmptyCRLSetForTesting();
10965 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0210966
[email protected]51523f52013-07-31 21:57:2810967 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1210968 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210969
[email protected]51523f52013-07-31 21:57:2810970 // Even with a fresh CRLSet, we should still do online revocation checks when
10971 // the certificate chain isn't covered by the CRLSet, which it isn't in this
10972 // test.
mattmaf868e72016-09-23 23:25:2010973 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2810974 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0210975
[email protected]51523f52013-07-31 21:57:2810976 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0210977 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2810978 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210979}
10980
10981class HTTPSCRLSetTest : public HTTPSOCSPTest {
10982 protected:
Ryan Sleevi24fe2682018-08-16 21:33:4610983 CertVerifier::Config GetCertVerifierConfig() override {
10984 CertVerifier::Config config;
10985 return config;
Ryan Sleevi5b4702a2018-04-06 22:23:5610986 }
10987
10988 void SetUp() override {
10989 HTTPSOCSPTest::SetUp();
10990
10991 // Unmark the certificate's OID as EV, which should disable revocation
10992 // checking (as per the user preference).
10993 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0210994 }
10995};
10996
10997TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2210998 SpawnedTestServer::SSLOptions ssl_options(
10999 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811000 ssl_options.ocsp_status =
11001 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Ryan Sleevib369d712018-08-20 16:43:2211002 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11003 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11004 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]a13234c2012-03-20 21:45:0211005
[email protected]924e9f92012-12-16 22:00:5311006 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211007 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211008
11009 // If we're not trying EV verification then, even if the CRLSet has expired,
11010 // we don't fall back to online revocation checks.
11011 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11012 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11013 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11014}
[email protected]51523f52013-07-31 21:57:2811015
Ryan Sleevi5b4702a2018-04-06 22:23:5611016TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
11017 // Test that when online revocation checking is disabled, and the leaf
11018 // certificate is not EV, that no revocation checking actually happens.
11019 if (!SystemSupportsOCSP()) {
11020 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11021 return;
11022 }
11023
11024 SpawnedTestServer::SSLOptions ssl_options(
11025 SpawnedTestServer::SSLOptions::CERT_AUTO);
11026 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Ryan Sleevib369d712018-08-20 16:43:2211027
11028 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11029 cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
11030 context_.cert_verifier()->SetConfig(cert_verifier_config);
Ryan Sleevi5b4702a2018-04-06 22:23:5611031
11032 CertStatus cert_status;
11033 DoConnection(ssl_options, &cert_status);
11034
11035 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11036
11037 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11038 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11039}
11040
[email protected]51523f52013-07-31 21:57:2811041TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2511042#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2811043 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11044 return;
11045#endif
11046
11047 SpawnedTestServer::SSLOptions ssl_options(
11048 SpawnedTestServer::SSLOptions::CERT_AUTO);
11049 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11050 ssl_options.cert_serial = 10;
Ryan Sleevib369d712018-08-20 16:43:2211051
11052 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11053 cert_verifier_config.crl_set =
11054 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {});
11055 context_.cert_verifier()->SetConfig(cert_verifier_config);
[email protected]51523f52013-07-31 21:57:2811056
11057 CertStatus cert_status = 0;
11058 DoConnection(ssl_options, &cert_status);
11059
11060 // If the certificate is recorded as revoked in the CRLSet, that should be
11061 // reflected without online revocation checking.
11062 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11063 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5611064 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2811065}
Adam Langleyea6d6782017-12-05 23:57:3311066
11067TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
11068#if defined(OS_ANDROID)
11069 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11070 return;
11071#endif
11072
11073 SpawnedTestServer::SSLOptions ssl_options(
11074 SpawnedTestServer::SSLOptions::CERT_AUTO);
11075 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11076 static const char kCommonName[] = "Test CN";
11077 ssl_options.cert_common_name = kCommonName;
11078
11079 {
Ryan Sleevib369d712018-08-20 16:43:2211080 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11081 cert_verifier_config.crl_set =
11082 CRLSet::ForTesting(false, nullptr, "", kCommonName, {});
11083 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3311084
11085 CertStatus cert_status = 0;
11086 DoConnection(ssl_options, &cert_status);
11087
11088 // If the certificate is recorded as revoked in the CRLSet, that should be
11089 // reflected without online revocation checking.
11090 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11091 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5611092 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3311093 }
11094
11095 const uint8_t kTestServerSPKISHA256[32] = {
11096 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
11097 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
11098 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
11099 };
11100 const std::string spki_hash(
11101 reinterpret_cast<const char*>(kTestServerSPKISHA256),
11102 sizeof(kTestServerSPKISHA256));
11103
11104 {
Ryan Sleevib369d712018-08-20 16:43:2211105 CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
11106 cert_verifier_config.crl_set =
11107 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash});
11108 context_.cert_verifier()->SetConfig(cert_verifier_config);
Adam Langleyea6d6782017-12-05 23:57:3311109
11110 CertStatus cert_status = 0;
11111 DoConnection(ssl_options, &cert_status);
11112
11113 // When the correct SPKI hash is specified, the connection should succeed
11114 // even though the subject is listed in the CRLSet.
11115 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11116 }
11117}
[email protected]316c1e5e2012-09-12 15:17:4411118#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2711119
Sergey Ulanovc4580e72017-09-13 23:30:1111120#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
11121 !defined(OS_FUCHSIA)
11122// FTP uses a second TCP connection with the port number allocated dynamically
11123// on the server side, so it would be hard to make RemoteTestServer proxy FTP
11124// connections reliably. FTP tests are disabled on platforms that use
11125// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3111126class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1111127 public:
[email protected]d9fca99a2012-02-24 16:16:2011128 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0511129 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5511130 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4711131 // Can't use |default_context_|'s HostResolver to set up the
11132 // FTPTransactionFactory because it hasn't been created yet.
Ryan Sleevib8449e02018-07-15 04:31:0711133 default_context().set_host_resolver(&host_resolver_);
mmenke9f2ec60c2015-06-01 20:59:4711134 }
11135
11136 // URLRequestTest interface:
11137 void SetUpFactory() override {
11138 // Add FTP support to the default URLRequestContext.
11139 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0511140 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4711141 }
11142
11143 std::string GetTestFileContents() {
11144 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1911145 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4711146 path = path.Append(kTestFilePath);
11147 path = path.AppendASCII(kFtpTestFile);
11148 std::string contents;
11149 EXPECT_TRUE(base::ReadFileToString(path, &contents));
11150 return contents;
[email protected]95409e12010-08-17 20:07:1111151 }
11152
[email protected]b89ca032009-08-31 21:41:3111153 protected:
mmenke9f2ec60c2015-06-01 20:59:4711154 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4711155
tommycli59a63432015-11-06 00:10:5511156 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3111157};
11158
[email protected]d2a133182012-08-05 16:44:0811159// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0911160TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0811161 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0811162
11163 TestDelegate d;
11164 {
Ryan Sleevib8449e02018-07-15 04:31:0711165 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611166 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911167 r->Start();
11168 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0811169
Wez2a31b222018-06-07 22:07:1511170 d.RunUntilComplete();
[email protected]d2a133182012-08-05 16:44:0811171
[email protected]f7022f32014-08-21 16:32:1911172 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5011173 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0811174 }
11175}
11176
mmenke9f2ec60c2015-06-01 20:59:4711177TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5511178 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111179
[email protected]a25e90e2009-09-09 17:05:3711180 TestDelegate d;
11181 {
Ryan Sleevib8449e02018-07-15 04:31:0711182 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611183 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
11184 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911185 r->Start();
11186 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711187
Wez2a31b222018-06-07 22:07:1511188 d.RunUntilComplete();
[email protected]a25e90e2009-09-09 17:05:3711189
[email protected]f7022f32014-08-21 16:32:1911190 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711191 EXPECT_EQ(1, d.response_started_count());
11192 EXPECT_FALSE(d.received_data_before_response());
11193 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5511194 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911195 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511196 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911197 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:3711198 }
11199}
11200
mmenke9f2ec60c2015-06-01 20:59:4711201TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5511202 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111203
[email protected]dd265012009-01-08 20:45:2711204 TestDelegate d;
11205 {
Ryan Sleevib8449e02018-07-15 04:31:0711206 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611207 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
11208 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911209 r->Start();
11210 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711211
Wez2a31b222018-06-07 22:07:1511212 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711213
[email protected]f7022f32014-08-21 16:32:1911214 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711215 EXPECT_EQ(1, d.response_started_count());
11216 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711217 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511218 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911219 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511220 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911221 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:2711222 }
11223}
11224
mmenke9f2ec60c2015-06-01 20:59:4711225TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5511226 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111227
[email protected]dd265012009-01-08 20:45:2711228 TestDelegate d;
11229 {
Ryan Sleevib8449e02018-07-15 04:31:0711230 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511231 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11232 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611233 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911234 r->Start();
11235 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711236
Wez2a31b222018-06-07 22:07:1511237 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711238
[email protected]f7022f32014-08-21 16:32:1911239 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4711240 EXPECT_EQ(1, d.response_started_count());
11241 EXPECT_FALSE(d.received_data_before_response());
11242 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511243 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911244 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511245 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911246 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2511247
11248 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1911249 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2511250 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2711251 }
11252}
11253
mmenke9f2ec60c2015-06-01 20:59:4711254TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5511255 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111256
[email protected]dd265012009-01-08 20:45:2711257 TestDelegate d;
11258 {
Ryan Sleevib8449e02018-07-15 04:31:0711259 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511260 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11261 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611262 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911263 r->Start();
11264 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711265
Wez2a31b222018-06-07 22:07:1511266 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711267
[email protected]f7022f32014-08-21 16:32:1911268 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711269 EXPECT_EQ(1, d.response_started_count());
11270 EXPECT_FALSE(d.received_data_before_response());
11271 EXPECT_EQ(d.bytes_received(), 0);
11272 }
11273}
11274
mmenke9f2ec60c2015-06-01 20:59:4711275TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5511276 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111277
[email protected]8b8a197d2009-08-26 15:57:5811278 TestDelegate d;
11279 // Set correct login credentials. The delegate will be asked for them when
11280 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811281 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811282 {
Ryan Sleevib8449e02018-07-15 04:31:0711283 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511284 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11285 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611286 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911287 r->Start();
11288 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811289
Wez2a31b222018-06-07 22:07:1511290 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5811291
[email protected]f7022f32014-08-21 16:32:1911292 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811293 EXPECT_EQ(1, d.response_started_count());
11294 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711295 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811296 }
11297}
11298
mmenke9f2ec60c2015-06-01 20:59:4711299TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5511300 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111301
[email protected]dd265012009-01-08 20:45:2711302 TestDelegate d;
11303 {
Ryan Sleevib8449e02018-07-15 04:31:0711304 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511305 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
11306 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611307 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911308 r->Start();
11309 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711310
Wez2a31b222018-06-07 22:07:1511311 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2711312
[email protected]f7022f32014-08-21 16:32:1911313 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711314 EXPECT_EQ(1, d.response_started_count());
11315 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711316 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2711317 }
11318}
[email protected]8b8a197d2009-08-26 15:57:5811319
mmenke9f2ec60c2015-06-01 20:59:4711320TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5511321 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111322
[email protected]8b8a197d2009-08-26 15:57:5811323 TestDelegate d;
11324 // Set correct login credentials. The delegate will be asked for them when
11325 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811326 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811327 {
Ryan Sleevib8449e02018-07-15 04:31:0711328 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511329 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
11330 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611331 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911332 r->Start();
11333 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811334
Wez2a31b222018-06-07 22:07:1511335 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5811336
[email protected]f7022f32014-08-21 16:32:1911337 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811338 EXPECT_EQ(1, d.response_started_count());
11339 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711340 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811341 }
11342}
[email protected]60a3df52009-09-22 16:13:2411343
mmenke9f2ec60c2015-06-01 20:59:4711344TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5511345 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111346
danakj8522a25b2016-04-16 00:17:3611347 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2411348 {
11349 // Pass correct login identity in the URL.
Ryan Sleevib8449e02018-07-15 04:31:0711350 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511351 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11352 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611353 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911354 r->Start();
11355 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411356
Wez2a31b222018-06-07 22:07:1511357 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2411358
[email protected]f7022f32014-08-21 16:32:1911359 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411360 EXPECT_EQ(1, d->response_started_count());
11361 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711362 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411363 }
11364
11365 d.reset(new TestDelegate);
11366 {
11367 // This request should use cached identity from previous request.
Ryan Sleevib8449e02018-07-15 04:31:0711368 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611369 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
11370 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911371 r->Start();
11372 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411373
Wez2a31b222018-06-07 22:07:1511374 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2411375
[email protected]f7022f32014-08-21 16:32:1911376 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411377 EXPECT_EQ(1, d->response_started_count());
11378 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711379 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411380 }
11381}
11382
mmenke9f2ec60c2015-06-01 20:59:4711383TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5511384 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111385
danakj8522a25b2016-04-16 00:17:3611386 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2411387 // Set correct login credentials. The delegate will be asked for them when
11388 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811389 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2411390 {
Ryan Sleevib8449e02018-07-15 04:31:0711391 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:5511392 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11393 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611394 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911395 r->Start();
11396 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411397
Wez2a31b222018-06-07 22:07:1511398 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2411399
[email protected]f7022f32014-08-21 16:32:1911400 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411401 EXPECT_EQ(1, d->response_started_count());
11402 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711403 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411404 }
11405
11406 // Use a new delegate without explicit credentials. The cached ones should be
11407 // used.
11408 d.reset(new TestDelegate);
11409 {
11410 // Don't pass wrong credentials in the URL, they would override valid cached
11411 // ones.
Ryan Sleevib8449e02018-07-15 04:31:0711412 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611413 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
11414 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911415 r->Start();
11416 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411417
Wez2a31b222018-06-07 22:07:1511418 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2411419
[email protected]f7022f32014-08-21 16:32:1911420 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411421 EXPECT_EQ(1, d->response_started_count());
11422 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711423 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411424 }
11425}
ricea3a1c71f2016-06-17 10:05:2611426
11427TEST_F(URLRequestTestFTP, RawBodyBytes) {
11428 ASSERT_TRUE(ftp_test_server_.Start());
11429
11430 TestDelegate d;
11431 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611432 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
11433 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2611434 req->Start();
Wez2a31b222018-06-07 22:07:1511435 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:2611436
11437 EXPECT_EQ(6, req->GetRawBodyBytes());
11438}
11439
brettwa1228ebb2016-10-28 03:51:3411440#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5111441
ttuttlec0c828492015-05-15 01:25:5511442TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
11443 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0711444 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611445 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5511446
11447 EXPECT_FALSE(req->response_info().network_accessed);
11448
11449 req->Start();
Wez2a31b222018-06-07 22:07:1511450 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5511451
11452 EXPECT_EQ(1, default_network_delegate_.completed_requests());
11453 EXPECT_FALSE(req->response_info().network_accessed);
11454}
11455
11456TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
11457 MockHostResolver host_resolver;
11458 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
11459 TestURLRequestContext context(true);
11460 context.set_network_delegate(&network_delegate);
11461 context.set_host_resolver(&host_resolver);
11462 host_resolver.rules()->AddSimulatedFailure("*");
11463 context.Init();
11464
11465 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1611466 std::unique_ptr<URLRequest> req(
11467 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
11468 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5511469
11470 EXPECT_FALSE(req->response_info().network_accessed);
11471
11472 req->Start();
Wez2a31b222018-06-07 22:07:1511473 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5511474 EXPECT_TRUE(req->response_info().network_accessed);
11475}
11476
mmenkeed0498b2015-12-08 23:20:4211477// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2211478// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4211479TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2211480 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0711481 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611482 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
11483 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2211484
danakj8522a25b2016-04-16 00:17:3611485 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2211486 req.get(), &default_network_delegate_,
11487 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4211488 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
11489 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2211490
11491 req->Start();
11492 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2211493 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5011494 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2211495 EXPECT_EQ(0, d.received_redirect_count());
11496}
11497
Andrey Kosyakov2e893e62017-08-31 17:00:5211498TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411499 ASSERT_TRUE(http_test_server()->Start());
11500 TestURLRequestContext context;
11501 GURL url(http_test_server()->GetURL("/cachetime"));
11502 TestDelegate delegate;
11503 HttpRequestHeaders extra_headers;
11504 extra_headers.SetHeader("X-Foo", "bar");
11505
11506 {
Andrey Kosyakov2e893e62017-08-31 17:00:5211507 HttpRawRequestHeaders raw_req_headers;
11508 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
11509
Andrey Kosyakov83a6eee2017-08-14 19:20:0411510 std::unique_ptr<URLRequest> r(context.CreateRequest(
11511 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11512 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5211513 r->SetRequestHeadersCallback(base::Bind(
11514 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
11515 r->SetResponseHeadersCallback(base::Bind(
11516 [](scoped_refptr<const HttpResponseHeaders>* left,
11517 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
11518 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411519 r->Start();
11520 while (!delegate.response_started_count())
11521 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5211522 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411523 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5211524 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411525 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211526 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411527 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211528 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
11529 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
11530 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
11531 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411532 }
11533 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411534 std::unique_ptr<URLRequest> r(context.CreateRequest(
11535 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11536 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5211537 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411538 FAIL() << "Callback should not be called unless request is sent";
11539 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5211540 r->SetResponseHeadersCallback(
11541 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
11542 FAIL() << "Callback should not be called unless request is sent";
11543 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411544 r->Start();
Wez2a31b222018-06-07 22:07:1511545 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0411546 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411547 }
11548}
11549
Andrey Kosyakov2e893e62017-08-31 17:00:5211550TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411551 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5211552 HttpRawRequestHeaders raw_req_headers;
11553 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
11554
Andrey Kosyakov83a6eee2017-08-14 19:20:0411555 TestURLRequestContext context;
11556 TestDelegate delegate;
11557 HttpRequestHeaders extra_headers;
11558 extra_headers.SetHeader("X-Foo", "bar");
Andrey Kosyakov83a6eee2017-08-14 19:20:0411559 GURL url(http_test_server()->GetURL("/redirect-test.html"));
Ryan Sleevib8449e02018-07-15 04:31:0711560 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0411561 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11562 r->SetExtraRequestHeaders(extra_headers);
11563 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5211564 base::Unretained(&raw_req_headers)));
11565 r->SetResponseHeadersCallback(base::Bind(
11566 [](scoped_refptr<const HttpResponseHeaders>* left,
11567 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
11568 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411569 r->Start();
Wez0e717112018-06-18 23:09:2211570 delegate.RunUntilRedirect();
Andrey Kosyakov83a6eee2017-08-14 19:20:0411571
11572 ASSERT_EQ(1, delegate.received_redirect_count());
11573 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5211574 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411575 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211576 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411577 EXPECT_EQ("gzip, deflate", value);
11578 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5211579 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
11580 raw_req_headers.request_line());
11581 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
11582 EXPECT_EQ(302, raw_resp_headers->response_code());
11583 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411584
Andrey Kosyakov2e893e62017-08-31 17:00:5211585 raw_req_headers = HttpRawRequestHeaders();
11586 raw_resp_headers = nullptr;
Chong Zhang7607f1f2018-06-01 20:52:2011587 r->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:1511588 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5211589 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411590 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211591 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411592 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211593 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
11594 raw_req_headers.request_line());
11595 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411596}
11597
Andrey Kosyakov2e893e62017-08-31 17:00:5211598TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411599 TestDelegate request_delegate;
11600
Ryan Sleevib8449e02018-07-15 04:31:0711601 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0411602 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
11603 TRAFFIC_ANNOTATION_FOR_TESTS));
11604 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
11605 FAIL() << "Callback should not be called unless request is sent";
11606 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5211607 r->SetResponseHeadersCallback(
11608 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
11609 FAIL() << "Callback should not be called unless request is sent";
11610 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411611 r->Start();
Wez2a31b222018-06-07 22:07:1511612 request_delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0411613 EXPECT_FALSE(r->is_pending());
11614}
11615
Andrey Kosyakov2e893e62017-08-31 17:00:5211616TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411617 ASSERT_TRUE(http_test_server()->Start());
11618 GURL url(http_test_server()->GetURL("/auth-basic"));
11619
11620 TestURLRequestContext context;
11621 TestDelegate delegate;
11622
11623 delegate.set_credentials(AuthCredentials(kUser, kSecret));
11624 HttpRequestHeaders extra_headers;
11625 extra_headers.SetHeader("X-Foo", "bar");
11626
Andrey Kosyakov2e893e62017-08-31 17:00:5211627 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
11628 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0411629
Andrey Kosyakov2e893e62017-08-31 17:00:5211630 using RespHeadersVector =
11631 std::vector<scoped_refptr<const HttpResponseHeaders>>;
11632 RespHeadersVector raw_resp_headers;
11633
11634 auto req_headers_callback = base::Bind(
11635 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
11636 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
11637 },
11638 &raw_req_headers);
11639 auto resp_headers_callback = base::Bind(
11640 [](RespHeadersVector* vec,
11641 scoped_refptr<const HttpResponseHeaders> headers) {
11642 vec->push_back(headers);
11643 },
11644 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0411645 std::unique_ptr<URLRequest> r(context.CreateRequest(
11646 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11647 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5211648 r->SetRequestHeadersCallback(req_headers_callback);
11649 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0411650 r->Start();
Wez2a31b222018-06-07 22:07:1511651 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0411652 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5211653 ASSERT_EQ(raw_req_headers.size(), 2u);
11654 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0411655 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5211656 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
11657 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411658 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211659 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
11660 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411661 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5211662 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
11663 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
11664 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
11665 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
11666
11667 std::unique_ptr<URLRequest> r2(context.CreateRequest(
11668 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
11669 r2->SetExtraRequestHeaders(extra_headers);
11670 r2->SetRequestHeadersCallback(req_headers_callback);
11671 r2->SetResponseHeadersCallback(resp_headers_callback);
11672 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
11673 r2->Start();
Wez2a31b222018-06-07 22:07:1511674 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5211675 EXPECT_FALSE(r2->is_pending());
11676 ASSERT_EQ(raw_req_headers.size(), 3u);
11677 ASSERT_EQ(raw_resp_headers.size(), 3u);
11678 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
11679 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
11680 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
11681 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0411682}
11683
Andrey Kosyakov2e893e62017-08-31 17:00:5211684TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0411685 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
11686 TestDelegate d;
Ryan Sleevib8449e02018-07-15 04:31:0711687 std::unique_ptr<URLRequest> r(default_context().CreateRequest(
Andrey Kosyakov83a6eee2017-08-14 19:20:0411688 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11689 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5211690 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0411691 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5211692 r->SetResponseHeadersCallback(
11693 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
11694 FAIL() << "Callback should not be called for non-HTTP schemes";
11695 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0411696 r->Start();
Wez2a31b222018-06-07 22:07:1511697 d.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0411698 EXPECT_FALSE(r->is_pending());
11699}
11700
Carlos ILaef65d62018-06-04 21:24:1311701TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
11702 TestDelegate d;
11703 BlockingNetworkDelegate network_delegate(
11704 BlockingNetworkDelegate::SYNCHRONOUS);
11705 const GURL kOriginalUrl("https://original.test");
11706 const GURL kRedirectUrl("http://redirect.test");
11707 network_delegate.set_redirect_url(kRedirectUrl);
11708 TestURLRequestContext context(true /* delay_initialization */);
11709 context.set_network_delegate(&network_delegate);
11710 context.Init();
11711
11712 std::unique_ptr<URLRequest> r(context.CreateRequest(
11713 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11714 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1311715 r->Start();
Wez0e717112018-06-18 23:09:2211716 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1311717 GURL::Replacements replacements;
11718 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
11719 // was set.
11720 replacements.SetSchemeStr("https");
11721 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
11722 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4411723 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1311724}
11725
11726TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
11727 TestDelegate d;
11728 BlockingNetworkDelegate network_delegate(
11729 BlockingNetworkDelegate::SYNCHRONOUS);
11730 const GURL kOriginalUrl("https://original.test");
11731 const GURL kRedirectUrl("http://redirect.test:80");
11732 network_delegate.set_redirect_url(kRedirectUrl);
11733 TestURLRequestContext context(true /* delay_initialization */);
11734 context.set_network_delegate(&network_delegate);
11735 context.Init();
11736
11737 std::unique_ptr<URLRequest> r(context.CreateRequest(
11738 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11739 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1311740 r->Start();
Wez0e717112018-06-18 23:09:2211741 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1311742 GURL::Replacements replacements;
11743 // The URL host should have not been changed.
11744 EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
11745 // The scheme should now be https, and the effective port should now be 443.
11746 EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
11747 EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
Carlos IL0d67fc72018-06-22 17:18:4411748 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1311749}
11750
11751TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
11752 TestDelegate d;
11753 BlockingNetworkDelegate network_delegate(
11754 BlockingNetworkDelegate::SYNCHRONOUS);
11755 const GURL kOriginalUrl("https://original.test");
11756 const GURL kRedirectUrl("http://redirect.test:1234");
11757 network_delegate.set_redirect_url(kRedirectUrl);
11758 TestURLRequestContext context(true /* delay_initialization */);
11759 context.set_network_delegate(&network_delegate);
11760 context.Init();
11761
11762 std::unique_ptr<URLRequest> r(context.CreateRequest(
11763 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11764 r->set_upgrade_if_insecure(true);
Carlos ILaef65d62018-06-04 21:24:1311765 r->Start();
Wez0e717112018-06-18 23:09:2211766 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1311767 GURL::Replacements replacements;
11768 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
11769 // was set, nonstandard port should not have been modified.
11770 replacements.SetSchemeStr("https");
11771 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
11772 d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4411773 EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1311774}
11775
11776TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
11777 TestDelegate d;
11778 BlockingNetworkDelegate network_delegate(
11779 BlockingNetworkDelegate::SYNCHRONOUS);
11780 const GURL kOriginalUrl("https://original.test");
11781 const GURL kRedirectUrl("http://redirect.test");
11782 network_delegate.set_redirect_url(kRedirectUrl);
11783 TestURLRequestContext context(true /* delay_initialization */);
11784 context.set_network_delegate(&network_delegate);
11785 context.Init();
11786 std::unique_ptr<URLRequest> r(context.CreateRequest(
11787 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
11788 r->set_upgrade_if_insecure(false);
Carlos ILaef65d62018-06-04 21:24:1311789 r->Start();
Wez0e717112018-06-18 23:09:2211790 d.RunUntilRedirect();
Carlos ILaef65d62018-06-04 21:24:1311791 // The redirect URL should not be changed if the upgrade_if_insecure flag is
11792 // not set.
11793 EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
Carlos IL0d67fc72018-06-22 17:18:4411794 EXPECT_FALSE(d.redirect_info().insecure_scheme_was_upgraded);
Carlos ILaef65d62018-06-04 21:24:1311795}
11796
Paul Jensen60e45532018-02-19 16:04:1811797// Test that URLRequests get properly tagged.
11798#if defined(OS_ANDROID)
11799TEST_F(URLRequestTestHTTP, TestTagging) {
11800 ASSERT_TRUE(http_test_server()->Start());
11801
11802 // The tag under which the system reports untagged traffic.
11803 static const int32_t UNTAGGED_TAG = 0;
11804
11805 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
11806
11807 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
11808 TestDelegate delegate;
Ryan Sleevib8449e02018-07-15 04:31:0711809 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
Paul Jensen60e45532018-02-19 16:04:1811810 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
11811 TRAFFIC_ANNOTATION_FOR_TESTS));
11812 EXPECT_EQ(SocketTag(), req->socket_tag());
11813 req->Start();
Wez2a31b222018-06-07 22:07:1511814 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1811815
11816 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
11817
11818 int32_t tag_val1 = 0x12345678;
11819 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
11820 old_traffic = GetTaggedBytes(tag_val1);
11821
11822 // Test specific tag value.
Ryan Sleevib8449e02018-07-15 04:31:0711823 req = default_context().CreateRequest(http_test_server()->GetURL("/"),
11824 DEFAULT_PRIORITY, &delegate,
11825 TRAFFIC_ANNOTATION_FOR_TESTS);
Paul Jensen60e45532018-02-19 16:04:1811826 req->set_socket_tag(tag1);
11827 EXPECT_EQ(tag1, req->socket_tag());
11828 req->Start();
Wez2a31b222018-06-07 22:07:1511829 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1811830
11831 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
11832}
11833#endif
11834
[email protected]7461a402011-03-24 23:19:5111835} // namespace net